带有IF语句的Android FOR LOOP

时间:2014-10-06 04:57:46

标签: android listview for-loop

在公开课下我宣布了

int content = 0;  
String content2;  

这只适用于一行。我的问题是我想使用for获取所有行,但它给了我错误。如何将其转换为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);
}

下面是我的for循环希望你会看到问题,因为我是android编程的新手。

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

这是我的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

这是我的Java文件的所有代码。我只是想要,如果Edittext = Textview,得分将增加到1.我在使用FOR LOOP获取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();

这个工作正常但只有一行。我把它作为评论,因为它正在发挥作用。

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

现在这是我的FOR LOOP让我头疼。

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

        }

}

2 个答案:

答案 0 :(得分:1)

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

首先,

更改

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

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

您必须查看xml中的元素,然后进行相应的转换。

答案 1 :(得分:0)

你犯了很多错误,我无法理解你到底想做什么。 首先这些意味着什么?

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 = 始终 1和0.这与:

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

如果您想增加content使用content++

另外为什么correct_answerTextView,后来为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);
}

要获得第二个位置,你必须增加它。在某处添加position++

最后你的for循环检查 xml中的correct_answer。是TextView还是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.