Android - JSON mySQL查询提供NetworkOnMainThreadException

时间:2012-04-17 06:33:25

标签: android mysql database json

我正在尝试运行此活动以查询数据库以填充表。 我试图按照我在网上找到的一个片段,唯一的问题是,无论如何,我都会收到“connectionandroid.os.NetworkOnMainThreadException”错误。

我试图像许多论坛中所建议的那样使用AsyncTask并在后台进行处理,但仍然没有。 我知道将长查询发送到数据库时会出现错误,但此查询可能需要0.1秒。我在本地拥有数据库,虽然使用公共IP访问它,并且数据库非常小。

这是我的PHP代码:

<?php

$hostname_localhost ="localhost";
$database_localhost ="DB";
$username_localhost ="root";
$password_localhost ="pwd";

mysql_connect($hostname_localhost,$username_localhost,$password_localhost);

mysql_select_db($database_localhost);

$sql=mysql_query("select * from friendlist where Id1 = 1");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

代码有效,好像我转到页面,我看到显示结果(我目前只有3行)。

这是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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MySQLAndroidActivity extends ListActivity {

JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
HttpResponse response;
HttpEntity entity;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();

 HttpPost httppost = new HttpPost("http://X.X.X.X/test.php");

 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);

 entity = response.getEntity();


 is = entity.getContent();

 }catch(Exception e){
     Log.e("log_tag", "Error in http connection"+e.toString());
     System.exit(1);
}

//convert response to string
try{
  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
   sb = new StringBuilder();
   sb.append(reader.readLine() + "\n");

   String line="0";
   while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
    }
    is.close();
    result=sb.toString();
    }catch(Exception e){
          Log.e("log_tag", "Error converting result "+e.toString());
    }
//parsing data
String idfriend;
String id1;
String id2;
try{
  jArray = new JSONArray(result);
  JSONObject json_data=null;
  for(int i=0;i<jArray.length();i++){
         json_data = jArray.getJSONObject(i);
         idfriend=json_data.getString("Idfriend");
         id1=json_data.getString("Id1");
         id2=json_data.getString("Id2");


         System.out.println("id1: " + id1);
     }
  }
  catch(JSONException e1){
   Toast.makeText(getBaseContext(), "No Id found" ,Toast.LENGTH_LONG).show();
  } catch (ParseException e1) {
   e1.printStackTrace();
 }
}
}

我还尝试使用简单的Activity而不是ListActivity。

我有一个几乎相似的代码,但是那个使用了不同的方法。事实上,它没有得到结果,在php上,它只返回一个字符,无论是否检索到0行或更多行。在这种情况下,我需要更高级别的东西,因为我需要获取某些特定字段的值。

编辑:

根据要求,堆栈跟踪:

  Error in http connectionandroid.os.NetworkOnMainThreadException
  04-17 06:44:17.921: W/System.err(24207): java.lang.Exception
  04-17 06:44:17.921: W/System.err(24207):  at       com.mysql.android.MySQLAndroidActivity.onCreate(MySQLAndroidActivity.java:56)
  04-17 06:44:17.921: W/System.err(24207):  at       android.app.Activity.performCreate(Activity.java:4465)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
  04-17 06:44:17.921: W/System.err(24207):  at android.os.Handler.dispatchMessage(Handler.java:99)
  04-17 06:44:17.921: W/System.err(24207):  at android.os.Looper.loop(Looper.java:137)
  04-17 06:44:17.931: W/System.err(24207):  at android.app.ActivityThread.main(ActivityThread.java:4424)
  04-17 06:44:17.931: W/System.err(24207):  at java.lang.reflect.Method.invokeNative(Native Method)
  04-17 06:44:17.931: W/System.err(24207):  at java.lang.reflect.Method.invoke(Method.java:511)
  04-17 06:44:17.931: W/System.err(24207):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
  04-17 06:44:17.931: W/System.err(24207):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  04-17 06:44:17.931: W/System.err(24207):  at dalvik.system.NativeStart.main(Native Method)

EDIT2:

这与我使用AsyncTask的版本非常相似(我正在创建它,没有编译器,所以它可能不完美;但它与我之前做的非常相似):< / p>

  @Override
   public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

      new LoadTask().execute();

  }



 private class LoadTask extends AsyncTask<Void, Integer, Void> {
            @Override
            protected void onPreExecute() {

            }

            @Override
            protected Void doInBackground(Void... params) {
                    synchronized (this) {

                    Looper.prepare();       
                    doStuff() //this method basically contains what it is inside the onCreate.

                    }

                    return null;
            }

       }
       }

- 我记得我被迫使用'Looper.prepare();'。 所以我在'doStuff();'

之前添加了它

编辑2:

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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class MySQLAndroidActivity extends ListActivity {

    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    HttpResponse response;
    HttpEntity entity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        new LoadTask.execute();

    }



    private class LoadTask extends AsyncTask < Void, Integer, Void > {@Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(Void...params) {

            Looper.prepare();

            doStuff();



            return null;


        }
    }


    public void doStuff() {
        ArrayList < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > ();
        //http post
        try {
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost("http://X.X.X.X/test.php");

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);

            entity = response.getEntity();


            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection" + e.toString());
            System.exit(1);
        }


        //convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        //parsing data
        String idfriend;
        String id1;
        String id2;
        try {
            jArray = new JSONArray(result);
            JSONObject json_data = null;

            System.out.println("Length " + jArray.length());
            Log.d("DB", "Length " + jArray.length());

            for (int i = 0; i < jArray.length(); i++) {

                System.out.println("counter " + i);
                json_data = jArray.getJSONObject(i);
                idfriend = json_data.getString("Idfriend");
                id1 = json_data.getString("Id1");
                id2 = json_data.getString("Id2");


                System.out.println("id1: " + id1);
            }
        } catch (JSONException e1) {
            Log.d("DB", "Error somewhere");
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
    }
}

提前致谢,

<磷>氮

2 个答案:

答案 0 :(得分:3)

我听说从ICS开始,不允许在UI(主)线程上执行网络操作。因此,您必须在单独的线程中执行此操作。因此,要么使用 AsyncTask 线程 HandlerThread 使用Looper和Handler 来执行Web操作。如果你在运行froyo或gingerbread的设备上尝试它,那就没关系,但ICS上没有。

关于您尝试通过处理程序或AsyncTask运行它,它取决于您是如何做到的。粘贴该代码,以便我看到问题。


<强>更新

public class MySQLAndroidActivity extends ListActivity {

    private static final String url = "http://X.X.X.X/test.php";

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

        LoadTask t = new LoadTask();
        t.execute(null);

    }

    private static class LoadTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(Void... params) {
            doStuff();

            return null;
        }
    }





    public static void doStuff() {
        JSONArray jArray;
        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        HttpResponse response;
        HttpEntity entity;

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);

            entity = response.getEntity();

            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection" + e.toString());
            System.exit(1);
        }

        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            result = sb.toString();

            Log.i("json string", result);
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }


        // parsing data
        String idfriend;
        String id1;
        String id2;
        try {
            jArray = new JSONArray(result);
            JSONObject json_data = null;

            System.out.println("Length " + jArray.length());
            Log.d("DB", "Length " + jArray.length());

            for (int i = 0; i < jArray.length(); i++) {

                System.out.println("counter " + i);
                json_data = jArray.getJSONObject(i);
                idfriend = json_data.getString("idfriend");
                id1 = json_data.getString("id1");
                id2 = json_data.getString("id2");

                System.out.println("id1: " + id1);
            }
        } catch (JSONException e1) {
            Log.d("DB", "Error somewhere");
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
    }

}

*有一些方法调用问题,最重要的是你从JSONObject中取出键作为 Idfriend,Id1,Id2 ,这是错误的,因为在你的json字符串中键是像 idfriend,id1,id2 。它区分大小写,这就是崩溃的原因。

答案 1 :(得分:0)

你应该阅读abou模型 - 视图 - 控制器模式(在谷歌查找)。这种模式定义了你应该从模型(数据库访问,读取Dao模式)和控制器(运行应用程序的逻辑,例如这些是主类)中单独实现视图(用户界面)。

希望这能帮到你!