尝试自定义列表视图,但在尝试连接数据库时出错

时间:2013-05-16 08:52:48

标签: android mysql listview httprequest android-arrayadapter

我一直在搜索如何从mysql中提取数据并使用自定义列表视图显示它们。现在,我发现Http请求有问题。有人可以帮我查一下这段代码吗?我无法找出为什么我的代码无法正常工作。

MainActivity.java

public class MainActivity extends Activity {

    ArrayList<Mall> arrayOfMallData = new ArrayList<Mall>();

    class Mall{
        public String Mall_title;
        public String Mall_desc;
    }

    FancyAdapter fancyAdapter = null;
    static ArrayList<String> resultRow;


@Override
protected void onCreate(Bundle savedInstanceState) {

    try{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String result = "";

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/BasicPHP/getJSON.php");
            HttpResponse response = httpClient.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            try {

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                    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());
            }
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        try {

            JSONArray jArray = new JSONArray(result);

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

                Mall resultRow = new Mall();

                resultRow.Mall_title = f.getString("Mall_Name");    
                resultRow.Mall_desc = f.getString("Mall_Business_Hours");

                arrayOfMallData.add(resultRow);              
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());     
        }


        ListView listView = (ListView)findViewById(R.id.listView);
        fancyAdapter = new FancyAdapter();
        listView.setAdapter(fancyAdapter); 

    } catch (Exception e) {
        Log.e("log_tag", "Error In Code: " + e.toString());
    }
}

class FancyAdapter extends ArrayAdapter<Mall> {
    FancyAdapter() {
        super(MainActivity.this, android.R.layout.simple_list_item_1, arrayOfMallData);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null){
            LayoutInflater inflater = getLayoutInflater();
            convertView = inflater.inflate(R.layout.malllist_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.populateFrom(arrayOfMallData.get(position));
        return(convertView);
    }
}

class ViewHolder {
    public TextView title = null;
    public TextView desc = null;

    ViewHolder(View row) {
        title = (TextView)row.findViewById(R.id.title);
        desc = (TextView)row.findViewById(R.id.desc);
    }

    void populateFrom(Mall r) {
        title.setText(r.Mall_title);
        desc.setText(r.Mall_desc);

    }
}  
}

这是我的LogCat

05-16 15:36:53.334: I/dalvikvm(539): threadid=3: reacting to signal 3
05-16 15:36:53.384: I/dalvikvm(539): Wrote stack traces to '/data/anr/traces.txt'
05-16 15:36:53.494: E/log_tag(539): Error in http connection android.os.NetworkOnMainThreadException
05-16 15:36:53.494: E/log_tag(539): Error parsing data org.json.JSONException: End of input at character 0 of 
05-16 15:36:53.594: D/libEGL(539): loaded /system/lib/egl/libGLES_android.so
05-16 15:36:53.614: D/libEGL(539): loaded /system/lib/egl/libEGL_emulation.so
05-16 15:36:53.634: D/(539): HostConnection::get() New Host Connection established 0x1dee68, tid 539
05-16 15:36:53.654: D/libEGL(539): loaded /system/lib/egl/libGLESv1_CM_emulation.so
05-16 15:36:53.665: D/libEGL(539): loaded /system/lib/egl/libGLESv2_emulation.so
05-16 15:36:53.726: W/EGL_emulation(539): eglSurfaceAttrib not implemented
05-16 15:36:53.744: D/OpenGLRenderer(539): Enabling debug mode 0
05-16 15:36:53.854: I/dalvikvm(539): threadid=3: reacting to signal 3
05-16 15:36:53.875: I/dalvikvm(539): Wrote stack traces to '/data/anr/traces.txt'

2 个答案:

答案 0 :(得分:2)

在主线程上的方法onCreate(Bundle savedInstanceState)中,您正在进行一些Web调用,这是问题的原因,您不能在主线程上执行此操作HttpResponse response = httpClient.execute(httppost);。将网络部件移动到其他线程上。看一下这个AsyncTask Android example

答案 1 :(得分:0)

android.os.NetworkOnMainThreadException 

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

private class RetriveJson extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... params) {
                   //retrive your data via url from here
        }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

}

并在您想要的位置调用此任务

new RetriveJson()。execute(“your url”);

我希望这会对你有所帮助。