2017-06-14 72 views
0

我试图从服务器获取消息以显示在吐司,但它没有出现。客户端接收来自服务器的消息,而无需任何errors.I曾试图onPOST等打开UI线程,但它没有工作吐司不在asynctask中显示

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main2); 
    new test().execute(); 

} 
public class test extends AsyncTask<String,String,String>{ 


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

     try 
     { 
      socket = new Socket("ip", port); 
      OutputStream outToServer = socket.getOutputStream(); 
      DataOutputStream out = new DataOutputStream(outToServer); 
      Log.i(debugString, "Connected_reg!"); 
      out.writeUTF("3"); 


      InputStream inFromServer = socket.getInputStream(); 
      DataInputStream in = new DataInputStream(inFromServer); 
      Log.i(debugString, in.readUTF()); 
      string= in.readUTF(); 

     } 
     catch (Exception e) { 
      Log.e(debugString, e.getMessage()); 
     } 


     return null; 
    } 


    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected void onPostExecute(String s) { 

     //super.onPostExecute(s); 

       Context context = getApplicationContext(); 
       CharSequence text = string; 
       int duration = Toast.LENGTH_SHORT; 
       Toast toast = Toast.makeText(context, text, duration); 
       toast.show(); 
    } 


} 
+0

好像你正在遭受'上下文'问题。也许[本文](https://possiblemobile.com/2013/06/context/)可以帮助您 – Pelocho

回答

0

这可能是与上下文做。

我以前遇到过问题,getApplicationContext不能用于某些特定的事情,尽管不记得我的头顶是什么形式。

而不是使用getApplicationContext,在调用异步任务的活动中,将this放在构造函数调用中。例如,假设你是从MainActivity去改线new test().execute();test(MainActivity.this).execute();

然后在异步类创建构造函数

public test(Context context),并设置全局类变量是上下文的值,然后使用这在你的toast.makeText中,而不是getApplicationContext返回的内容。

也看看logcat,看看是否有任何错误或异常被抛出,它可能也值得在onpostexecute方法中添加一个日志行,只是为了仔细检查你是否定义在那里。

+1

onPostExecute在UI线程上按设计运行。 https://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result) –

+0

对不起,忘了这一点,我用一个替代方案更新了我的答案 – Boardy

0

测试类中创建构造函数,该类接收上下文并在Toast.makeText中使用该上下文。将主机活动上下文传递给该构造函数。

getApplicationContext()是一个Context类方法,AsyncTask不是该类所固有的。我想你是在一个范围内,你可以调用该方法,但该范围上下文无效的范围内,您正在调用Toast.makeText方法。