如何从AsyncTask启动一个Activity?

时间:2016-01-10 12:00:41

标签: java android android-studio android-asynctask start-activity

我已经构建了一个AsyncTask,并希望在它结束时启动另一个Activity(onPostExecute),但是它不起作用,我找不到问题。也许String,String,String有问题? 这是我的代码:

public class StartSearch extends AsyncTask<String, String, String> {

    private Activity activity;

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

        StringBuilder sb = new StringBuilder();
        String http = "https://list-creater-service.herokuapp.com/api/v1/search";
        HttpURLConnection urlConnection = null;
        JSONObject json = null;
        HttpResponse response = null;

        try {
            //connect to server
            URL url = new URL(http);
            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setUseCaches(false);
            urlConnection.setConnectTimeout(10000);
            urlConnection.setReadTimeout(10000);
            urlConnection.setRequestProperty("Content-Type","application/json");

            urlConnection.setRequestProperty("Host", "list-creater-service.herokuapp.com");
            urlConnection.connect();

            //Create JSONObject here
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("gamemode", gametype);
            jsonParam.put("country", selCountry);
            jsonParam.put("min_size", minSize);
            jsonParam.put("max_size", maxSize);
            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
            out.write(jsonParam.toString());
            out.close();



            int HttpResult = urlConnection.getResponseCode();
            if(HttpResult == HttpURLConnection.HTTP_OK){

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        urlConnection.getInputStream(),"utf-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                String jsonS = sb.toString();

                JSONArray jsonArray = new JSONArray(jsonS);
                int length = jsonArray.length();

                String[] names = new String[length];

                for (int i = 0; i < length; i++) {
                    JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());

                    ArrayList serverList = new ArrayList();
                    serverList.add(jsonObject.getString("name"));

                    serverData = getSharedPreferences(filename, 0);
                    SharedPreferences.Editor editor = serverData.edit();
                    Set<String> set = new HashSet<String>();
                    set.addAll(serverList);
                    editor.putStringSet("name", set);
                    editor.commit();
                    System.out.println(jsonObject.getString("name"));

                    names[i] = jsonObject.getString("name");
                }

                //String name = jsonObject.getString("name");
                System.out.println("" + sb.toString());

            }else{
                System.out.println(urlConnection.getResponseMessage());
            }

        } catch (MalformedURLException e) {

            e.printStackTrace();
        }
        catch (IOException e) {

            e.printStackTrace();
        } catch (JSONException e) {
            //TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(urlConnection!=null)
                urlConnection.disconnect();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        activity.startActivity(new Intent(activity, ServerIndex.class));
    }

}

需要一些帮助! 谢谢:)

2 个答案:

答案 0 :(得分:1)

您已声明活动活动,但尚未将当前活动上下文分配给它。为其分配当前活动上下文。 像
    活性= currentContext;

答案 1 :(得分:0)

您应该在onPostExecute

中使用runOnUIThread
            runOnUiThread(new Runnable() { 

            public void run() {
                activity.startActivity(new Intent(activity,  ServerIndex.class));
            }});

正如Raghunandan所说,活动没有初始化。您可以使用

从StartSearch类访问startActivity方法
 SomeActivity.this.startActivity  (SomeActivity has to be initialized)

由于onPostExecute在UI线程上运行,您可能会也可能不会调用runOnUIThread。