2015-03-31 174 views
-1

我有一個簡單的表單,填寫時應該使用php將數據插入數據庫(localhost)。 當我點擊按鈕時,它說應用程序名稱不幸停止工作。嘗試通過PHP將Android Studio連接到MySQL數據庫

這裏是我的代碼

主要的Java類

public class MainActivity extends ActionBarActivity { 



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

// url to create new product 
private static String url_create_product = "http://localhost/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.activity_main); 

    // 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 
    * */ 


    /** 
    * 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) { 



       finish(); 
      } else { 
       // failed to create product 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 



} 

JSONParser類

public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

// function get json from url 
// by making HTTP POST or GET mehtod 
public JSONObject makeHttpRequest(String url, String method, 
            List<NameValuePair> params) { 

    // Making HTTP request 
    try { 

     // check for request method 
     if(method == "POST"){ 
      // request method is POST 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     }else if(method == "GET"){ 
      // request method is GET 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      String paramString = URLEncodedUtils.format(params, "utf-8"); 
      url += "?" + paramString; 
      HttpGet httpGet = new HttpGet(url); 

      HttpResponse httpResponse = httpClient.execute(httpGet); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 
     } 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 

主要活動(包含表單)

<?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="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="Age" 
    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="Email" 
    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="Sign Up"/> 

</LinearLayout> 

我的清單

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="cambiopune.onlinedatabase" > 

<uses-permission android:name="android.permission.INTERNET" /> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
     <activity android:name=".JSONParser" /> 
    </activity> 

    </application> 

</manifest> 

,我得到的按鈕的日誌錯誤點擊

03-31 11:04:19.290 20660-20696/cambiopune.onlinedatabase E/Buffer Error﹕    Error converting result java.lang.NullPointerException: lock == null 

    03-31 11:04:19.290 20660-20696/cambiopune.onlinedatabase E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of 

    03-31 11:04:19.297 20660-20696/cambiopune.onlinedatabase E/AndroidRuntime﹕` enter code here` FATAL EXCEPTION: AsyncTask #5 
Process: cambiopune.onlinedatabase, PID: 20660 
java.lang.RuntimeException: An error occured while executing    doInBackground() 
     at android.os.AsyncTask$3.done(AsyncTask.java:300) 
     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 
     at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 
     at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
     at java.lang.Thread.run(Thread.java:818) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference 
     at    cambiopune.onlinedatabase.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:106) 
     at cambiopune.onlinedatabase.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:79) 
     at android.os.AsyncTask$2.call(AsyncTask.java:288) 
     at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
       at   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
       at   java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
        at java.lang.Thread.run(Thread.java:818) 


+0

因此,您的手機上實際上已經運行了MySQL數據庫和PHP服務器?理論上,應用程序的「本地主機」將成爲設備本身。只是試圖驗證您的問題的上下文... – Jim 2015-03-31 06:22:16

+0

我有一個MySQL數據庫在phpMyAdmin通過我的電腦。就像我在電腦上通過瀏覽器訪問數據庫一樣,同時我在手機上運行應用程序。 – MihirK98 2015-04-01 06:36:14

回答

0

這裏,

json = sb.toString(); 

確保你的sb對象不爲null。

+0

我如何確保它不爲空? – MihirK98 2015-04-01 06:31:58

+0

查看天氣情況,您將獲得該服務的有效回覆 – 2015-04-01 07:20:20

0

所以你應該注意到,「localhost」是運行腳本或web服務器的設備的名稱。如果您在Android設備上說「localhost」,它可能會嘗試查找您的Android設備上運行的服務器。

如果您在計算機上運行Web服務器,則您的網絡將爲該計算機分配一個IP地址。看看你的網絡設置,然後告訴你的Android應用程序什麼地址是...而不是「localhost」

另外,如果你在你的網絡上使用DHCP,你的電腦(也可能是你的電話) -assigned。如果您的計算機獲取新的IP地址,則不起作用。另外,如果你的手機在同一個網絡上使用WiFi,你很好。如果你切換到4G或其他WiFi網絡,它可能不會工作。沒有路由表來處理請求。