2

I am trying to make an app that work on json parser background but i keep getting error on every single attmpt. i tried using cleaning project a lot of times but that doesn't work.

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);
        }
    });
}

This is my 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);
    }

}

this is my Quiz Activity.

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.

Thanks in Advance

<?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>

Manifest :- Here it is the manifest, i tried it without intent inflater in Default activity but it didn't worked :(

Zeeshan Sardar
  • 235
  • 3
  • 15

2 Answers2

0

Either do -

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

Or

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

 </activity>

Clean & build the project. uninstall the previous installed copy from testing device/avd. then run again.

Amit K. Saha
  • 5,871
  • 2
  • 27
  • 35
0

Make sure your source folder, your android dependencies and 'libs' are exported.

You can edit your classpath and add exported="true" to the values or see on Eclipse: Right button> Build path.. > configure build path, under the tab 'Order and Export' you can set this values.

Then re build the project.

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
  • Sorry, I failed to understand your answer. Could you please share how is it related to "libs" folder? – Amit K. Saha Apr 20 '15 at 19:47
  • Sorry, i misunterprited your question, is your Activity in your source folder or in a jar or in a Android project? – Marcos Vasconcelos Apr 20 '15 at 19:49
  • Its not my question at all :). Though I believe, we can't put .java file in libs folder, can we? – Amit K. Saha Apr 20 '15 at 19:50
  • No, but we can put compiled jar files into the libs folder, and the .class will be inside the jar and can be used in your project. – Marcos Vasconcelos Apr 20 '15 at 19:51
  • See your error "04-20 12:44:06.200: W/dalvikvm(924): Unable to resolve superclass of Lcom/fyp/please/QuizActivity; (7)" you may be missing export the ActionBarCompat library – Marcos Vasconcelos Apr 20 '15 at 19:53
  • Activity in src folder @MArcos – Zeeshan Sardar Apr 20 '15 at 19:58
  • Build path.. > configure build path, under the tab 'Order and Export' you can set this values to what? – Zeeshan Sardar Apr 20 '15 at 20:16
  • To exported, everything must be exported – Marcos Vasconcelos Apr 20 '15 at 20:26
  • When i did this, no i am receiving this "[2015-04-21 01:36:04 - Dex Loader] Unable to execute dex: Multiple dex files define Landroid/support/v7/app/ActionBar$Callback; [2015-04-21 01:36:04 - Please] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Landroid/support/v7/app/ActionBar$Callback;" – Zeeshan Sardar Apr 20 '15 at 20:36
  • Thanks for you help @MarcosVasconcelos but didn't worked – Zeeshan Sardar Apr 20 '15 at 20:53
  • In this case, probably you have the support.jar added twice in your project, check if you have one at any "android library project" that you are using. If not, remove the jar from the build path since it will be auto handled by android build while its at libs folder – Marcos Vasconcelos Apr 22 '15 at 22:45