异步任务和Toast - Android

时间:2014-11-20 18:25:44

标签: android android-asynctask toast

我开始使用Android Studio同步我的应用。我的代码是:

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

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

        //Declaration of variables
        String User = strings[0];
        String Pass = strings[1];
        DefaultHttpClient httpClient;
        HttpPost Request = new HttpPost(url_Loguin);
        HttpResponse Response;
        HttpParams httpParameters = new BasicHttpParams();


        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        httpClient = new DefaultHttpClient(httpParameters);


        List<NameValuePair> BodyRequest_Elements = new ArrayList<NameValuePair>();
        BodyRequest_Elements.add(new BasicNameValuePair("user_name", User));
        BodyRequest_Elements.add(new BasicNameValuePair("user_passwd", Pass));

        try {
            HttpEntity entity = new UrlEncodedFormEntity(BodyRequest_Elements);
            Request.setHeader(entity.getContentType());
            Request.setEntity(entity);

            Response = httpClient.execute(Request);

            HttpEntity entity2 = Response.getEntity();
            InputStream is = entity2.getContent();

            return Response.toString();
        }
        catch (Exception ex){
            Log.getStackTraceString(ex);
            return null;
        }
    }

    protected void onPostExecute(String result){
        Toast.makeText(this, "Task Finalized: " + result, Toast.LENGTH_SHORT).show();
    }
}

这个类是我的主要活动(Loguin_Activity)的外部类(Sync_Class),当我在toast中调用它时,给我错误。那么如何从我的活动中发送Context?提前致谢,对不起我的英语!

PD1:如果您需要更多代码或信息建议我! :d

3 个答案:

答案 0 :(得分:1)

在你的Task类中,创建一个构造函数并给它你的上下文:

private class Check_Loguin_Request
{
  Context cx;
  public Check_Loguin_Request(Context cx)
  {
    this.cx=cx;
  }
}

然后在OnPostExecute中使用此cx

protected void onPostExecute(String result)
{
   Toast.makeText(cx, "Task Finalized: " + result, Toast.LENGTH_SHORT).show();
}

像这样使用这个类:

Check_Loguin_Request login=new Check_Loguin_Request(getBaseContext());

答案 1 :(得分:0)

将Context对象传递给AsyncTask的构造函数。

public class MyTask extends AsyncTask<?, ? ,?> {
    private Context mContext;

    public MyTask(Context context) {
        mContext = context;
    } 
}

然后,在构建AsyncTask时:

MyTask task = new MyTask(this);
task.execute(...);

您可以使用此mContext参考显示Toast。

答案 2 :(得分:0)

Use Context context;
context=this;

Toast toast = Toast.makeText(context, "Your Text", +3);
toast.show();