为什么我的UI只在AsyncTask完成时显示



我在MainActivity中放了一个扩展AsycTask的名为RetrieveHttp的子类,它应该在后台做一些处理工作。

"活动"的工作方式如下:显示UI,启动后台任务(检索URL,将内容解析为字符串数组(,当AsyncTask完成时,它应该在UI上创建Toast。

不幸的是,UI正在等待doInBackground()方法完成的任务。只有当AsyncTask完成时,才会显示UI,同时用户只看到黑屏。你能给我一些建议吗?我的代码出了什么问题?

public class Splashscreen extends Activity implements OnClickListener {
private String questions[];
//HTTP-Downloader to InputStream
private RetrieveHttp myHttp = new RetrieveHttp();
@Override
public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    setContentView(R.layout.hauptmenue);
    //..implementing some listeners here, referencing GUI elements
    try {
        questions = myHttp.execute("http://myurl.de").get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.hauptmenue, menu);     
    return true;
}
public void onClick(View v) {
    //doing some stuff...
}
public class RetrieveHttp extends AsyncTask<String, Void, String[]> {
    protected void onPreExecute() {
    }
    @Override
    protected String[] doInBackground(String... params) {
        URL url;
        String string = "";
        String[] questions = null;
        InputStream content = null;
        try {
            url = new URL(params[0]);
            content = getInputStreamFromUrl(url.toString());
            try {
                // Stream to String
                string = CharStreams.toString(new InputStreamReader(
                        content, "UTF-8"));
                questions = string.split("#");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return questions;
    }
    protected void onPostExecute(String[] string) {
        Toast.makeText(getApplicationContext(), 
                    "Finished", Toast.LENGTH_LONG).show();
        return;
    }
}
public static InputStream getInputStreamFromUrl(String url) {
    InputStream content = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet(url));
        content = response.getEntity().getContent();
    } catch (Exception e) {
        Log.e("[GET REQUEST]", "Network exception", e);
    }

    return content;
}
}

因为这行

questions = myHttp.execute("http://myurl.de").get();

CCD_ 7方法等待异步任务完成,基本上否定了异步任务应该做的事情

删除get并在asynctask的onPostExecute中设置questions,UI将像正常一样显示

最新更新