【问题标题】:How to start an Activity from AsyncTask?如何从 AsyncTask 启动 Activity?
【发布时间】:2016-01-10 12:00:40
【问题描述】:

我已经构建了一个 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));
    }

}

需要帮助! 谢谢 :)

【问题讨论】:

  • activity在哪里初始化?
  • 任何异常或错误
  • 你试过Intent方法了吗???
  • 第二行代码privateActivity活动;
  • @YannikPieper new StartSearch (ActivityName.this).execute(stringparams) 然后只需创建一个将上下文作为参数的构造函数并使用它。请注意确保您的上下文不会比活动生命周期更长,否则您会面临内存泄漏的风险

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


【解决方案1】:

您已声明了 Activity 活动,但尚未将当前活动上下文分配给它。将当前活动上下文分配给它。 喜欢
活动=当前上下文;

【讨论】:

    【解决方案2】:

    你应该在你的 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。

    【讨论】:

    • onPostExecute 在 ui 线程上运行。唯一的问题是发布的问题是缺少对超级的调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2016-12-19
    相关资源
    最近更新 更多