为什么错误NetworkOnMainThreadException即将发生?

时间:2015-09-30 08:02:56

标签: android localhost android-database

我想简化一个Android应用程序连接到PHP Mysql,我阅读了很多PHP和Mysql教程连接Php与Android应用程序但是每个人都在emmulor上运行,我没有真正的设备,所以我使用emmulator for测试

为什么此错误来自此代码

我的Java文件

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

String name;
String id;
InputStream is=null;
String result=null;
String line=null;
int code;

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

    final EditText e_id=(EditText) findViewById(R.id.editText1);
    final EditText e_name=(EditText) findViewById(R.id.editText2);
    Button insert=(Button) findViewById(R.id.button1);

    insert.setOnClickListener(new View.OnClickListener() {

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

        id = e_id.getText().toString();
        name = e_name.getText().toString();

        insert();
    }
});
}

   public void insert()
     {
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>    
     ();

nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));

    try
    {
    HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://127.0.0.1/android/insert.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.e("pass 1", "connection success ");
     }
      catch(Exception e)
     {
        Log.e("Fail 1", e.toString());
        Toast.makeText(getApplicationContext(), "Invalid IP Address",
        Toast.LENGTH_LONG).show();
     }     

     try
      {
        BufferedReader reader = new BufferedReader
        (new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null)
         {
            sb.append(line + "\n");
          }
        is.close();
        result = sb.toString();
    Log.e("pass 2", "connection success ");
}
    catch(Exception e)
{
        Log.e("Fail 2", e.toString());
}     

try
{
        JSONObject json_data = new JSONObject(result);
        code=(json_data.getInt("code"));

        if(code==1)
        {
    Toast.makeText(getBaseContext(), "Inserted Successfully",
        Toast.LENGTH_SHORT).show();
        }
        else
        {
     Toast.makeText(getBaseContext(), "Sorry, Try Again",
        Toast.LENGTH_LONG).show();
        }
}
catch(Exception e)
{
        Log.e("Fail 3", e.toString());
}
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

}

}

这是我的PHP文件

<?php
$host="127.0.0.1";
    $db="android";
$uname="root";
$pwd="";

    $con = mysqli_connect("$host","$uname","$pwd") or die("connection failed");
mysqli_select_db($con,$db) or die("db selection failed");

$id=(isset($_REQUEST['id']) )?$_REQUEST['id']: '';
$name=(isset($_REQUEST['name']) ) ? $_REQEST['name']: '';

$flag['code']=0;

if($r=mysqli_query("insert into sample values('$id','$name')   ,$con"))
{
    $flag['code']=1;
    echo"hi";
}

print(json_encode($flag));
mysqli_close($con);
?>

这是Logcat Window

09-30 03:35:16.800: E/Fail 1(1064): android.os.NetworkOnMainThreadException
09-30 03:35:16.870: E/Fail 2(1064): java.lang.NullPointerException: lock ==  
 null
09-30 03:35:16.870: E/Fail 3(1064): java.lang.NullPointerException

1 个答案:

答案 0 :(得分:0)

当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask中运行您的代码:

(function( $ ){

     $.fn.multipleInput = function() {

          return this.each(function() {

               // create html elements

               // list of email addresses as unordered list
               $list = $('<ul />');

               // input
               var $input = $('<input type="text" />').keyup(function(event) {

                    if(event.which == 32 || event.which == 188) {
                         // key press is space or comma
                         var val = $(this).val().slice(0, -1); // remove space/comma from value

                         // append to list of emails with remove button
                         $list.append($('<li class="multipleInput-email"><span> ' + val + '</span></li>')
                              .append($('<a href="#" class="multipleInput-close" title="Remove" />')
                                   .click(function(e) {
                                        $(this).parent().remove();
                                        e.preventDefault();
                                   })
                              )
                         );
                         $(this).attr('placeholder', '');
                         // empty input
                         $(this).val('');
                    }

               });

               // container div
               var $container = $('<div class="multipleInput-container" />').click(function() {
                    $input.focus();
               });

               // insert elements into DOM
               $container.append($list).append($input).insertAfter($(this));

               // add onsubmit handler to parent form to copy emails into original input as csv before submitting
               var $orig = $(this);
               $(this).closest('form').submit(function(e) {

                    var emails = new Array();
                    $('.multipleInput-email span').each(function() {
                         emails.push($(this).html());
                    });
                    emails.push($input.val());

                    $orig.val(emails.join());

               });

               return $(this).hide();

          });

     };
})( jQuery );