如何让我的连接的连接的AsyncTask [英] How Do I make my Connection an AsyncTask Connection

查看:209
本文介绍了如何让我的连接的连接的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:我发现,最简单的方法是使用 AQuery

我需要让我的HttpPost获取另一个线程JSON数据,我不知道如何得到它的所有合作。香港专业教育学院看了看无痛线程博客和仍然无法得到它的工作。

下面是我原来的code befor试图ansyncing它。

这是我第一次尝试这样AsyncTasking PLZ不要是苛刻。日Thnx。

在我的OnCreate:

  / **
     *连接到MySQL使用PHP和填充的ListView
     * ================================================= =======
     * /
    mList =(ListView控件)findViewById(R.id.sidebar_list);    / ** - HTTP POST的名单 - * /
    尝试//< - 这TRY方法是什么意思需要在一个单独的线程?
    {
    HttpClient的HttpClient的=新DefaultHttpClient();
    HttpPost httpPost =新HttpPost(http://192.168.1.34/xxxx/xxxxx_list.php);    清单<&的NameValuePair GT; nameValue =新的ArrayList<&的NameValuePair GT;();
    httpPost.setEntity(新UrlEn codedFormEntity(nameValue));    HTT presponse HTT presponse = httpClient.execute(httpPost);    HttpEntity httpEntity = HTT presponse.getEntity();    是= httpEntity.getContent();    }赶上(例外五)
    {
    // TODO处理收到
    Log.e(log_tag,在HTTP错误连接+ e.toString());
    Toast.makeText(这一点,HTTP连接错误:+ e.toString(),Toast.LENGTH_LONG).show();
    }    //以下的所有的位置可以在UI线程?
    / **
     *转换的响应串------------------------------------
     * ----------------------
     * * /
    尝试
    {
    BUFR的BufferedReader =新的BufferedReader(新的InputStreamReader(是,ISO-8859-1),8);
    SB =新的StringBuilder();
    sb.append(BufR.readLine()+\\ n);    串行=0;
    而((行= BufR.readLine())!= NULL)
    {
    sb.append(行+\\ n);
    }
    is.close();
    结果= sb.toString();
    }赶上(例外五)
    {
    // TODO处理收到
    Log.e(log_tag,在转换为字符串错误+ e.toString());
    }    //配对数据
    INT q_id;
    串q_label;
    串q_title;
    串q_description;
    串q_gotoURL;    尝试
    {
    jArray =新JSONArray(结果);
    JSONObject的json_data = NULL;
    的for(int i = 0; I< jArray.length();我++)
    {
    json_data = jArray.getJSONObject(ⅰ);
    q_id = json_data.getInt(_ ID);
    q_label = json_data.getString(标签);
    q_title = json_data.getString(标题);
    q_description = json_data.getString(说明);
    q_gotoURL = json_data.getString(gotoURL);
    // mList.add();
    }    setupList();
    }赶上(JSONException E1)
    {
    Toast.makeText(getBaseContext(),无数据找到,Toast.LENGTH_LONG).show();
    }赶上(ParseException的E1)
    {
    e1.printStackTrace();
    }    };


解决方案

我觉得你可以尝试这样的事:

 公共类MyActivity延伸活动{//配对数据
INT q_id;
串q_label;
串q_title;
串q_description;
串q_gotoURL;
上下文语境;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onCreate(savedInstanceState);
    mList =(ListView控件)findViewById(R.id.sidebar_list);
    上下文= getApplicationContext();
    新HttpTask()执行(http://192.168.1.34/xxxx/xxxxx_list.php);}
私有类HttpTask扩展的AsyncTask<弦乐,太虚,字符串> {
    保护字符串doInBackground(字符串的URL ...){
        尝试{
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httpPost =新HttpPost(网址[0]);            清单<&的NameValuePair GT; nameValue =新的ArrayList<&的NameValuePair GT;();
            httpPost.setEntity(新UrlEn codedFormEntity(nameValue));            HTT presponse HTT presponse = httpClient.execute(httpPost);            HttpEntity httpEntity = HTT presponse.getEntity();            是= httpEntity.getContent();            //获取结果
            BUFR的BufferedReader =新的BufferedReader(新的InputStreamReader(是,ISO-8859-1),8);
            SB =新的StringBuilder();
            sb.append(BufR.readLine()+\\ n);            串行=0;
            而((行= BufR.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            结果= sb.toString();        }赶上(例外五){
            Toast.makeText(背景下,HTTP连接错误:+ e.toString(),Toast.LENGTH_LONG).show();
            返回null;
        }
    }    保护无效onPostExecute(字符串结果){
        尝试{
            如果(结果== NULL)
                抛出新的异常(结果为空);
            jArray =新JSONArray(结果);
            JSONObject的json_data = NULL;
            的for(int i = 0; I< jArray.length();我++){
                json_data = jArray.getJSONObject(ⅰ);
                q_id = json_data.getInt(_ ID);
                q_label = json_data.getString(标签);
                q_title = json_data.getString(标题);
                q_description = json_data.getString(说明);
                q_gotoURL = json_data.getString(gotoURL);
                // mList.add();
            }
            //发送消息到处理程序来绘制列表
            drawListHandler.sendEmptyMessage(0);
        }赶上(例外E1){
            Toast.makeText(上下文,e1.getMessage(),Toast.LENGTH_LONG).show();
        }
    }
}处理器drawListHandler =新的处理程序(){
    / *(非Javadoc中)
     * @see android.os.Handler#的handleMessage(android.os.Message)
     * /
    @覆盖
    公共无效的handleMessage(消息MSG){
        setupList();
    }
};
}

UPDATE: I found that the easiest way is to use AQuery.

I need to get my HttpPost for getting JSON data on another thread and I dont know how to get it all working together. Ive looked at the Painless Threading Blog and still cant get it to work.

Below is my original code befor trying to ansyncing it.

This is my first try at AsyncTasking so plz dont be to harsh. Thnx.

Inside my OnCreate:

    /**
     * Connecting to MySQL using PHP and Populate the ListView
     * ========================================================
     */
    mList = (ListView) findViewById(R.id.sidebar_list);

    /** - http post for the list - */
    try  //<--THIS TRY METHOD IS WHAT NEED TO BE ON A SEPERATE THREAD??
    {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://192.168.1.34/xxxx/xxxxx_list.php");

    List<NameValuePair> nameValue = new ArrayList<NameValuePair>();
    httpPost.setEntity(new UrlEncodedFormEntity(nameValue));

    HttpResponse httpResponse = httpClient.execute(httpPost);

    HttpEntity httpEntity = httpResponse.getEntity();

    is = httpEntity.getContent();

    } catch (Exception e)
    {
    // TODO handle e
    Log.e("log_tag", "Error in HTTP connect" + e.toString());
    Toast.makeText(this, "HTTP Connection Error : " + e.toString(), Toast.LENGTH_LONG).show();
    }

    // EVERYTHING BELOW HERE CAN BE ON THE UI THREAD???
    /**
     * Convert response to string------------------------------------
     * ----------------------
     * */
    try
    {
    BufferedReader BufR = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    sb = new StringBuilder();
    sb.append(BufR.readLine() + "\n");

    String line = "0";
    while ((line = BufR.readLine()) != null)
    {
    sb.append(line + "\n");
    }
    is.close();
    result = sb.toString();
    } catch (Exception e)
    {
    // TODO handle e
    Log.e("log_tag", "Error in convert to String" + e.toString());
    }

    // paring data
    int q_id;
    String q_label;
    String q_title;
    String q_description;
    String q_gotoURL;

    try
    {
    jArray = new JSONArray(result);
    JSONObject json_data = null;
    for (int i = 0; i < jArray.length(); i++)
    {
    json_data = jArray.getJSONObject(i);
    q_id = json_data.getInt("_ID");
    q_label = json_data.getString("label");
    q_title = json_data.getString("title");
    q_description = json_data.getString("description");
    q_gotoURL = json_data.getString("gotoURL");
    // mList.add();
    }

    setupList();
    } catch (JSONException e1)
    {
    Toast.makeText(getBaseContext(), "No Data Found", Toast.LENGTH_LONG).show();
    } catch (ParseException e1)
    {
    e1.printStackTrace();
    }

    };

解决方案

I think you can try something like this:

public class MyActivity extends Activity {

// paring data
int q_id;
String q_label;
String q_title;
String q_description;
String q_gotoURL;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    mList = (ListView) findViewById(R.id.sidebar_list);
    context = getApplicationContext();
    new HttpTask().execute("http://192.168.1.34/xxxx/xxxxx_list.php");

}
private class HttpTask extends AsyncTask<String, Void, String> {


    protected String doInBackground(String... urls) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(urls[0]);

            List<NameValuePair> nameValue = new ArrayList<NameValuePair>();
            httpPost.setEntity(new UrlEncodedFormEntity(nameValue));

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

            is = httpEntity.getContent();

            // Get result
            BufferedReader BufR = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(BufR.readLine() + "\n");

            String line = "0";
            while ((line = BufR.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

        } catch (Exception e) {
            Toast.makeText(context, "HTTP Connection Error : " + e.toString(), Toast.LENGTH_LONG).show();
            return null;
        }
    }

    protected void onPostExecute(String result) {
        try {
            if(result == null)
                throw new Exception("result is null");
            jArray = new JSONArray(result);
            JSONObject json_data = null;
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                q_id = json_data.getInt("_ID");
                q_label = json_data.getString("label");
                q_title = json_data.getString("title");
                q_description = json_data.getString("description");
                q_gotoURL = json_data.getString("gotoURL");
                // mList.add();
            }
            //send message to handler to draw list
            drawListHandler.sendEmptyMessage(0);
        } catch (Exception e1) {
            Toast.makeText(context, e1.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

Handler drawListHandler = new Handler(){
    /* (non-Javadoc)
     * @see android.os.Handler#handleMessage(android.os.Message)
     */
    @Override
    public void handleMessage(Message msg) {
        setupList();
    }
};
}

这篇关于如何让我的连接的连接的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆