2013-12-13 86 views
0

我是一個在android編程中的新手。我正在嘗試創建一個應用程序,它將與Internet上的數據庫進行通信。作爲幫助,我正在使用androidhive的項目。 對於開始我想創建的應用程序將發送一些數據到本地主機上的數據庫。我正在使用WAMP。使用php mySQL連接android

運行我的應用程序後,並插入我想要存儲在數據庫上的數據,我收到了一堆異常和我的應用程序崩潰。 例如:

  1. E /緩存器的錯誤(545):錯誤轉換結果顯示java.lang.NullPointerException
  2. E/JSON解析器(545):錯誤解析數據org.json.JSONException:在輸入完
  3. E/AndroidRuntime的字符0(545):致命異常:的AsyncTask#1
  4. E/AndroidRuntime(545):了java.lang.RuntimeException:執行doInBackground()

而發生錯誤很多其他人例外...

我的PHP腳本(或任何你想要調用它們)工作正常,但我想這個問題是在JSONParser或其他Android活動的某處...我一直在尋找的解決方案,但我找不到它,或者我無法理解它。另外,我從androidhive下載了代碼,並且它在我的電腦上無法使用。類似的問題與我的項目

活動創建訂單(產品或其他):

package com.example.heywaiter; 

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{ 

    private ProgressDialog pDialog; 

JSONParser jsonParser = new JSONParser(); 
EditText inputTablle; 
EditText inputOrder; 
EditText inputQuantity; 
Button btnOrder; 

private static String url_create_product = "http://127.0.0.1/android_connect/create_product.php"; 
private static final String TAG_SUCCESS = "success"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.new_product); 

    inputTablle = (EditText) findViewById(R.id.inputTablle); 
    inputOrder = (EditText) findViewById(R.id.inputOrder); 
    inputQuantity = (EditText) findViewById(R.id.inputQuantity); 
    btnOrder = (Button) findViewById(R.id.btnOrder); 

    btnOrder.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      new CreateNewProduct().execute(); 
     } 
    }); 
} 

內部類:

class CreateNewProduct extends AsyncTask<String, String, String>{ 



    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(NewProductActivity.this); 
     pDialog.setMessage("Sending order..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... args) { 
     String tablle = inputTablle.getText().toString(); 
     String drink = inputOrder.getText().toString(); 
     String quantity = inputQuantity.getText().toString(); 

     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tablle", tablle)); 
     params.add(new BasicNameValuePair("drink", drink)); 
     params.add(new BasicNameValuePair("quantity", quantity)); 

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

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

     try{ 

      int success = json.getInt(TAG_SUCCESS); 

      if(success ==1){ 
       Intent i = new Intent(getApplicationContext(), MainActivity.class); 
       startActivity(i); 

       finish(); 
      }else{ 

      } 
     }catch(JSONException e){ 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     pDialog.dismiss(); 
    } 

} 

}

JSONParser

package com.example.heywaiter; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 

import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

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; 

} 
} 

另外,如果你需要我的androidManifest:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.heywaiter" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="14" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="com.example.heywaiter.Splash" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity 
      android:name="com.example.heywaiter.MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="com.example.heywaiter.MainActivity" /> 

       <category android:name="android.intent.category.DEFAULT" /> 
      </intent-filter> 
     </activity> 
     <activity 
      android:name=".NewProductActivity" 
      android:label="New Product"> 
     </activity> 
     <activity 
      android:name=".AllProductsActivity" 
      android:label="All Products" > 
     </activity> 
    </application> 
    <!-- Internet Permissions --> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
</manifest> 

在此先感謝! :)

回答

0

過了一段時間,我發現問題出在哪裏,我都不敢相信那是什麼..

當連接到本地主機代替:

private static String url_create_product = "http://127.0.0.1/android_connect/create_product.php"; 

在NewProductActivity.java類應用下面的代碼:

private static String url_all_products = "https://10.0.2.2/android_connect/create_product.php"; 

出於某種原因,你不能使用127.0.0.110.0.2.2一切都會好起來。

0

使用,對於保存到數據庫

nameValuePairs2 = new ArrayList<NameValuePair>(); 
    nameValuePairs2.add(new BasicNameValuePair("username",username)); 
    nameValuePairs2.add(new BasicNameValuePair("password",password)); 
try{ 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost(mainurl+"registration.php"); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       HttpResponse response = httpclient.execute(httppost); 
       String the_string_response = convertResponseToString(response); 
      // Toast.makeText(getApplicationContext(), "Response " + the_string_response, Toast.LENGTH_LONG).show(); 
      }catch(Exception e){ 
       // Toast.makeText(getApplicationContext(), "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show(); 
       // System.out.println("Error in http connection "+e.toString()); 
      }