0

Under the public class I declared

int content = 0;  
String content2;  

This one works for only one row. My problem is I want to fetch all row using for but it gives me error. How can I convert this to FOR LOOP?

ListView listview = getListView();
int position = 0;
View angelC = listview.getChildAt(position);
inputAnswer = (EditText)angelC.findViewById(R.id.inputAnswer);
correct_answer = (TextView)angelC.findViewById(R.id.correct_answer);
if(inputAnswer.getText().toString().equals(correct_answer.getText().toString()) ){
    content = 0 + 1;
    content2 = Integer.toString(content);
}else{
  content = 0 + 0;
  content2 = Integer.toString(content);
}

Below is my for loop hope you'll see the problem because I am a newbie in android programming.

for (int i = 0; i < listview.getAdapter().getCount(); i++) {
    View angelC = listview.getChildAt(i);
    inputAnswer = (EditText) angelC.findViewById(R.id.inputAnswer);
    correct_answer = (TextView) angelC.findViewById(R.id.correct_answer);


  if(inputAnswer.getText().toString().equals(correct_answer.getText().toString()) ){
    content = 0 + 1;
    content2 = Integer.toString(content);
}else{
    content = 0 + 0;
    content2 = Integer.toString(content);
    }
}

This is my LOGCAT

FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
at com.example.androidhive.AnswerQuestionActivity$PassProduct.doInBackground(AnswerQuestionActivity.java:158)
at com.example.androidhive.AnswerQuestionActivity$PassProduct.doInBackground(AnswerQuestionActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 3 more
 Skipped 494 frames!  The application may be doing too much work on its main thread.
onDetachedFromWindow
Activity com.example.androidhive.AnswerQuestionActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41803fa8 V.E..... R.....ID 0,0-220,114} that was originally added here
android.view.WindowLeaked: Activity com.example.androidhive.AnswerQuestionActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41803fa8 V.E..... R.....ID 0,0-220,114} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:454)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:235)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
at android.app.Dialog.show(Dialog.java:282)
at com.example.androidhive.AnswerQuestionActivity$PassProduct.onPreExecute(AnswerQuestionActivity.java:123)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at android.view.View.performClick(View.java:4421)
at android.view.View$PerformClick.run(View.java:18190)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
 Activity com.example.androidhive.AnswerQuestionActivity has leaked IntentReceiver com.immersion.android.haptics.HapticFeedbackManager$HapticFeedbackBroadcastReceiver@417bfa78 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Activity com.example.androidhive.AnswerQuestionActivity has leaked IntentReceiver com.immersion.android.haptics.HapticFeedbackManager$HapticFeedbackBroadcastReceiver@417bfa78 that was originally registered here. Are you missing a call to unregisterReceiver()?
1at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:800)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:601)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1650)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1630)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1624)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:430)
at com.immersion.android.haptics.HapticFeedbackManager.setupPackageBroadcastReceiver(HapticFeedbackManager.java:564)
at com.immersion.android.haptics.HapticFeedbackManager.<init>(HapticFeedbackManager.java:108)
at com.immersion.android.HapticFeedbackManagerProxy.initialize(HapticFeedbackManagerProxy.java:90)
at com.immersion.android.HapticFeedbackManagerProxy.access$100(HapticFeedbackManagerProxy.java:30)
at com.immersion.android.HapticFeedbackManagerProxy$1$1.run(HapticFeedbackManagerProxy.java:71)
at java.lang.Thread.run(Thread.java:856)
10-06 13:08:51.374: I/Process(14572): Sending signal. PID: 14572 SIG: 9

This is all the code of my Java file. I just want that if the Edittext = Textview the score will increment to 1. And I have a problem using FOR LOOP to fetch all rows in mysql.

    package com.example.androidhive;



public class AnswerQuestionActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;
    //
    EditText inputLastName, inputFirstName, inputYear, inputCourse, inputAge;
    //list xml
    EditText inputAnswer;
    Button btnPass;
    TextView correct_answer;
    int content = 0;
    String content2;




    //OLD LOCAL ADDRESS 10.0.2.2
    static String server = ((NewQuestionActivity)getActivity()).server;
    private static String url_all_products = "http://"+server+"/android_quiz/get_all_products.php";
    private static String url_pass_product = "http://"+server+"/android_quiz/pass_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_QUESTION = "question";
    private static final String TAG_SELECT_A = "select_a";
    private static final String TAG_SELECT_B = "select_b";
    private static final String TAG_SELECT_C = "select_c";
    private static final String TAG_CORRECT_ANSWER = "correct_answer";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.student_listview);


        //EditText
        inputLastName = (EditText) findViewById(R.id.inputLastName);
        inputFirstName = (EditText) findViewById(R.id.inputFirstName);
        inputYear = (EditText) findViewById(R.id.inputYear); 
        inputCourse = (EditText) findViewById(R.id.inputCourse); 
        inputAge = (EditText) findViewById(R.id.inputAge);


        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        //TOAST MESSAGE ON START-UP
        Toast.makeText(this, "Put the letter of your answer in the whitebox", Toast.LENGTH_LONG).show();


        btnPass = (Button) findViewById(R.id.btnPass);
        btnPass.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            new PassProduct().execute();
        }
    });


}
    /**
     * Background Async Task to Create new product
     * */
    class PassProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AnswerQuestionActivity.this);
            pDialog.setMessage("Passing Answers..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Passing product
         * 
         * */


        protected String doInBackground(String... args) {
            String name = inputLastName.getText().toString() +" "+inputFirstName.getText().toString();
            String year_course = inputYear.getText().toString() +" - "+ inputCourse.getText().toString();
            String age = inputAge.getText().toString();

This is working fine but only for one row. I toggle it a comment because it's working.

ListView listview = getListView();
//          
//          int position = 0;
//          View angelC = listview.getChildAt(position);
//          inputAnswer = (EditText)angelC.findViewById(R.id.inputAnswer);
//          correct_answer = (TextView)angelC.findViewById(R.id.correct_answer);
//          if(inputAnswer.getText().toString().equals(correct_answer.getText().toString()) ){
//              
//          content = 0 + 1;
//          content2 = Integer.toString(content);
//          }else{
//              
//            content = 0 + 0;
//          content2 = Integer.toString(content);
//          }

Now this is my FOR LOOP that cause me a headache.

  for (int i = 0; i < listview.getAdapter().getCount(); i++) {
   View angelC = listview.getChildAt(i);
            inputAnswer = (EditText) angelC.findViewById(R.id.inputAnswer);
            correct_answer = (TextView) angelC.findViewById(R.id.correct_answer);
                   if(inputAnswer.getText().toString().equals(correct_answer.getText().toString()) ){

      //INCREMENT THE SCORE
        }else{

     // NO INCREMENT

        }



            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("year_course", year_course));
            params.add(new BasicNameValuePair("age", content2));


            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_pass_product,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), MainScreenActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

      }









    private static NewQuestionActivity getActivity() {
        // TODO Auto-generated method stub
        return null;
    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received 
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AnswerQuestionActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String question = c.getString(TAG_QUESTION);
                        String A = c.getString(TAG_SELECT_A);
                        String B = c.getString(TAG_SELECT_B);
                        String C = c.getString(TAG_SELECT_C);
                        String correct_answer = c.getString(TAG_CORRECT_ANSWER);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_QUESTION, question);
                        map.put(TAG_SELECT_A,"a. "+ A);
                        map.put(TAG_SELECT_B,"b. "+ B);
                        map.put(TAG_SELECT_C,"c. "+ C);
                        map.put(TAG_CORRECT_ANSWER, correct_answer);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewQuestionActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AnswerQuestionActivity.this, productsList, R.layout.student_question,
                            new String[] { TAG_PID, TAG_QUESTION, TAG_SELECT_A,TAG_SELECT_B,TAG_SELECT_C,TAG_CORRECT_ANSWER },
                            new int[] { R.id.pid, R.id.question, R.id.choice_a, R.id.choice_b, R.id.choice_c, R.id.correct_answer});
                    // updating listview
                    setListAdapter(adapter);
                }
            });
            }

        }

}
Francis
  • 11
  • 1
  • 5
  • 1
    I wanted to write the answer, but there are to many mistakes... Like: `content = 0 + 1;` <- what does this mean??? – Martynas Oct 06 '14 at 05:19
  • You can't just iterate listview and get all your input because listview recycle views (http://stackoverflow.com/a/14108676/341998), you should store your input somewhere else. – Bracadabra Oct 06 '14 at 05:19
  • @Martynas it's the score = to 0. so if the inputanswer is equal to correct answer it will increment. – Francis Oct 06 '14 at 05:24
  • I also used simple listview adapter not a custom. – Francis Oct 06 '14 at 05:26
  • IT WILL NOT INCREMENT!!! 0+1 is ALWAYS 1 – Martynas Oct 06 '14 at 05:40
  • @Martynas I am sorry. How can I correct that? Please help me. – Francis Oct 06 '14 at 05:49
  • I do not understand how you can work with mySQL and write such a program and do not know how to simply increment like `content++;`. Each time it runs over this line it will add 1 to content – Martynas Oct 06 '14 at 06:36

2 Answers2

1
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

Firstly,

Change

correct_answer = (EditText) angelC.findViewById(R.id.correct_answer);

to

correct_answer = (TextView) angelC.findViewById(R.id.correct_answer);

You have to see what element is there in your xml, and cast accordingly.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
  • Thanks, it's running but now it only save the last inputted data. It is not saving all. I think my problem is array? I'm using simple list adapter. Help me – Francis Oct 06 '14 at 05:43
  • @user3255811 change `content = 0 + 1;` to `content = i;` and check – MysticMagicϡ Oct 06 '14 at 05:50
  • not working it stored "2" in my mysql. By the way I added my java file above. Please help me boss. – Francis Oct 06 '14 at 06:13
0

You are doing so many mistakes that i can't understand what the hell you want to do. First of all what these means???

if(inputAnswer.getText().toString().equals(correct_answer.getText().toString()) ){

    content = 0 + 1;
    content2 = Integer.toString(content);
    }else{

      content = 0 + 0;
    content2 = Integer.toString(content);

content and content2 = ALWAYS 1 and 0. This is the same as:

if(inputAnswer.getText().toString().equals(correct_answer.getText().toString()) ){
    content2 = "1";
    }else{
    content2 = "0";

If you want to increment content use content++

Also why correct_answer is TextView and later it is EditText ???

ListView listview = getListView();

int position = 0;
View angelC = listview.getChildAt(position);
inputAnswer = (EditText)angelC.findViewById(R.id.inputAnswer);
correct_answer = (TextView)angelC.findViewById(R.id.correct_answer);
if(inputAnswer.getText().toString().equals(correct_answer.getText().toString()) ){

content++;
content2 = Integer.toString(content);
}

Also to have second position you have to increment it. Somewhere add position++

And finally your for loop Check the correct_answer in your xml. Is it TextView or EditText:

for (int i = 0; i < listview.getAdapter().getCount(); i++) {
View angelC = listview.getChildAt(i);
        inputAnswer = (EditText) angelC.findViewById(R.id.inputAnswer);
        correct_answer = (TextView) angelC.findViewById(R.id.correct_answer);
               if(inputAnswer.getText().toString().equals(correct_answer.getText().toString()) ){

  score++;//INCREMENT THE SCORE
    }
//    else{} //if you don't need to increment don't use else.
Martynas
  • 627
  • 2
  • 8
  • 28
  • What the Hell ! YOUR AN ANGEL! THANKS MATE ! I did it . I did it!. I'm sorry that i caused you trouble but you still help me! I am sorry for many many mistake ! I am NEWBIE though . BUT THANKS TO YOU ! @Martynas. How can thank you? – Francis Oct 06 '14 at 07:10
  • That is the correct answer ! the last one that you mentioned – Francis Oct 06 '14 at 07:13
  • Dear, nobody's born knowing everything. If it answered your question accept it. And you didn't caused any problem... – Martynas Oct 06 '14 at 07:27
  • Thanks ! But I found another problem it's only working in 3 rows. but when i add another question. It gives me error. T______T – Francis Oct 07 '14 at 03:52
  • Could you @Francis add all your class so we could see everything. Now you give piece by piece and it is not certain what is wrong – Martynas Oct 07 '14 at 04:46
  • Maybe you should add if statment to check if the value is not equal to null? what kind of error are you getting? Make your question understandable – Martynas Oct 07 '14 at 05:03
  • I found out that it's working in EMULATOR but when in android device it's really not working when I have more than 3 rows in mysql. By the way I am using connectify hotspot. I found in Logcat (FATAL EXCEPTION: main java.lang.NullPointerException). Sometimes it's running in android device but sometimes not. I think the problem is in the wifi connection. – Francis Oct 08 '14 at 02:48
  • If you get `NullPointerException` check the LogCat. It shows in what line the `NullPointerException` was. If you do not see lines in your code go to Windows>Preferences>General>Editors>Text Editors and check Show line number – Martynas Oct 08 '14 at 05:18