2014-05-09 41 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

相关问题