2016-08-29 97 views
0

活動的開始我有一個異步任務,像這樣在我的應用程序:呼叫異步任務從Android中

private class getUserSummary extends AsyncTask<String, String, JSONObject> { 

    private ProgressDialog pDialog; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(DashboardActivity.this); 
     pDialog.setMessage("Getting sales summary..."); 
     //pDialog.setTitle("Getting sales summary..."); 
     pDialog.setIndeterminate(true); 
     pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    @Override 
    protected JSONObject doInBackground(String... strings) { 
     String JsonResponse = null; 
     String JsonDATA = "email=my email address"; 

     HttpURLConnection urlConnection = null; 
     BufferedReader reader = null; 
     try { 
      ServiceUrl smf = new ServiceUrl(); 
      URL url = new URL(smf.getUserSummaryUrl()); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setDoOutput(true); 
      // is output buffer writter 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

      //set headers and method 
      Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); 
      writer.write(JsonDATA); 
      // json data 
      writer.close(); 

      int responseCode = urlConnection.getResponseCode(); 
      if (responseCode == 400) { 
       InputStream inputResponse = urlConnection.getErrorStream(); 
       reader = new BufferedReader(new InputStreamReader(inputResponse)); 
       StringBuffer errorBuffer = new StringBuffer(); 
       String errorLine; 
       while ((errorLine = reader.readLine()) != null) { 
        errorBuffer.append(errorLine + "\n"); 
       } 
       Log.i("Error text", errorBuffer.toString()); 
       return new JSONObject(errorBuffer.toString()); 
      } 
      //Log.i("Response code", String.valueOf(inputStream)); 

      InputStream inputStream = urlConnection.getInputStream(); 
      //input stream 
      StringBuffer buffer = new StringBuffer(); 
      if (inputStream == null) { 
       // Nothing to do. 
       return null; 
      } 

      reader = new BufferedReader(new InputStreamReader(inputStream)); 

      String inputLine; 
      while ((inputLine = reader.readLine()) != null) 
       buffer.append(inputLine + "\n"); 
      if (buffer.length() == 0) { 
       // Stream was empty. No point in parsing. 
       return null; 
      } 
      JsonResponse = buffer.toString(); 
      //response data 
      Log.i("RESPONSE", JsonResponse); 

      return new JSONObject(JsonResponse); 

     } catch (ProtocolException e) { 
      e.printStackTrace(); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } finally { 
      if (urlConnection != null) { 
       urlConnection.disconnect(); 
      } 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (final IOException e) { 
        Log.e("ERROR", "Error closing stream", e); 
       } 
      } 
     } 
     return null; 
    } 

    protected void onPostExecute(JSONObject result) { 
     pDialog.dismiss(); 
     //post operation here 
    } 
} 

和的onCreate調用()這個方法

 @Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_dashboard); 

    ButterKnife.bind(this); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    initCollapsingToolbar(); 


    new getUserSummary().execute(); 
    } 

我運行這是用戶登錄活動即將被破壞。這就是爲什麼我需要在onCreate()方法上調用它。但我得到這個錯誤時,在onCreate()方法

android.view.WindowLeaked: Activity softlogic.computers.softlogicsalesreward.DashboardActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{5329b90 V.E...... R......D 0,0-1002,348} that was originally added here 
    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:603) 
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326) 
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:109) 
    at android.app.Dialog.show(Dialog.java:505) 
    at softlogic.computers.softlogicsalesreward.DashboardActivity$getUserSummary.onPreExecute(DashboardActivity.java:88) 
    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604) 
    at android.os.AsyncTask.execute(AsyncTask.java:551) 
    at softlogic.computers.softlogicsalesreward.DashboardActivity.onResume(DashboardActivity.java:65) 
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287) 
    at android.app.Activity.performResume(Activity.java:7015) 
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210) 
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426) 
    at android.app.ActivityThread.access$1100(ActivityThread.java:229) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:7325) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

是否有任何其他事件,我可以把這個電話嗎?或者我做錯了什麼?

+0

您是否實現了onPostExecute()? –

+0

添加你的'OnCreate'和'OnResume()' –

+0

發佈活動代碼,你可以在這裏調用asyncTask –

回答

0

你的asyncTask必須是這樣的。看到你的代碼後,你可能會忘記一些AsyncTask.Compare方法來更好地理解這個例子。

這是的AsyncTask的完整的例子:

private class AsyncTaskRunner extends AsyncTask<String, String, String> { 

    private String resp; 
    ProgressDialog progressDialog; 

    @Override 
    protected String doInBackground(String... params) { 
     publishProgress("Sleeping..."); // Calls onProgressUpdate() 
     try { 
      int time = Integer.parseInt(params[0])*1000; 

      Thread.sleep(time); 
      resp = "Slept for " + params[0] + " seconds"; 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
      resp = e.getMessage(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      resp = e.getMessage(); 
     } 
     return resp; 
    } 


    @Override 
    protected void onPostExecute(String result) { 
     // execution of result of Long time consuming operation 
     progressDialog.dismiss(); 
     finalResult.setText(result); 
    } 


    @Override 
    protected void onPreExecute() { 
     progressDialog = ProgressDialog.show(MainActivity.this, 
       "ProgressDialog", 
       "Wait for "+time.getText().toString()+ " seconds"); 
    } 


    @Override 
    protected void onProgressUpdate(String... text) { 
     finalResult.setText(text[0]); 

    } 
} 

調用是這樣的:

new AsyncTaskRunner (this).execute(); 
+0

我已經正確實施了異步任務。但不能在activity的onCreate()方法中調用。 – Sanjeewa

+0

看到我更新的答案。 – KrishnaJ

+0

非常感謝你的時間。並感謝大家。導致此錯誤的'getUserSummaryUrl()'方法出現問題。問題解決了。 – Sanjeewa

0

您忘記調用pDialog.dismiss(); in onPostExecute方法的異步任務

+0

我打電話給pDialog.dismiss();在onPostExecute()方法中。 – Sanjeewa

0

你可以使用線程策略這一點。這很好。 只需在setcontent下面添加兩行即可。

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
    .detectAll() 
    .penaltyLog() 
    .build(); 
StrictMode.setThreadPolicy(policy);