2014-05-09 72 views
0

我是新從Android連接到PHP。 所以這裏是我的代碼:如何解決這個問題:嚴重異常的AsyncTask#1了java.lang.RuntimeException時出錯,執行doInBackground()

package com.example.androidhive; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 


public class tesMainScreen extends Activity{ 

    Button btnViewProducts; 
    Button btnNewProduct; 

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

     // Buttons 
     btnViewProducts = (Button) findViewById(R.id.btnViewProducts); 
     btnNewProduct = (Button) findViewById(R.id.btnCreateProduct); 

     // view products click event 
     btnViewProducts.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       // Launching All products Activity 
       Intent i = new Intent(getApplicationContext(), AllProductsActivity.class); 
       startActivity(i); 

      } 
     }); 

     // view products click event 
     btnNewProduct.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       // Launching create new product activity 
       Intent i = new Intent(getApplicationContext(), NewProductActivity.class); 
       startActivity(i); 

      } 
     }); 
    } 
} 

而這正是doinBackground存在:

package com.example.androidhive; 

import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 

public class NewProductActivity extends Activity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    JSONParser jsonParser = new JSONParser(); 
    EditText inputName; 
    EditText inputPrice; 
    EditText inputDesc; 

    // url to create new product 
    private static String url_create_product = "http://10.0.2.2/android_connect/create_product.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 

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

     // Edit Text 
     inputName = (EditText) findViewById(R.id.inputName); 
     inputPrice = (EditText) findViewById(R.id.inputPrice); 
     inputDesc = (EditText) findViewById(R.id.inputDesc); 

     // Create button 
     Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct); 

     // button click event 
     btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       // creating new product in background thread 
       new CreateNewProduct().execute(); 
      } 
     }); 
    } 

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

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

     /** 
     * Creating product 
     * */ 
     protected String doInBackground(String... args) { 
      String name = inputName.getText().toString(); 
      String price = inputPrice.getText().toString(); 
      String description = inputDesc.getText().toString(); 

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

      // getting JSON Object 
      // Note that create product url accepts POST method 
      JSONObject json = jsonParser.makeHttpRequest("{http://10.0.2.2/android_connect/create_product.php}", 
        "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(), AllProductsActivity.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(); 
     } 

    } 
} 

它有很多錯誤的logcat的:

- 05-09 10:56:44.007: ERROR/AndroidRuntime(456): FATAL EXCEPTION: AsyncTask #1 
- 05-09 10:56:45.207: ERROR/WindowManager(456): Activity com.example.androidhive.NewProductActivity has leaked window [email protected] that was originally added here 
- 05-09 10:56:46.447: ERROR/InputDispatcher(61): channel '4070d668 com.example.androidhive/com.example.androidhive.tesMainScreen (server)' ~ Consumer closed input channel or an error occurred. events=0x8 

所以請幫助我的感謝。

+0

試着這個'if(success == 1){pDialog.dismiss(); }'和除去'pDialog.dismiss();''從onPostExecute(.......)' –

+0

不要調用'startActivity(ⅰ)'和'光潔度()''doInBackground(字符串內功能.. 。args)'。從'doInBackground(String ... args)'以字符串的形式返回信息,然後根據信息的值在'onPostExecute(String info)'中採取行動。 – Shahidul

+0

嘗試過,仍然錯誤,任何方法呢? – stevian12

回答

0

調用下面的東西放在onPostExecute: -

   Intent i = new Intent(getApplicationContext(), AllProductsActivity.class); 
       startActivity(i); 

       // closing this screen 
       finish(); 

檢查解僱onPostExecute

 if(dialog != null && dialog.isShowing()) 
      dialog.dismiss(); 

UI元素只能從UI線程進行更新。使用一個異步任務做背景的話,並修改onPostExecute的UI,它運行在UI線程上

+0

仍然錯誤,任何方法呢? – stevian12

+0

什麼樣的錯誤? – duggu

+0

相同,這是11月5日至9日:26:43.417:ERROR/AndroidRuntime(637):致命異常:的AsyncTask#1 11月5日至9日:26:43.417:ERROR/AndroidRuntime(637):了java.lang.RuntimeException:一個執行doInBackground()時發生錯誤 – stevian12

0

此錯誤:

Activity [...] has leaked window [email protected] that was originally added here

是因爲你試圖發動另一ActivityDialog仍呈現。您試圖從onPostExecute它是正確的方式dismiss它,但是,你調用一個新IntentdoInBackground推出的新活動。然後,系統無法訪問onPostExecute,因爲您不從doInBackground發送任何內容。
更改方法如下:

protected String doInBackground(String... args) { 
    String isLoaded; 
    // ... 
    try { 
     int success = json.getInt(TAG_SUCCESS); 
     if (success == 1) { 
      // success: return a string value "success" 
      isLoaded = "Success"; 
     } else { 
      // failed: return a string value "failed" 
      isLoaded = "Failed"; 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    // return this String value to onPostExecute 
    return isLoaded; 
} 

// then retrieve this value by param "file_url" 
protected void onPostExecute(String file_url) { 
    // dismiss the dialog once done 
    pDialog.dismiss(); 
    if(file_url.equals("Success") { 
     // success: launch another activity 
     Intent i = new Intent(NewProductActivity.this, AllProductsActivity.class); 
     startActivity(i); 
     NewProductActivity.this.finish(); 
    } else if(file_url.equals("Failed") { 
     // failed: do something 
     Toast.makeText(NewProductActivity.this, "An error occurred...", Toast.LENGTH_SHORT).show(); 
    } 
} 

另一件事,你可以調用從(或onDestroydismiss方法,在用戶的情況下,退出你的應用程序。如果他回來,你只需要檢索它:

@Override 
public void onPause(){ 
    super.onPause(); 
    if(pDialog != null) 
     pDialog.dismiss(); 
} 
+0

仍然顯示相同的錯誤。任何其他方法? – stevian12

+0

我認爲你需要改變'getApplicationContext',我猜是附加到上下文'tesMainScreen'而不是'NewProductActivity'類。在tesMainScreen中爲'Intents'做同樣的事情。看我的編輯。 – Fllo

+0

也@ stevian12,對於'InputDispatcher'錯誤,我真的不知道如何解決這個問題,但[this thread](https://groups.google.com/forum/#!topic/android-developers/CSGPbZHaD7s)可能會幫助和[這一個](http://stackoverflow.com/a/14672742/2668136)。 – Fllo

相關問題