Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/179.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 错误:方法gettext()必须是从UI线程调用的_Android - Fatal编程技术网

Android 错误:方法gettext()必须是从UI线程调用的

Android 错误:方法gettext()必须是从UI线程调用的,android,Android,在做一个项目时,我遇到了这个错误 错误:方法gettext()必须是从UI线程调用的 在以下行: String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString(); 请帮忙 这是我为ChatActivity.java类编写的全部代码 package com.example.ank

在做一个项目时,我遇到了这个错误 错误:方法gettext()必须是从UI线程调用的 在以下行:

String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
请帮忙

这是我为ChatActivity.java类编写的全部代码

package com.example.ankit.myapplication;

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.ankit.myapplication.XmppService;
import com.squareup.okhttp.OkHttpClient;

import org.jivesoftware.smack.packet.Message;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;

//import services.XmppService;


public class ChatActivity extends Activity {
    EditText editText_mail_id;
    EditText editText_chat_message;
    ListView listView_chat_messages;
    Button button_send_chat;
    List<ChatObject> chat_list;

    BroadcastReceiver recieve_chat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        Scanner in = new Scanner(System.in);
        XmppService xm= new XmppService();
        Log.d("pavan","in chat "+getIntent().getStringExtra("user_id"));
        Log.d("pavan","in chat server "+Util.SERVER);
        XmppService.setupAndConnect(ChatActivity.this, Util.SERVER, "",
                getIntent().getStringExtra("user_id"), Util.XMPP_PASSWORD);


        editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
        editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
        listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
        button_send_chat= (Button) findViewById(R.id.button_send_chat);
        button_send_chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // send chat message to server
                String message=editText_chat_message.getText().toString();

                showChat("sent",message);

                //  new SendMessage().execute();

                XmppService.sendMessage(ChatActivity.this, editText_mail_id.getText().toString() + Util.SUFFIX_CHAT, Message.Type.chat, message);
                editText_chat_message.setText("");


            }
        });


        recieve_chat=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                String message=intent.getStringExtra("message");

                Log.d("pavan","in local braod "+message);
                showChat("recieve",message);


            }
        };

        LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));



    }

    private void showChat(String type, String message){

        if(chat_list==null || chat_list.size()==0){

            chat_list= new ArrayList<ChatObject>();
        }

        chat_list.add(new ChatObject(message,type));

        ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);

        listView_chat_messages.setAdapter(chatAdabter);
        //chatAdabter.notifyDataSetChanged();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private class SendMessage extends AsyncTask<String, Void, String> {

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


        }

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

            String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
            Log.i("pavan", "url" + url);

            OkHttpClient client_for_getMyFriends = new OkHttpClient();

            String response = null;
            // String response=Utility.callhttpRequest(url);

            try {
                url = url.replace(" ", "%20");
                response = callOkHttpRequest(new URL(url),
                        client_for_getMyFriends);
                for (String subString : response.split("<script", 2)) {
                    response = subString;
                    break;
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            //Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();



        }


    }



    // Http request using OkHttpClient
    String callOkHttpRequest(URL url, OkHttpClient tempClient)
            throws IOException {

        HttpURLConnection connection = tempClient.open(url);

        connection.setConnectTimeout(40000);
        InputStream in = null;
        try {
            // Read the response.
            in = connection.getInputStream();
            byte[] response = readFully(in);
            return new String(response, "UTF-8");
        } finally {
            if (in != null)
                in.close();
        }
    }

    byte[] readFully(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        for (int count; (count = in.read(buffer)) != -1;) {
            out.write(buffer, 0, count);
        }
        return out.toByteArray();
    }








}
package com.example.ankit.myapplication;
导入android.app.Activity;
导入android.app.Service;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.content.SharedReferences;
导入android.os.AsyncTask;
导入android.support.annotation.NonNull;
导入android.support.v4.content.LocalBroadcastManager;
导入android.support.v7.app.ActionBarActivity;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ListView;
导入android.widget.Toast;
导入com.example.ankit.myapplication.XmppService;
导入com.squareup.okhttp.OkHttpClient;
导入org.jivesoftware.smack.packet.Message;
导入java.io.ByteArrayOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.Collection;
导入java.util.Iterator;
导入java.util.List;
导入java.util.ListIterator;
导入java.util.Scanner;
//导入服务.XmppService;
公共类聊天活动扩展了活动{
EditText EditText\u邮件\u id;
编辑文本编辑文本聊天信息;
ListView ListView_聊天_信息;
按钮发送聊天;
列表聊天室列表;
广播接收机接收聊天;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u chat);
扫描仪输入=新扫描仪(系统输入);
XmppService xm=新的XmppService();
Log.d(“pavan”,“in chat”+getIntent().getStringExtra(“user_id”));
Log.d(“pavan”,“在聊天服务器中”+Util.server);
XmppService.setupAndConnect(ChatActivity.this,Util.SERVER,“,
getIntent().getStringExtra(“用户id”),Util.XMPP\u密码);
editText\u mail\u id=(editText)findViewById(R.id.editText\u mail\u id);
editText\u chat\u message=(editText)findViewById(R.id.editText\u chat\u message);
listView_chat_messages=(listView)findViewById(R.id.listView_chat_messages);
按钮发送聊天=(按钮)findViewById(R.id.button发送聊天);
按钮\发送\聊天。setOnClickListener(新视图。OnClickListener(){
@凌驾
公共void onClick(视图v){
//向服务器发送聊天信息
String message=editText\u chat\u message.getText().toString();
showChat(“已发送”,消息);
//新建SendMessage().execute();
XmppService.sendMessage(ChatActivity.this,editText\u mail\u id.getText().toString()+Util.SUFFIX\u CHAT,Message.Type.CHAT,Message);
editText\u chat\u message.setText(“”);
}
});
receive_chat=新广播接收器(){
@凌驾
公共void onReceive(上下文、意图){
字符串消息=intent.getStringExtra(“消息”);
Log.d(“pavan”,“本地braod”+消息);
showChat(“接收”,信息);
}
};
LocalBroadcastManager.getInstance(this.registerReceiver)(Receive_chat,new IntentFilter(“message_Received”);
}
私有void showChat(字符串类型、字符串消息){
if(chat_list==null | | chat_list.size()==0){
chat_list=new ArrayList();
}
添加(新的聊天对象(消息,类型));
ChatAdabter ChatAdabter=新的ChatAdabter(chataActivity.this,R.layout.chat\u视图,chat\u列表);
listView_chat_messages.setAdapter(chatAdabter);
//notifyDataSetChanged();
}
@凌驾
受保护的空onDestroy(){
super.ondestory();
}
私有类SendMessage扩展异步任务{
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
//TODO自动生成的方法存根
字符串url=Util.send_chat_url+“?email_id=“+editText_mail_id.getText().toString()+”&message=“+editText_chat_message.getText().toString();
Log.i(“pavan”,“url”+url);
OkHttpClient_for_getMyFriends=new OkHttpClient();
字符串响应=null;
//String response=Utility.callhttpRequest(url);
试一试{
url=url.replace(“,“%20”);
response=callOkHttpRequest(新的URL),
客户(为我的朋友);
for(字符串子字符串:response.split(“
不要从UI线程外部访问Android UI工具包

将editText\u mail\u id.getText()和editText\u chat\u message.getText()作为参数传递给异步任务,或在onPreExecute中将其设置为某个变量

比如:

private class SendMessage extends AsyncTask<String, Void, String> {
    private String mailId;
    private String msgText;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mailId = editText_mail_id.getText().toString();
        msgText = editText_chat_message.getText().toString();

    }

您可以像我一样创建用于存储参数的类

只需创建一个类

例如:

public class MyTaskParams
{
    String mailId;
    String message;

    public MyTaskParams(String mailId, String message)
    {
        this.mailId = mailId;
        this.message = message;
    }
}

public class SendMessage extends AsyncTask<MyTaskParams, Void, String {

    @Override
    protected String doInBackground(MyTaskParams... params) {
    String mailId = params[0].mailId;
    String message = params[0].message;
    String url = Util.send_chat_url+"?email_id="+ mailId +"&message="+ message;        
    }
}
使用此代码,您可以从任何活动调用SendMessage类,不要将asynctask与get text绑定,因为如果这样做,您只能在该活动中使用SendMessage
希望这能对您有所帮助。

如果您在活动中,也可以使用runOnUiThread访问UI线程。
public class MyTaskParams
{
    String mailId;
    String message;

    public MyTaskParams(String mailId, String message)
    {
        this.mailId = mailId;
        this.message = message;
    }
}

public class SendMessage extends AsyncTask<MyTaskParams, Void, String {

    @Override
    protected String doInBackground(MyTaskParams... params) {
    String mailId = params[0].mailId;
    String message = params[0].message;
    String url = Util.send_chat_url+"?email_id="+ mailId +"&message="+ message;        
    }
}
MyTaskParams params = new MyTaskParams(editText_mail_id.getText().toString(),editText_chat_message.getText().toString());

SendMessage myTask = new SendMessage();
myTask.execute(params);