数据未插入远程数据库

时间:2013-06-03 13:06:37

标签: android

我正在尝试将数据插入到我的远程数据库中。但它显示了Http Connection异常。

以下是带有清单文件的三个类和PHP文件:

清单文件

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

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

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

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

</manifest>

这是我的ConnectBase类

package com.example.remotedatabase;

import android.app.Activity;

public class ConnectBase extends Activity{

 public static String link = "http://127.0.1.1:8080/androiddatabase/test.php";

}

这是我的CustomHttpClient类:

package com.example.remotedatabase;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 2000 * 1000; // milliseconds

/** Single instance of our HttpClient */
private static HttpClient mHttpClient;

/**
 * Get our single instance of our HttpClient object.
 *
 * @return an HttpClient object with connection parameters set
 */
private static HttpClient getHttpClient() {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
    return mHttpClient;
}

/**
 * Performs an HTTP Post request to the specified url with the
 * specified parameters.
 *
 * @param url The web address to post the request to
 * @param postParameters The parameters to send via the request
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * Performs an HTTP GET request to the specified url.
 *
 * @param url The web address to post the request to
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(url));
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
}

这是我的主要活动类:

  package com.example.remotedatabase;

    import java.util.ArrayList;

    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;



    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class GtugBase extends Activity {

    //  @Override
    //  protected void onCreate(Bundle savedInstanceState) {
    //      super.onCreate(savedInstanceState);
    //      setContentView(R.layout.main);
    //      
         /** Called when the activity is first created. */
        Button btnAdd;
        EditText txtFirstname,txtLastname;
        String status,error;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            btnAdd = (Button)findViewById(R.id.button1);
            txtFirstname = (EditText)findViewById(R.id.editFirstname);
            txtLastname = (EditText)findViewById(R.id.editLastname);


            /* ** Onclick of the add button ** */
            btnAdd.setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    /* Collect values from EditText */
                    String firstName = txtFirstname.getText().toString();
                    String lastName = txtFirstname.getText().toString();
                    /* Send Values to Method */
                    SendToPhpFile(firstName,lastName);
                }

            });




        }

        protected void SendToPhpFile(String firstName, String lastName) {
            ArrayList<NameValuePair> pp = new ArrayList<NameValuePair>();

            /* In case you are having many php functions, this helps you    
            to select the function you want to send parameters to.       
            For example here i will be sending values to the "add" function */

            pp.add(new BasicNameValuePair("whichfunction", "AddUser"));



            /* Add values to arraylist */
            pp.add(new BasicNameValuePair("firstname", firstName));
            pp.add(new BasicNameValuePair("lastname", lastName));


            /* With the help of the HttpClient Class we send all parameter     
             to the php script. check ConnectBase.java for the location   */
                    try{
                status = "";
                status = CustomHttpClient.executeHttpPost(ConnectBase.link, pp);
                String res=status.toString();
                res= res.replaceAll("\\s+","");

                /* Depending on value you return if insert was successful */
                    if(res.equals("1")){
                        Toaster("Data successfully added.");
                    }else{
                        Toaster(status);
                    }
                }catch(Exception e){
                    Toaster("Data successfully added oh really: " + e.toString());
                }

        }
        public void Toaster(String string){
            Toast.makeText(this, string,Toast.LENGTH_LONG).show();   

        }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.gtug_base, menu);
        return true;
    }
    }

这是我的php文件::

 <?php
    /*  Database connection  */
    mysql_connect("localhost","root","");
    mysql_select_db("androiddatabase");

    /*  Get the value in the whichfunction parameter
         sent from the android application which will
         determine the function to call.   */

    $getFunctionToCall = $_POST['whichfunction'];


    /*  Depending on the value of the whichfunction
    parameter switch to call different function */

        switch ($getFunctionToCall){
    case "AddUser":
    echo AddUser($_POST['firstname'],$_POST['lastname']);
    break;   
    }

    /* Function to add user to the user table */

    function AddUser($firstname,$lastname){
    $sql = "insert into user(firstname,lastname) values('$firstname','$lastname')";
    if(mysql_query($sql)){
    return 1; // Return 1 for success;
    }else{
    return 2;// Return 2 for database error;   
    }
    }   
     ?>

这是我的Logcat:

06-03 18:59:30.653: E/JavaBinder(142): !!! FAILED BINDER TRANSACTION !!!
06-03 18:59:30.657: E/InputDispatcher(142): channel '4097d448 com.example.remotedatabase/com.example.remotedatabase.GtugBase (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
06-03 18:59:30.657: E/InputDispatcher(142): channel '4097d448 com.example.remotedatabase/com.example.remotedatabase.GtugBase (server)' ~ Channel is unrecoverably broken and will be disposed!

1 个答案:

答案 0 :(得分:0)

您必须在清单中添加使用权限INTERNET。否则系统不会让您的应用看到互联网。

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

此外,如果您使用的是API 10ish +,则必须将http执行移至后台线程,在某个API级别之后,如果您尝试在主线程上进行Internet调用,则系统会抛出异常。考虑使用AsyncTask将网络操作从主线程移开。