在AsyncTask中显示Toast

时间:2016-11-05 08:21:42

标签: java android android-asynctask

void permute(string prefix, string rest)
{

if (rest == "")
{
    cout << prefix << endl;
}
else
{
    for (int i = 0; i < rest.length(); i++)
    {
        //test if rest[i] is unique.
        bool found = false;
        for (int j = 0; j < i; j++)
        {
            if (rest[j] == rest[i])
                found = true;
        }
        if (found)
            continue;
        string newPrefix = prefix + rest[i];
        string newRest = rest.substr(0, i) + rest.substr(i + 1);
        permute(newPrefix, newRest);

    }

 }
}

int main()
{
 permute("T", "MAC");
 return 0;
}

但是当我调试并运行应用程序时,它会让Toast显示出来。有没有办法使用AsyncTask执行操作,而它的工作?

谢谢!

8 个答案:

答案 0 :(得分:3)

Toast属于UI。

我们只能在主线程(UI线程)中更新UI。

AsyncTask.doInBackground()永远不会在主线程中被调用,这就是原因。

答案 1 :(得分:1)

您应该使用here中的代码:

public enum Toaster {
    INSTANCE;

    private final Handler handler = new Handler(Looper.getMainLooper());

    public void showToast(final Context context, final String message, final int length) {
        handler.post(
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, message, length).show();
                }
            }
        );
    }

    public static Toaster get() {
        return INSTANCE;
    }
}

然后你可以做

Toaster.get().showToast(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT);

这将在UI线程上运行您的代码,它将起作用。

答案 2 :(得分:1)

这可能会有所帮助

  

onPreExecute(){          //一些代码#1       }

doInBackground() {
    runOnUiThread(new Runnable() {
                public void run() {
                    // some code #3 (Write your code here to run in UI thread)

                }
            });
}

onPostExecute() {
   // some code #3
}

答案 3 :(得分:0)

尝试以下

public class ayncClass extends AsyncTask<String, Void, String> {

    public void onPreExecute(){


    }
    @Override
    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(URL HERE);
        try{
            HttpResponse responseGiven = client.execute(get);
            StatusLine statusLine = responseGiven.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if(statusCode == 404){
                // Toast.makeText(getApplicationContext(), "ERROR", //Toast.LENGTH_SHORT).show();

            }
        } catch(Exception e){

        }
        return String.valueOf(statusCode ); // make this change
    }

    public void onPostExecute(String result){
        super.onPostExecute(s);
 Toast.makeText(getApplicationContext(), result, 
 Toast.LENGTH_SHORT).show();
    }

}

答案 4 :(得分:0)

始终将Toast消息放在PostExecute方法中。

public void onPostExecute(...) {             super.onPostExecute(一个或多个);

    Toast.makeText(context, "Hellooo I am at Post Execute method", Toast.LENGTH_SHORT).show();
    }

答案 5 :(得分:0)

Toast只能从UI线程中显示。在UI线程中调用onPostExecute,因此您可以将statusCode存储在成员变量中,并在onPostExecute方法中检查404并在那里显示Toast。像这样:

public class ayncClass extends AsyncTask<String, Void, String> {

    private int mStatusCode;

    @Override
    protected String doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(URL HERE);
        try{
            HttpResponse responseGiven = client.execute(get);
            StatusLine statusLine = responseGiven.getStatusLine();
            mStatusCode = statusLine.getStatusCode();
        } catch(Exception e){
            // do NOT let catch blocks without log
            // if something bad happens you will never know
        }
        return null;
    }

    public void onPostExecute(...){
        super.onPostExecute(s);
        if(mStatusCode == 404){
            Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
        }
    }
}

或者只是将状态代码作为参数传递给onPostExecute:

public class ayncClass extends AsyncTask<String, Void, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(URL HERE);
        try{
            HttpResponse responseGiven = client.execute(get);
            StatusLine statusLine = responseGiven.getStatusLine();
            return statusLine.getStatusCode();
        } catch(Exception e){
            // do NOT let catch blocks without log
            // if something bad happens you will never know
        }
        return -1;
    }

    public void onPostExecute(Integer statusCode){
        super.onPostExecute(s);
        if(statusCode == 404){
            Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
        }
    }
}

答案 6 :(得分:0)

当您必须在UI线程中显示某些内容(例如Toast消息)时,请写下:

runOnUiThread(new Runnable(){
    public void run() {
        //Interaction with UI (Toast message)
    }
});

答案 7 :(得分:-1)

您无法在doInBackground函数中显示toast,因为UI线程上的doInBackground函数不起作用。您可以将进度发布到onProgressUpdate函数。它适用于 UI线程

<div class="menu-header">
    <ul>
        <?php if (isset($result->num_rows) > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) { ?>
                <li><?php echo $row['Menu_name'];?></li>
            <?php }
        } ?>
    </ul>
</div>