2015-03-31 178 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网络,它可能不会工作。没有路由表来处理请求。