2016-04-03 50 views
0

我正在使用volley來加載JSON數據。當onResponse被調用時,應用程序崩潰

這是MainActivity

public class MainActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener { 

    private final String TAG = "MainActivity"; 


    //Creating a list of posts 
    private List<PostItems> mPostItemsList; 

    //Creating Views 
    private RecyclerView recyclerView; 
    private RecyclerView.Adapter adapter; 
    private RecyclerView.LayoutManager layoutManager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Log.d(TAG, "Device rotated and onCreate called"); 

     //Initializing Views 
     recyclerView = (RecyclerView) findViewById(R.id.post_recycler); 
     layoutManager = new LinearLayoutManager(this); 
     recyclerView.setLayoutManager(layoutManager); 


     //Initializing the postlist 
     mPostItemsList = new ArrayList<>(); 
     adapter = new PostAdapter(mPostItemsList, this); 

     recyclerView.setAdapter(adapter); 

     if (NetworkCheck.isAvailableAndConnected(this)) { 
      //Caling method to get data 
      getData(); 
     } else { 
      final Context mContext; 
      mContext = this; 
      final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
      alertDialogBuilder.setTitle("No Internet Connection"); 
      alertDialogBuilder.setMessage("Failed to load. Please ensure you're connected to the internet and try again."); 
      alertDialogBuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        if (!NetworkCheck.isAvailableAndConnected(mContext)) { 
         alertDialogBuilder.show(); 
        } else { 
         getData(); 
        } 


       } 
      }); 
      alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        finish(); 

       } 
      }); 
      alertDialogBuilder.show(); 

     } 

    } 

    //This method will get data from the web api 
    private void getData(){ 

     Log.d(TAG, "getData called"); 
     //Showing progress dialog 
     final ProgressDialog progressDialog = ProgressDialog.show(this, null, "Loading posts", false, false); 

     //Creating a json request 
     JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL, 
       new Response.Listener<JSONArray>() { 
        @Override 
        public void onResponse(JSONArray response) { 
         Log.d(TAG, "onResponse called"); 
         //Dismissing the progress dialog 
         progressDialog.dismiss(); 


         //calling method to parse json array 
         parseData(response); 

        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 

        } 
       }); 

     //Creating request queue 
     RequestQueue requestQueue = Volley.newRequestQueue(this); 

     //Adding request to the queue 
     requestQueue.add(jsonArrayRequest); 
    } 


} 

如果應用程序啓動時,我不旋轉,它加載&解析JSON相當好的;但如果應用程序啓動並且我多次旋轉設備,則應用程序會在調用onResponse時立即崩潰。

這是堆棧跟蹤

04-03 12:46:10.493 22221-22221/com.example.poster D/MainActivity: Device rotated and onCreate called 
04-03 12:46:10.493 22221-22221/com.example.poster D/MainActivity: getData called 
04-03 12:46:11.234 22221-22221/com.example.poster D/MainActivity: Device rotated and onCreate called 
04-03 12:46:11.234 22221-22221/com.example.poster D/MainActivity: getData called 
04-03 12:46:12.675 22221-22221/com.example.poster D/MainActivity: Device rotated and onCreate called 
04-03 12:46:12.685 22221-22221/com.example.poster D/MainActivity: getData called 
04-03 12:46:14.096 22221-22221/com.example.poster D/MainActivity: Device rotated and onCreate called 
04-03 12:46:14.096 22221-22221/com.example.poster D/MainActivity: getData called 
04-03 12:46:15.278 22221-22221/com.example.poster D/MainActivity: Device rotated and onCreate called 
04-03 12:46:15.288 22221-22221/com.example.poster D/MainActivity: getData called 
04-03 12:46:15.448 22221-22221/com.example.poster D/MainActivity: onResponse called 
04-03 12:46:15.448 22221-22221/com.example.poster E/AndroidRuntime: FATAL EXCEPTION: main 
                    Process: com.example.poster, PID: 22221 
                    java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{7873bab V.E..... R......D 0,0-480,174} not attached to window manager 
                     at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:396) 
                     at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:322) 
                     at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116) 
                     at android.app.Dialog.dismissDialog(Dialog.java:341) 
                     at android.app.Dialog.dismiss(Dialog.java:324) 
                     at com.example.poster.MainActivity$4.onResponse(MainActivity.java:142) 
                     at com.example.poster.MainActivity$4.onResponse(MainActivity.java:137) 
                     at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65) 
                     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) 
                     at android.os.Handler.handleCallback(Handler.java:739) 
                     at android.os.Handler.dispatchMessage(Handler.java:95) 
                     at android.os.Looper.loop(Looper.java:135) 
                     at android.app.ActivityThread.main(ActivityThread.java:5910) 
                     at java.lang.reflect.Method.invoke(Native Method) 
                     at java.lang.reflect.Method.invoke(Method.java:372) 
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 

從堆棧跟蹤,線142 progressDialog.dismiss();和線路137 new Response.Listener<JSONArray>() {

任何想法可能會導致這個和它的解決方案?

更新:我正在考慮編碼它,所以只有在第一次創建應用程序時才調用getData()。這是因爲,在配置更改(在本例中爲旋轉)後重新創建活動時,會調用getData()。所以這會導致活動重新加載。這可能嗎?即僅在第一次調用getData()時,纔會創建活動。

+0

把你parseData代碼 –

+0

但堆棧跟蹤並沒有使parseData提?它真的需要嗎?如果我錯了,請糾正我。 – Faraday

+0

更改'最終ProgressDialog progressDialog = ProgressDialog。show(this,null,「加載帖子」,false,false);'OnCreate()' – Kathi

回答

5

當應用旋轉,activity被重建。現在您已獲得ProgressDialogprogressDialog的實例。所以當活動旋轉時,舊的活動被破壞,因此這個實例progressDialog被破壞。現在

,任務是在後臺線程運行,當它返回時,它找不到progressDialog,因爲它已經被破壞,因此目前not attached to window managerIllegalArgumentException)。

所以最好在訪問它之前檢查實例progressDialogonResponse

嘗試使用ProgressDialog這樣的:

定義一個全局實例: private ProgressDialog progressDialog;

getData方法:

private void getData(){ 

    Log.d(TAG, "getData called"); 
    //Showing progress dialog 
    progressDialog = new ProgressDialog(MainActivity.this); 
    progressDialog.setMessage("Loading posts"); 
    progressDialog.show(); 

onResponse回調:

if(progressDialog!=null){ 
    progressDialog.hide(); 
} 

onDestroy活動:

if(progressDialog!=null) progressDialog.dismiss(); // to prevent memory leak 
+0

我該怎麼做?並且,請問我已經更新了這個問題。 – Faraday

+0

謝謝先生!它像魔術一樣工作!但是我有一個coupla問題:爲什麼我們不直接從'onRespose'調用'progressDialog.dismis()'並在'onDestroy'中忘記它?其次,當配置更改後重新創建活動時,我不能阻止'getData()'被調用嗎? – Faraday

0

您只需檢查對象null何時關閉progressdialog

ProgressDialog progressDialog = ProgressDialog.show(this, null, "Loading posts", false, false); 

if(progressDialog!=null) 
progressDialog.dismiss(); 
相關問題