2013-03-17 21 views
0

我已經嘗試按照下面的教程與PHP連接的Android,MySQL的:我怎樣才能糾正嚴重異常 - 異步任務

http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

但是我自己並按照本教程大部分用戶已經接近獲得力直接從教程下載的源文件運行應用程序時出現錯誤,然後單擊其中一個按鈕。

(看看評論部分 - 幾乎每個人都具有本教程的一個問題)

logcat的:

03-17 14:40:10.064: D/dalvikvm(2936): GC_CONCURRENT freed 177K, 5% free 7488K/7812K, paused 2ms+11ms, total 33ms 
03-17 14:40:16.294: D/dalvikvm(2936): GC_CONCURRENT freed 80K, 4% free 7856K/8140K, paused 3ms+2ms, total 26ms 
03-17 14:40:16.784: E/JSON Parser(2936): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject 
03-17 14:40:16.794: W/dalvikvm(2936): threadid=15: thread exiting with uncaught exception (group=0x41d42930) 
03-17 14:40:16.794: E/AndroidRuntime(2936): FATAL EXCEPTION: AsyncTask #5 
03-17 14:40:16.794: E/AndroidRuntime(2936): java.lang.RuntimeException: An error occured while executing doInBackground() 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at android.os.AsyncTask$3.done(AsyncTask.java:299) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at java.util.concurrent.FutureTask.run(FutureTask.java:239) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at java.lang.Thread.run(Thread.java:856) 
03-17 14:40:16.794: E/AndroidRuntime(2936): Caused by: java.lang.NullPointerException 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:98) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:1) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at android.os.AsyncTask$2.call(AsyncTask.java:287) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
03-17 14:40:16.794: E/AndroidRuntime(2936):  ... 3 more 
03-17 14:40:17.284: E/WindowManager(2936): Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42488ea0 V.E..... R.....ID 0,0-296,153} that was originally added here 
03-17 14:40:17.284: E/WindowManager(2936): android.view.WindowLeaked: Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42488ea0 V.E..... R.....ID 0,0-296,153} that was originally added here 
03-17 14:40:17.284: E/WindowManager(2936): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354) 
03-17 14:40:17.284: E/WindowManager(2936): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216) 
03-17 14:40:17.284: E/WindowManager(2936): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) 
03-17 14:40:17.284: E/WindowManager(2936): at android.app.Dialog.show(Dialog.java:281) 
03-17 14:40:17.284: E/WindowManager(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.onPreExecute(NewProductActivity.java:75) 
03-17 14:40:17.284: E/WindowManager(2936): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) 
03-17 14:40:17.284: E/WindowManager(2936): at android.os.AsyncTask.execute(AsyncTask.java:534) 
03-17 14:40:17.284: E/WindowManager(2936): at com.example.androidhive.NewProductActivity$1.onClick(NewProductActivity.java:55) 
03-17 14:40:17.284: E/WindowManager(2936): at android.view.View.performClick(View.java:4204) 
03-17 14:40:17.284: E/WindowManager(2936): at android.view.View$PerformClick.run(View.java:17355) 
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Handler.handleCallback(Handler.java:725) 
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Handler.dispatchMessage(Handler.java:92) 
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Looper.loop(Looper.java:137) 
03-17 14:40:17.284: E/WindowManager(2936): at android.app.ActivityThread.main(ActivityThread.java:5041) 
03-17 14:40:17.284: E/WindowManager(2936): at java.lang.reflect.Method.invokeNative(Native Method) 
03-17 14:40:17.284: E/WindowManager(2936): at java.lang.reflect.Method.invoke(Method.java:511) 
03-17 14:40:17.284: E/WindowManager(2936): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
03-17 14:40:17.284: E/WindowManager(2936): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
03-17 14:40:17.284: E/WindowManager(2936): at dalvik.system.NativeStart.main(Native Method) 




JAVA: NewProductActivity.java 


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://linkingmanager.zxq.net/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(url_create_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(), 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(); 
    } 

} 
} 


XML: add_product.xml 




<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<!-- Name Label --> 
<TextView android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Product Name" 
    android:paddingLeft="10dip" 
    android:paddingRight="10dip" 
    android:paddingTop="10dip" 
    android:textSize="17dip"/> 

<!-- Input Name --> 
<EditText android:id="@+id/inputName" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="5dip" 
    android:layout_marginBottom="15dip" 
    android:singleLine="true"/> 

<!-- Price Label --> 
<TextView android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Price" 
    android:paddingLeft="10dip" 
    android:paddingRight="10dip" 
    android:paddingTop="10dip" 
    android:textSize="17dip"/> 

<!-- Input Price --> 
<EditText android:id="@+id/inputPrice" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="5dip" 
    android:layout_marginBottom="15dip" 
    android:singleLine="true" 
    android:inputType="numberDecimal"/> 

<!-- Description Label --> 
<TextView android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Description" 
    android:paddingLeft="10dip" 
    android:paddingRight="10dip" 
    android:paddingTop="10dip" 
    android:textSize="17dip"/> 

<!-- Input description --> 
<EditText android:id="@+id/inputDesc" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="5dip" 
    android:layout_marginBottom="15dip" 
    android:lines="4" 
    android:gravity="top"/> 

<!-- Button Create Product --> 
<Button android:id="@+id/btnCreateProduct" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Create Product"/> 

</LinearLayout> 



JAVA: AllProductsActivity.java 


package com.example.androidhive; 

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

import org.apache.http.NameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.ListActivity; 
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.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 
public class AllProductsActivity extends ListActivity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    // Creating JSON Parser object 
    JSONParser jParser = new JSONParser(); 

    ArrayList<HashMap<String, String>> productsList; 

    // url to get all products list 
    private static String url_all_products = "http://linkingmanager.zxq.net/get_all_products.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_NAME = "name"; 

    // products JSONArray 
    JSONArray products = null; 

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


     // Hashmap for ListView 
     productsList = new ArrayList<HashMap<String, String>>(); 

     // Loading products in Background Thread 
     new LoadAllProducts().execute(); 

     // Get listview 
     ListView lv = getListView(); 

     // on seleting single product 
     // launching Edit Product Screen 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       // getting values from selected ListItem 
       String pid = ((TextView) view.findViewById(R.id.pid)).getText() 
         .toString(); 

       // Starting new intent 
       Intent in = new Intent(getApplicationContext(), 
         EditProductActivity.class); 
       // sending pid to next activity 
       in.putExtra(TAG_PID, pid); 

       // starting new activity and expecting some response back 
       startActivityForResult(in, 100); 
      } 
     }); 

    } 

    // 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(AllProductsActivity.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 name = c.getString(TAG_NAME); 

         // 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_NAME, name); 

         // adding HashList to ArrayList 
         productsList.add(map); 
        } 
       } else { 
        // no products found 
        // Launch Add New product Activity 
        Intent i = new Intent(getApplicationContext(), 
          NewProductActivity.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(
          AllProductsActivity.this, productsList, 
          R.layout.list_item, new String[] { TAG_PID, 
            TAG_NAME}, 
          new int[] { R.id.pid, R.id.name }); 
        // updating listview 
        setListAdapter(adapter); 
       } 
      }); 

     } 

    } 
} 


XML: all_products.xml 



<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical"> 
<!-- Main ListView 
    Always give id value as list(@android:id/list) 
--> 
<ListView 
    android:id="@android:id/list" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/> 

</LinearLayout> 
+2

沒有看代碼,聽起來像這個'教程'是一堆垃圾。我會停止使用它並尋找另一個。 – NickT 2013-03-17 19:09:58

+0

我認爲在構建JSONObject時,這與aysnc任務的關係不如未捕獲的異常。您需要發佈正在返回的字符串(或足夠大的示例)以及您嘗試構建JSONObject的代碼。 – 2013-03-17 19:10:25

+0

請不要浪費你的時間,嘗試修復一個破碎的教程和我們的時間再次問同樣的問題。 – Simon 2013-03-17 19:15:50

回答

0
Caused by: java.lang.NullPointerException 
03-17 14:40:16.794: E/AndroidRuntime(2936):  at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:98) 

在這條線,如果我不是錯

Log.d("Create Response", json.toString()); 

所以它意味着由於某種原因您在這裏得到空的

JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
       "POST", params); 

也許你的網址不正確。

+0

所以我應該用「http://linkingmanager.zxq.net/create_product.php」替換「創建響應」? – user2161499 2013-03-17 19:44:33

+0

我應該在哪裏更正URL? (在PHP文件或在Java?我已驗證,我可以訪問http://linkingmanager.zxq.net/create_product.php) – user2161499 2013-03-17 19:50:50