2014-10-06 46 views
0

在公共類,我宣佈的Android FOR LOOP與IF語句

int content = 0; 
String content2; 

這一個適用於只有一排。我的問題是我想獲取所有使用的行,但它給了我錯誤。我怎樣才能將其轉換爲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.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 

這是我的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); 
       } 
      }); 
      } 

     } 

} 
+0

顯示您的logcat .. – Riser 2014-10-06 05:02:43

+1

我想寫出答案,但有很多錯誤...就像:'content = 0 + 1;'< - 這是什麼意思? – Martynas 2014-10-06 05:19:09

+0

你不能迭代listview並獲得所有的輸入,因爲listview回收視圖(http://stackoverflow.com/a/14108676/341998),你應該把你的輸入存儲在其他地方。 – Bracadabra 2014-10-06 05:19:25

回答

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,並相應地投。

+0

謝謝,它正在運行,但現在它只保存最後輸入的數據。它不是全部保存。我認爲我的問題是數組?我正在使用簡單的列表適配器。幫我 – Francis 2014-10-06 05:43:46

+0

@ user3255811改變'content = 0 + 1;'到'content = i;'並檢查 – 2014-10-06 05:50:27

+0

不工作它在我的mysql中存儲「2」。順便說一句,我在上面添加了我的java文件。請幫助我的老闆。 – Francis 2014-10-06 06:13:44

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

內容和內容2 = ALWAYS 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. 
+0

地獄!你的天使!謝了哥們 !我做的 。我做的!。我很抱歉,我造成了你的麻煩,但你仍然幫助我!我很抱歉很多很多錯誤!雖然我是新手。但感謝你! @Martynas。怎麼能謝謝你? – Francis 2014-10-06 07:10:48

+0

這是正確的答案!你提到的最後一個 – Francis 2014-10-06 07:13:09

+0

親愛的,沒有人出生就知道一切。如果它回答你的問題,請接受它。你沒有造成任何問題... – Martynas 2014-10-06 07:27:28