2015-04-20 2 views
2

Я пытаюсь создать приложение, которое работает на фоне парсера json, но я все время получаю ошибку при каждом подключении. я много раз пытался использовать проект очистки, но это не работает.java.lang.noclassdeffounderror android app

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Button startButton = (Button) findViewById(R.id.button); 
startButton.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 

     Intent intent = new Intent(MainActivity.this, QuizActivity.class); 
     startActivity(intent); 
     } 
    }); 
} 

Это мой MainActivity.class

package com.fyp.please; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.BasicHttpParams; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.RadioButton; 
import android.widget.RadioGroup; 
import android.widget.TextView; 
import android.widget.Toast; 

public class QuizActivity extends ActionBarActivity { 
private TextView quizQuestion; 

private RadioGroup radioGroup; 
private RadioButton optionOne; 
private RadioButton optionTwo; 
private RadioButton optionThree; 
private RadioButton optionFour; 

private int currentQuizQuestion; 
private int quizCount; 

private QuizWrapper firstQuestion; 
private List<QuizWrapper> parsedObject; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_quiz); 

    quizQuestion = (TextView) findViewById(R.id.quiz_question); 

    radioGroup = (RadioGroup) findViewById(R.id.radioGroup); 
    optionOne = (RadioButton) findViewById(R.id.radio0); 
    optionTwo = (RadioButton) findViewById(R.id.radio1); 
    optionThree = (RadioButton) findViewById(R.id.radio2); 
    optionFour = (RadioButton) findViewById(R.id.radio3); 

    Button previousButton = (Button) findViewById(R.id.previousquiz); 
    Button nextButton = (Button) findViewById(R.id.nextquiz); 

    AsyncJsonObject asyncObject = new AsyncJsonObject(); 
    asyncObject.execute(""); 

    nextButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      int radioSelected = radioGroup.getCheckedRadioButtonId(); 
      int userSelection = getSelectedAnswer(radioSelected); 

      int correctAnswerForQuestion = firstQuestion.getCorrectAnswer(); 

      if (userSelection == correctAnswerForQuestion) { 
       // correct answer 
       Toast.makeText(QuizActivity.this, 
         "You got the answer correct", Toast.LENGTH_LONG) 
         .show(); 
       currentQuizQuestion++; 
       if (currentQuizQuestion >= quizCount) { 
        Toast.makeText(QuizActivity.this, 
          "End of the Quiz Questions", Toast.LENGTH_LONG) 
          .show(); 
        return; 
       } else { 
        firstQuestion = parsedObject.get(currentQuizQuestion); 
        quizQuestion.setText(firstQuestion.getQuestion()); 
        String[] possibleAnswers = firstQuestion.getAnswers() 
          .split(","); 
        uncheckedRadioButton(); 
        optionOne.setText(possibleAnswers[0]); 
        optionTwo.setText(possibleAnswers[1]); 
        optionThree.setText(possibleAnswers[2]); 
        optionFour.setText(possibleAnswers[3]); 
       } 
      } else { 
       // failed question 
       Toast.makeText(QuizActivity.this, 
         "You chose the wrong answer", Toast.LENGTH_LONG) 
         .show(); 
       return; 
      } 
     } 
    }); 
    previousButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      currentQuizQuestion--; 
      if (currentQuizQuestion < 0) { 
       return; 
      } 
      uncheckedRadioButton(); 
      firstQuestion = parsedObject.get(currentQuizQuestion); 
      quizQuestion.setText(firstQuestion.getQuestion()); 
      String[] possibleAnswers = firstQuestion.getAnswers() 
        .split(","); 
      optionOne.setText(possibleAnswers[0]); 
      optionTwo.setText(possibleAnswers[1]); 
      optionThree.setText(possibleAnswers[2]); 
      optionFour.setText(possibleAnswers[3]); 
     } 
    }); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_quiz, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

private class AsyncJsonObject extends AsyncTask<String, Void, String> { 

    private ProgressDialog progressDialog; 

    @Override 
    protected String doInBackground(String... params) { 

     HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams()); 
     HttpPost httpPost = new HttpPost(
       "http://192.168.1.5/Android_Quiz/index1.php"); 
     String jsonResult = ""; 

     try { 
      HttpResponse response = httpClient.execute(httpPost); 
      jsonResult = inputStreamToString(
        response.getEntity().getContent()).toString(); 
      System.out.println("Returned Json object " 
        + jsonResult.toString()); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return jsonResult; 
    } 

    @Override 
    protected void onPreExecute() { 
     // TODO Auto-generated method stub 
     super.onPreExecute(); 
     progressDialog = ProgressDialog.show(QuizActivity.this, 
       "Downloading Quiz", "Wait....", true); 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     progressDialog.dismiss(); 
     System.out.println("Resulted Value: " + result); 
     parsedObject = returnParsedJsonObject(result); 
     if (parsedObject == null) { 
      return; 
     } 
     quizCount = parsedObject.size(); 
     firstQuestion = parsedObject.get(0); 

     quizQuestion.setText(firstQuestion.getQuestion()); 
     String[] possibleAnswers = firstQuestion.getAnswers().split(","); 
     optionOne.setText(possibleAnswers[0]); 
     optionTwo.setText(possibleAnswers[1]); 
     optionThree.setText(possibleAnswers[2]); 
     optionFour.setText(possibleAnswers[3]); 
    } 

    private StringBuilder inputStreamToString(InputStream is) { 
     String rLine = ""; 
     StringBuilder answer = new StringBuilder(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

     try { 
      while ((rLine = br.readLine()) != null) { 
       answer.append(rLine); 
      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return answer; 
    } 
} 

private List<QuizWrapper> returnParsedJsonObject(String result) { 

    List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>(); 
    JSONObject resultObject = null; 
    JSONArray jsonArray = null; 
    QuizWrapper newItemObject = null; 

    try { 
     resultObject = new JSONObject(result); 
     System.out.println("Testing the water " + resultObject.toString()); 
     jsonArray = resultObject.optJSONArray("quiz_questions"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    for (int i = 0; i < jsonArray.length(); i++) { 
     JSONObject jsonChildNode = null; 
     try { 
      jsonChildNode = jsonArray.getJSONObject(i); 
      int id = jsonChildNode.getInt("id"); 
      String question = jsonChildNode.getString("question"); 
      String answerOptions = jsonChildNode 
        .getString("possible_answers"); 
      int correctAnswer = jsonChildNode.getInt("correct_answer"); 
      newItemObject = new QuizWrapper(id, question, answerOptions, 
        correctAnswer); 
      jsonObject.add(newItemObject); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
    return jsonObject; 
} 

private int getSelectedAnswer(int radioSelected) { 

    int answerSelected = 0; 
    if (radioSelected == R.id.radio0) { 
     answerSelected = 1; 
    } 
    if (radioSelected == R.id.radio1) { 
     answerSelected = 2; 
    } 
    if (radioSelected == R.id.radio2) { 
     answerSelected = 3; 
    } 
    if (radioSelected == R.id.radio3) { 
     answerSelected = 4; 
    } 
    return answerSelected; 
} 

private void uncheckedRadioButton() { 
    optionOne.setChecked(false); 
    optionTwo.setChecked(false); 
    optionThree.setChecked(false); 
    optionFour.setChecked(false); 
    } 

} 

это моя викторина активность.

04-20 12:44:06.200: W/dalvikvm(924): Unable to resolve superclass of Lcom/fyp/please/QuizActivity; (7) 
04-20 12:44:06.200: W/dalvikvm(924): Link of class 'Lcom/fyp/please/QuizActivity;' failed 
04-20 12:44:06.210: D/AndroidRuntime(924): Shutting down VM 
04-20 12:44:06.250: W/dalvikvm(924): threadid=1: thread exiting with uncaught exception (group=0xb2af4ba8) 
04-20 12:44:06.330: E/AndroidRuntime(924): FATAL EXCEPTION: main 
04-20 12:44:06.330: E/AndroidRuntime(924): Process: com.fyp.please, PID: 924 
04-20 12:44:06.330: E/AndroidRuntime(924): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.fyp.please/com.fyp.please.QuizActivity}: java.lang.ClassNotFoundException: Didn't find class "com.fyp.please.QuizActivity" on path: DexPathList[[zip file "/data/app/com.fyp.please-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.fyp.please-2, /system/lib]] 
04-20 12:44:06.330: E/AndroidRuntime(924): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121) 
04-20 12:44:06.330: E/AndroidRuntime(924): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
04-20 12:44:06.330: E/AndroidRuntime(924): at android.app.ActivityThread.access$800(ActivityThread.java:135) 
04-20 12:44:06.330: E/AndroidRuntime(924): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
04-20 12:44:06.330: E/AndroidRuntime(924): at android.os.Handler.dispatchMessage(Handler.java:102) 

LogCat Window.

Заранее спасибо

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.fyp.please" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="10" 
     android:targetSdkVersion="19" /> 

    <uses-permission android:name="android.permission.INTERNET"/> 

     <application 
      android:allowBackup="true" 
      android:icon="@drawable/ic_launcher" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme" > 
      <activity 
       android:name=".MainActivity" 
       android:label="@string/app_name" > 
       <intent-filter> 
        <action android:name="android.intent.action.MAIN" /> 

        <category android:name="android.intent.category.LAUNCHER" /> 
       </intent-filter> 
      </activity> 
      <activity 
       android:name="com.fyp.please.QuizActivity" 
       android:label="@string/title_activity_quiz" > 

       <intent-filter> 
        <action android:name="com.fyp.please.QUIZACTIVITY" /> 

        <category android:name="android.intent.category.DEFAULT" /> 
       </intent-filter> 

      </activity> 
     </application> 

    </manifest> 

манифеста: - Вот это манифест, я попытался его без намерения Inflater в деятельности по умолчанию, но он не работал :(

+0

Является ли ваш класс там в вашем манифесте Android? – Exception

+0

Вы попробовали [this] (http://stackoverflow.com/questions/19523167/android-classnotfoundexception-didnt-find-class-on-path/22652153#22652153)? – Exception

+1

да пробовал :(но не помог в моем случае –

ответ

0

Либо сделать -

Intent intent = new Intent(MainActivity.this, QuizActivity.class); 
intent.setAction("com.fyp.please.QUIZACTIVITY"); 
startActivity(intent); 

Или

<activity android:name="com.fyp.please.QuizActivity" 
      android:label="@string/title_activity_quiz" > 

</activity> 

Очистить & построить проект. удалите предыдущую установленную копию с тестового устройства/avd. затем снова запустите.

+0

оба не сработали :( –

0

Убедитесь, что ваша исходная папка, ваши зависимости от android и 'libs' экспортированы.

Вы можете отредактировать свой путь к классу и добавить экспортированные значения = "true" в значения или увидеть на Eclipse: Правая кнопка> Путь сборки ..> настроить путь сборки, в закладке «Заказ и экспорт» вы можете установить эти значения.

Затем повторите сборку проекта.

+0

Извините, я не понял ваш ответ. Не могли бы вы рассказать, как это связано с папкой «libs»? –

+0

Извините, я misunterprited ваш вопрос, ваша деятельность в вашей исходной папке или в банке или в Android-проекте? –

+0

Его не мой вопрос вообще :) Хотя я считаю, мы не можем поместить файл .java в папку libs, можно ли? –