2014-10-09 3 views
1

나는 안드로이드 애플리케이션을 개발 중입니다.유출 된 창을 피하기 위해 AsyncHttpClient 작업에서 ProgressDialog를 적절히 관리하십시오. Android

AsyncHttpClient를 사용하기 위해 내 응용 프로그램에서 서버로 여러 요청을해야합니다.

내 앱의 일부에 사용자 프로필과 일부 일정을 표시 할 타임 라인이 있습니다. 사용자가 로그인 할 때 프로필 정보와 타임 라인 정보를 얻어서 서버에 3 가지 다른 요청을해야합니다.

첫 번째 요청 : 로그인 -> 쿠키 저장 및 세션 정보를 SharedPreferences 두 번째 요청 : 프로필 가져 오기 -> 사용자의 개인 정보를 저장하십시오. 세 번째 요청 : 사용자 타임 라인 가져 오기 -> 현재 사용자와 관련된 게시물 및 이벤트를 저장합니다.

public static void login(final String email, final String password, 
      final Context context, final Context appContext, final Resources res) { 

     prgDialog = new ProgressDialog(context); 
     prgDialog.setMessage(res.getString(R.string.dialog_please_wait)); 
     prgDialog.setCancelable(false); 
     prgDialog.show(); 
     cookieStore = new PersistentCookieStore(appContext); 
     client.setCookieStore(cookieStore); 

     RequestParams params = new RequestParams(); 
     params.put("user_session[email]", email); 
     params.put("user_session[password]", password); 

     client.addHeader("Accept", HEADER); 

     client.post(getAbsoluteUrl(LOGIN_PATH), params, 
       new JsonHttpResponseHandler() { 

        @Override 
        public void onFailure(int statusCode, 
          org.apache.http.Header[] headers, 
          java.lang.String responseString, 
          java.lang.Throwable throwable) { 
         prgDialog.hide(); 
         if (statusCode == 404) { 
          Toast.makeText(context, 
            res.getString(R.string.error_404), 
            Toast.LENGTH_LONG).show(); 
         } else if (statusCode == 500) { 
          Toast.makeText(context, 
            res.getString(R.string.error_500), 
            Toast.LENGTH_LONG).show(); 
         } else if (statusCode == 401) { 
          Toast.makeText(context, 
            res.getString(R.string.login_401), 
            Toast.LENGTH_LONG).show(); 
         } else { 
          Toast.makeText(
            context, 
            "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", 
            Toast.LENGTH_LONG).show(); 
         } 
        } 

        @Override 
        public void onSuccess(int statusCode, Header[] headers, 
          JSONObject response) { 
         if (statusCode == 200) { 
          // In this case the JSONOBject has the user 
          // credentials, such as user_id, person_id 
          // user_instance_type and user_instance_id 
          // Parse them into an object that has the same 
          // attributes 
          Gson gson = new Gson(); 
          UserCredentials userCredentials = gson.fromJson(
            response.toString(), UserCredentials.class); 

          setInitialPrefs(userCredentials, appContext); 

          // Get the user profile and save into the 
          // database 
          getUserProfile(userCredentials.getUser_id(), 
            context, appContext, prgDialog); 

          // Get the timeline 
          getWalls(true, context, appContext, prgDialog); 
         } 

        } 
       }); 
    } 

두 가지 방법이 getUserProfile 및 getWalls 비동기 요청 자체입니다

여기 내 로그인 요청입니다. 당신은 코드를 볼 경우

public static void getUserProfile(int userId, final Context context, 
      final Context appContext, final ProgressDialog prgDialog) { 

     prgDialog.show(); 

     cookieStore = new PersistentCookieStore(appContext); 
     client.setCookieStore(cookieStore); 
     client.addHeader("Accept", HEADER); 

     client.get(getAbsoluteUrl(USERS_PATH + userId), 
       new JsonHttpResponseHandler() { 
        @Override 
        public void onFailure(int statusCode, 
          org.apache.http.Header[] headers, 
          java.lang.String responseString, 
          java.lang.Throwable throwable) { 
         prgDialog.hide(); 
         if (statusCode == 404) { 
          Log.d(TAG, "404 getting profile"); 
         } else if (statusCode == 500) { 
          Toast.makeText(
            context, 
            context.getResources().getString(
              R.string.error_500), 
            Toast.LENGTH_LONG).show(); 
          } else if (statusCode == 401) { 
          Log.d(TAG, "401 getting profile"); 
         } else { 
          Log.d(TAG, "Error getting profile"); 
         } 
        } 

        @Override 
        public void onSuccess(int statusCode, Header[] headers, 
          JSONObject response) { 

         if (statusCode == 200) { 
          // In this case the JSONOBject has the user 
          // profile 
          // Parse them into an object that has the same 
          // attributes 
          Gson gson = new Gson(); 
          UserProfile userProfile = gson.fromJson(
            response.toString(), UserProfile.class); 
          UserProfileController profileController = new UserProfileController(
            context); 
          profileController.insertProfile(userProfile); 
         } 

        } 

       }); 
    } 

public static void getWalls(final boolean firstTime, final Context context, 
      Context appContext, final ProgressDialog prgDialog) { 
     cookieStore = new PersistentCookieStore(appContext); 

     prgDialog.show(); 
     client.setCookieStore(cookieStore); 
     client.addHeader("Accept", HEADER); 

     client.get(getAbsoluteUrl(WALLS_PATH), new JsonHttpResponseHandler() { 
      @Override 
      public void onFailure(int statusCode, 
        org.apache.http.Header[] headers, 
        java.lang.String responseString, 
        java.lang.Throwable throwable) { 
       prgDialog.hide(); 
       if (statusCode == 404) { 
        Log.d(TAG, "404 getting walls"); 
       } else if (statusCode == 500) { 
        Toast.makeText(
          context, 
          context.getResources().getString(
            R.string.error_500), 
          Toast.LENGTH_LONG).show(); 
        } else if (statusCode == 401) { 
        Log.d(TAG, "401 getting walls"); 
       } else { 
        Log.d(TAG, "Error getting walls"); 
       } 
      } 

      @Override 
      public void onSuccess(int statusCode, Header[] headers, 
        JSONObject response) { 
       if (statusCode == 200) { 
        Gson gson = new Gson(); 

        TimelineController.getInstance(context); 

        Timeline timeline = gson.fromJson(response.toString(), 
          Timeline.class); 

        TimelineController.insertTimeline(timeline); 

        if (firstTime) { 
         prgDialog.hide(); 
         Intent i = new Intent(context, TimelineActivity.class); 
         i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP 
           | Intent.FLAG_ACTIVITY_CLEAR_TASK 
           | Intent.FLAG_ACTIVITY_NEW_TASK); 
         context.startActivity(i); 
         ((AuthActivity) context).finish(); 
        } else { 
         prgDialog.hide(); 
         Intent i = new Intent(context, TimelineActivity.class); 
         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
           | Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         context.startActivity(i); 
        } 
       } 
      } 

     }); 
    } 

, 제가 진행 대화 상자가 수행하려고하는

것은 마지막 요청을 완료합니다 (getWalls 요청)입니다 때까지 같이 유지하는 것입니다 때때로 다음은 코드는 동일한 사용자 또는 다른 사용자로 로그 아웃하고 다시 로그인 할 때 android.view.WindowLeaked 예외가 발생하고 진행 상황 대화 상자를 잘 관리하지 못해서라고 생각합니다.

누출 된 창을 방지하기 위해 진행률 대화 상자를 올바르게 관리하려면 어떻게해야합니까?

누구든지이 문제에 도움을 주시기 바랍니다. 미리 감사드립니다.

답변

0

문제가 진행 대화 상자라고 가정 할 때 정적 표시 방법 중 하나를 사용하려고 할 수 있습니다. 다음 코드는 진행 대화가 이중 또는 삼중 게재되지 않았는지 확인합니다 :

if (progressDialog == null || !progressDialog.isShowing()) { 
    progressDialog = ProgressDialog.show(activity, "Changing password ...", "Please wait.", true, false); 
} 

그리고 당신은 정의

private ProgressDialog progressDialog;