尝试通过PHP将Android Studio连接到MySQL数据库

时间:2015-03-31 05:46:28

标签: java php android mysql android-asynctask

我有一个简单的表单,填写时应该使用php将数据插入数据库(localhost)。 当我点击按钮时,它说应用程序名称不幸停止工作。

这是我的代码

主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 Class

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)


2 个答案:

答案 0 :(得分:0)

在这里,

json = sb.toString();

确保您的sb对象不为空。

答案 1 :(得分:0)

所以你应该注意到&#34; localhost&#34;是运行脚本或Web服务器的设备的名称。如果你说&#34; localhost&#34;在您的Android设备上,它可能会尝试在您的Android设备上找到运行的服务器。

如果您在计算机上运行Web服务器,则您的网络将为该计算机分配IP地址。查看您的网络设置,然后告诉您的Android应用程序地址是什么...而不是&#34; localhost&#34;

此外,如果您在网络上使用DHCP,则会重新分配您的计算机(可能还有您的手机)。如果您的计算机获得新的IP地址,则无法正常工作。

此外,如果您的手机在同一个网络上使用WiFi,那么你很好。如果你切换到4G或其他WiFi网络,它可能不会工作。没有路由表来处理请求。

相关问题