糊涂把code中的AsyncTask [英] confused to put code in AsyncTask

查看:112
本文介绍了糊涂把code中的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个code接收聊天消息。但我弄糊涂了,当我试图把它放在的AsyncTask 。我已经警告读不能得到解决 read.readline()当我把它放在 postexecute
我想在此背景下code的工作,检查存在的任何消息来不来。我想问问,使code一直在后台运行,它是使用的AsyncTask 或有任何其他方式做到这一点?
请人帮我,我困惑如何做到这一点。谢谢

收到消息部分

  HttpURLConnection的连接;
        网址URL = NULL;
        尝试{
            linkurl =新Koneksi(本);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL + =/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            URL =新的URL(SERVER_URL);
            连接=(HttpURLConnection类)url.openConnection();
            connection.setDoOutput(真正的);
            connection.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
            connection.setRequestMethod(POST);

            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httpPost =新HttpPost(SERVER_URL);
            // ArrayList的<的NameValuePair>参数=新的ArrayList<的NameValuePair>();
            //添加参数
                //httpPost.setEntity(new UrlEn codedFormEntity(参数));

                HTT presponse HTT prespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT prespose.getEntity();

                //读取内容
                InputStream的时间= httpEntity.getContent();
                的BufferedReader读=新的BufferedReader(新的InputStreamReader(在));
                弦乐味精=TES;
                而(真)
                {

                    尝试 {
                        味精= read.readLine();
                        Log.d(,MSGGG:+ MSG);

                        //msgList.add(msg);
                    }赶上(IOException异常E){
                        // TODO自动生成的catch块
                        e.getMessage();
                    }
                    如果(MSG == NULL)
                    {
                        打破;
                    }
                    其他
                    {
                        showMessage(味精,假);
                    }
                }}
        赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }

            }
 

AsyncTask的一部分,我试图 - 更新,但得到的 getintent警告()在这里我必须把这些codeS

 公共类ReceivedTask扩展的AsyncTask<字符串,字符串,字符串> {

    束束= this.getIntent()getExtras()。
    最后的字符串参数2 = bundle.getString(keyUserId);
    最后的字符串参数3 = bundle.getString(keyChatsId);
     串param4 = bundle.getString(keyMessagesId);

    @覆盖
    在preExecute保护无效(){
        // TODO自动生成方法存根
        super.on preExecute();
    }

    @覆盖
    保护字符串doInBackground(字符串...为arg0){
        // TODO自动生成方法存根

        HttpURLConnection的连接;
        网址URL = NULL;
        尝试{
            linkurl =新Koneksi(ChatRoom.this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL + =/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            URL =新的URL(SERVER_URL);
            连接=(HttpURLConnection类)url.openConnection();
            connection.setDoOutput(真正的);
            connection.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
            connection.setRequestMethod(POST);

            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httpPost =新HttpPost(SERVER_URL);
            // ArrayList的<的NameValuePair>参数=新的ArrayList<的NameValuePair>();
            //添加参数
                //httpPost.setEntity(new UrlEn codedFormEntity(参数));

                HTT presponse HTT prespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT prespose.getEntity();

                //读取内容
                InputStream的时间= httpEntity.getContent();
                的BufferedReader读=新的BufferedReader(新的InputStreamReader(在));
                弦乐味精=TES;
                而(真)
                {

                    尝试 {
                        味精= read.readLine();
                        Log.d(,MSGGG:+ MSG);

                        //msgList.add(msg);
                    }赶上(IOException异常E){
                        // TODO自动生成的catch块
                        e.getMessage();
                    }
                    如果(MSG == NULL)
                    {
                        打破;
                    }
                    其他
                    {
                        showMessage(味精,假);
                    }
                }}
        赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }

            }
    }
 

ChatRoom.java - 我完全code

 公共类聊天室延伸活动{
    公共Koneksi linkurl;
    字符串SERVER_URL;
    私人的EditText的MessageText;
    私人TextView的meLabel;
    私人TextView的friendLabel;
    私人的ViewGroup messagesContainer;
    私人滚动型scrollContainer;
/ *私人处理程序处理程序=新的处理程序(); * /

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.chatpage);

        messagesContainer =(ViewGroup中)findViewById(R.id.messagesContainer);
        scrollContainer =(滚动型)findViewById(R.id.scrollContainer);

        按钮sendMessageButton =(按钮)findViewById(R.id.sendButton);

        束束= this.getIntent()getExtras()。
        / *最后弦乐paramnama = bundle.getString(非农产品市场准入); * /
        =的MessageText(的EditText)findViewById(R.id.messageEdit);
        meLabel =(TextView中)findViewById(R.id.meLabel);
        friendLabel =(TextView中)findViewById(R.id.friendLabel);
        meLabel.setText(我);


        最后的字符串参数1 = bundle.getString(keyCourseId);
        最后的字符串参数2 = bundle.getString(keyUserId);
        最后的字符串参数3 = bundle.getString(keyChatsId);
         串param4 = bundle.getString(keyMessagesId);


        sendMessageButton.setOnClickListener(新View.OnClickListener(){

            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根

                ArrayList的<的NameValuePair> postParameters =新的ArrayList<的NameValuePair>();
                postParameters.add(新BasicNameValuePair(信息,messageText.getText()的toString()));

                串响应=无效;

                尝试 {
                    linkurl =新Koneksi(ChatRoom.this);
                    SERVER_URL = linkurl.getUrl();
                    SERVER_URL + =/mobile/ChatKirimTeks.php?idu="+param2+"&idch="+param3;
                   响应= CourseHttpClient.executeHttpPost(SERVER_URL,postParameters);

                   字符串解析度= response.toString();

                   RES = res.trim();

                   RES = res.replaceAll(\\ S +,);
                   如果(res.equals(1)){
                       。字符串messageString = messageText.getText()的toString();
                       showMessage(messageString,真正的);
                       messageText.getText()清()。
                   }其他
                   {
                       CreateDialog函数(MAAF,消息安达Gagal Terkirim);
                   }
                }

                赶上(例外五){

                    messageText.setText(e.toString());

                }

             }

        });


        HttpURLConnection的连接;
        网址URL = NULL;
        尝试{
            linkurl =新Koneksi(本);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL + =/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            URL =新的URL(SERVER_URL);
            连接=(HttpURLConnection类)url.openConnection();
            connection.setDoOutput(真正的);
            connection.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
            connection.setRequestMethod(POST);

            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httpPost =新HttpPost(SERVER_URL);
            // ArrayList的<的NameValuePair>参数=新的ArrayList<的NameValuePair>();
            //添加参数
                //httpPost.setEntity(new UrlEn codedFormEntity(参数));

                HTT presponse HTT prespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT prespose.getEntity();

                //读取内容
                InputStream的时间= httpEntity.getContent();
                的BufferedReader读=新的BufferedReader(新的InputStreamReader(在));
                弦乐味精=TES;
                而(真)
                {

                    尝试 {
                        味精= read.readLine();
                        Log.d(,MSGGG:+ MSG);

                        //msgList.add(msg);
                    }赶上(IOException异常E){
                        // TODO自动生成的catch块
                        e.getMessage();
                    }
                    如果(MSG == NULL)
                    {
                        打破;
                    }
                    其他
                    {
                        showMessage(味精,假);
                    }
                }}
        赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }

            }


    公共类ReceivedTask扩展的AsyncTask<字符串,字符串,字符串> {

        @覆盖
        在preExecute保护无效(){

        }

        @覆盖
        保护字符串doInBackground(字符串...为arg0){
            // TODO自动生成方法存根
            HttpURLConnection的连接;
            网址URL = NULL;
            尝试{
                linkurl =新Koneksi(ChatRoom.this);
                SERVER_URL = linkurl.getUrl();
                SERVER_URL + =/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
                URL =新的URL(SERVER_URL);
                连接=(HttpURLConnection类)url.openConnection();
                connection.setDoOutput(真正的);
                connection.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
                connection.setRequestMethod(POST);

                HttpClient的HttpClient的=新DefaultHttpClient();
                HttpPost httpPost =新HttpPost(SERVER_URL);
                // ArrayList的<的NameValuePair>参数=新的ArrayList<的NameValuePair>();
                //添加参数
                    //httpPost.setEntity(new UrlEn codedFormEntity(参数));

                    HTT presponse HTT prespose = httpClient.execute(httpPost);
                    HttpEntity httpEntity = HTT prespose.getEntity();

                    //读取内容
                    InputStream的时间= httpEntity.getContent();
                    的BufferedReader读=新的BufferedReader(新的InputStreamReader(在));
            }
            赶上(IOException异常E){
                // TODO自动生成的catch块
                e.printStackTrace();
                返回null;
            }

        }
        @覆盖
        保护无效onPostExecute(字符串结果){
            // TODO自动生成方法存根
            super.onPostExecute(结果);
            弦乐味精=TES;
            而(真)
            {

                尝试 {
                    味精= read.readLine();
                    Log.d(,MSGGG:+ MSG);

                    //msgList.add(msg);
                }赶上(IOException异常E){
                    // TODO自动生成的catch块
                    e.getMessage();
                }
                如果(MSG == NULL)
                {
                    打破;
                }
                其他
                {
                    showMessage(味精,假);
                }
            }
        }
    }

    公共无效showMessage(字符串消息,布尔leftSide){
        最后的TextView TextView的=新的TextView(ChatRoom.this);
        textView.setTextColor(Color.BLACK);
        textView.setText(消息);

        INT bgRes = R.drawable.left_message_bg;

        LinearLayout.LayoutParams PARAMS =新LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);

        如果(!leftSide){
            bgRes = R.drawable.right_message_bg;
            params.gravity = Gravity.RIGHT;
        }

        textView.setLayoutParams(PARAMS);

        textView.setBackgroundResource(bgRes);

        runOnUiThread(新的Runnable(){
            @覆盖
            公共无效的run(){
                messagesContainer.addView(TextView的);

                //滚动到底
                如果(scrollContainer.getChildAt(0)!= NULL){
                    scrollContainer.scrollTo(scrollContainer.getScrollX(),scrollContainer.getChildAt(0).getHeight());
                }
                scrollContainer.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    私人无效CreateDialog函数(字符串标题,文本字符串){
        AlertDialog广告=新AlertDialog.Builder(本)
        .setPositiveButton(OK,NULL)
        .setTitle(标题)
        .setMessage(文本)
        。创建();
        ad.show();
    }
}
 

解决方案

你得到错误信息读不能得到解决由于Android禁止用户从访问互联网用户界面线程。你所要做的是在后台线程。事实上,使用点的AsyncTask 是保持用户界面线程尽可能免费。

每当我用的AsyncTask ,我通常会创建一个类来保存任务的所有参数,另一个类来保存结果。另外,我要确保结果类可以重新present可能出现的任何错误情况,如:抛出异常。所以,我使用的通用模板看起来是这样的(注:这是当不需要进度报告)。

 公共类MyActivity延伸活动{

    静态类MyAsyncTaskParameters {
        //把所有任务将在这里需要的参数
    }

    无效KickOffAsynctask(...){//各种参数所要求的在手任务
        MyAsyncTaskParameters PARAMS =新MyAsyncTaskParameters(...); //封装了所有的参数
        MyAsyncTask newtask =新MyAsyncTask();
        newtask.execute(PARAMS);
    }

    静态类MyAsyncTaskResults {
        //把所有的结果,该任务可以在这里产生
        //注意:可能会出现错误的任务,也异常
        //可以扔掉的任务,所以有可能
        //这个类来描述所有错误情况可能发生
    }

    静态类MyAsyncTask扩展的AsyncTask< MyAsyncTaskParameters,太虚,MyAsyncTaskResults> {

        @覆盖
        保护MyAsyncTaskResults doInBackground(MyAsyncTaskParameters ... PARAMS){
            MyAsyncTaskResults结果=新MyAsyncTaskResults();
            尝试 {
                MyAsyncTaskParameters taskParameters = PARAMS [0];
                //此方法在后台线程中运行,因此
                //做尽可能多的在这里的AsyncTask的。
            }赶上(的Throwable E){
                //结果集对象,以表明发生了异常。
            }
            返回结果;
        }

        @覆盖
        保护无效onPostExecute(MyAsyncTaskResults RES){
            //这个方法将在用户界面线程中运行。
            //用它来处理与存储在水库的结果。
            //如果发生错误,则资源对象将有它存储
            //所以采取适当的行动,例如报告给用户。
        }

    }

}
 

I have this code to receive chat messages. but i got confused when i tried to place it in AsyncTask. i have warning read cannot be resolved for read.readline() when i put it in postexecute .
i want to make this code work in background, to check there is any messages coming or not. and i wanna ask, to make the code always running in background is it use AsyncTask or there is any other way to do it?
anyone please help me, i confused how to make it. thank you

receive message part

HttpURLConnection connection;
        URL url = null;
        try{
            linkurl = new Koneksi(this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");    

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);
            //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            //add parameter
                //httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpRespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpRespose.getEntity();

                //read content
                InputStream in = httpEntity.getContent();
                BufferedReader read = new BufferedReader(new InputStreamReader(in));
                String msg = "tes";
                while(true)
                {

                    try {
                        msg = read.readLine();
                        Log.d("","MSGGG:  "+ msg);

                        //msgList.add(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.getMessage();
                    }
                    if(msg == null)
                    {
                        break;
                    }
                    else
                    {
                        showMessage(msg, false);
                    }
                }}
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            }

AsyncTask part that i tried - updated but get warning at getintent() where i must put these codes?

public class ReceivedTask extends AsyncTask<String, String, String> {

    Bundle bundle = this.getIntent().getExtras();
    final String param2 = bundle.getString("keyUserId");
    final String param3 = bundle.getString("keyChatsId");
     String param4 = bundle.getString("keyMessagesId");

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub

        HttpURLConnection connection;
        URL url = null;
        try{
            linkurl = new Koneksi(ChatRoom.this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");    

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);
            //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            //add parameter
                //httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpRespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpRespose.getEntity();

                //read content
                InputStream in = httpEntity.getContent();
                BufferedReader read = new BufferedReader(new InputStreamReader(in));
                String msg = "tes";
                while(true)
                {

                    try {
                        msg = read.readLine();
                        Log.d("","MSGGG:  "+ msg);

                        //msgList.add(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.getMessage();
                    }
                    if(msg == null)
                    {
                        break;
                    }
                    else
                    {
                        showMessage(msg, false);
                    }
                }}
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            }
    }

ChatRoom.java - my full code

public class ChatRoom extends Activity {
    public Koneksi linkurl;
    String SERVER_URL;
    private EditText messageText;
    private TextView meLabel;
    private TextView friendLabel;
    private ViewGroup messagesContainer;
    private ScrollView scrollContainer;
/*    private Handler handler = new Handler();*/

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

        messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
        scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);

        Button sendMessageButton = (Button) findViewById(R.id.sendButton);

        Bundle bundle = this.getIntent().getExtras();
        /*final String paramnama = bundle.getString("nama");*/
        messageText = (EditText) findViewById(R.id.messageEdit);
        meLabel = (TextView) findViewById(R.id.meLabel);
        friendLabel = (TextView) findViewById(R.id.friendLabel);
        meLabel.setText("me");


        final String param1 = bundle.getString("keyCourseId");
        final String param2 = bundle.getString("keyUserId");
        final String param3 = bundle.getString("keyChatsId");
         String param4 = bundle.getString("keyMessagesId");


        sendMessageButton.setOnClickListener(new View.OnClickListener() {

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

                ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("messages", messageText.getText().toString()));

                String response = null;

                try {
                    linkurl = new Koneksi(ChatRoom.this);
                    SERVER_URL = linkurl.getUrl();
                    SERVER_URL += "/mobile/ChatKirimTeks.php?idu="+param2+"&idch="+param3;
                   response = CourseHttpClient.executeHttpPost(SERVER_URL, postParameters);

                   String res = response.toString();

                   res = res.trim();

                   res = res.replaceAll("\\s+","");
                   if(res.equals("1")){
                       String messageString = messageText.getText().toString();
                       showMessage(messageString, true);
                       messageText.getText().clear();
                   }else
                   {
                       createDialog("Maaf", "Messages Anda Gagal Terkirim");
                   }
                }

                catch (Exception e) {

                    messageText.setText(e.toString());  

                }

             }

        });


        HttpURLConnection connection;
        URL url = null;
        try{
            linkurl = new Koneksi(this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
            url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");    

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);
            //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            //add parameter
                //httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpRespose = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpRespose.getEntity();

                //read content
                InputStream in = httpEntity.getContent();
                BufferedReader read = new BufferedReader(new InputStreamReader(in));
                String msg = "tes";
                while(true)
                {

                    try {
                        msg = read.readLine();
                        Log.d("","MSGGG:  "+ msg);

                        //msgList.add(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.getMessage();
                    }
                    if(msg == null)
                    {
                        break;
                    }
                    else
                    {
                        showMessage(msg, false);
                    }
                }}
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            }


    public class ReceivedTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            HttpURLConnection connection;
            URL url = null;
            try{
                linkurl = new Koneksi(ChatRoom.this);
                SERVER_URL = linkurl.getUrl();
                SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
                url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");    

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(SERVER_URL);
                //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
                //add parameter
                    //httpPost.setEntity(new UrlEncodedFormEntity(param));

                    HttpResponse httpRespose = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpRespose.getEntity();

                    //read content
                    InputStream in = httpEntity.getContent();
                    BufferedReader read = new BufferedReader(new InputStreamReader(in));
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }

        }
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            String msg = "tes";
            while(true)
            {

                try {
                    msg = read.readLine();
                    Log.d("","MSGGG:  "+ msg);

                    //msgList.add(msg);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.getMessage();
                }
                if(msg == null)
                {
                    break;
                }
                else
                {
                    showMessage(msg, false);
                }
            }
        }
    }

    public void showMessage(String message, boolean leftSide) {
        final TextView textView = new TextView(ChatRoom.this);
        textView.setTextColor(Color.BLACK);
        textView.setText(message);

        int bgRes = R.drawable.left_message_bg;

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        if (!leftSide) {
            bgRes = R.drawable.right_message_bg;
            params.gravity = Gravity.RIGHT;
        }

        textView.setLayoutParams(params);

        textView.setBackgroundResource(bgRes);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                messagesContainer.addView(textView);

                // Scroll to bottom
                if (scrollContainer.getChildAt(0) != null) {
                    scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
                }
                scrollContainer.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    private void createDialog(String title, String text) {
        AlertDialog ad = new AlertDialog.Builder(this)
        .setPositiveButton("Ok", null)
        .setTitle(title)
        .setMessage(text)
        .create();
        ad.show();
    }
}

解决方案

You're getting the error message read cannot be resolved because Android forbids you to access the internet from the User Interface thread. You have to do that in a background thread. Indeed, the point of using AsyncTask is to keep the user interface thread as free as possible.

Whenever I use AsyncTask, I usually create a class to hold all the parameters of the task, and another class to hold the results. Also, I make sure that the results class can represent any error conditions that may occur, e.g. exceptions thrown. So the general template that I use looks something like this (NB: this is for when a progress report isn't required).

public class MyActivity extends Activity {

    static class MyAsyncTaskParameters {
        // put all the parameters that the task will need here
    }

    void KickOffAsynctask(...) {  // various arguments as required by the task in hand
        MyAsyncTaskParameters params = new MyAsyncTaskParameters(...);  // package up all the parameters
        MyAsyncTask newtask = new MyAsyncTask();
        newtask.execute(params);
    }

    static class MyAsyncTaskResults {
        // put all the results that the task can generate here
        // NOTE: errors can occur in tasks, also exceptions
        //       can be thrown in tasks, so make it possible
        //       for this class to describe all error conditions that can occur
    }

    static class MyAsyncTask extends AsyncTask<MyAsyncTaskParameters, Void, MyAsyncTaskResults> {

        @Override
        protected MyAsyncTaskResults doInBackground(MyAsyncTaskParameters... params) {
            MyAsyncTaskResults results = new MyAsyncTaskResults();
            try {
                MyAsyncTaskParameters taskParameters = params[0];
                // This method will run in a background thread, so
                // do as much as possible of the AsyncTask here.
            } catch (Throwable e) {
                // Set results object to indicate that an exception occurred.
            }
            return results;
        }

        @Override
        protected void onPostExecute(MyAsyncTaskResults res) {
            // This method will run in the User Interface thread.
            // Use it to deal with the results stored in res.
            // If an error has occurred, the res object will have it stored
            // so take appropriate action, e.g. report to user.
        }

    }

}

这篇关于糊涂把code中的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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