Android FOR LOOP with IF statement

advertisements

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.androi[email protected]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.androi[email protected]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);
                }
            });
            }

        }

}


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.