2013-05-15 1 views
1

튜토리얼 링크를 사용 : http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/내 alertdialog에 어디서 추가해야하며 json에서 값을 얻는 방법은 무엇입니까?

문제는 다음과 같습니다 내가 작업 로그인이 내 응용 프로그램에 대한 활동을 가입하십시오. 그러나 일부 정보를 표시하기 위해 사용자가 로그인/가입 버튼을 클릭하면 알림 대화 상자를 표시하려고합니다.

위 튜토리얼 링크를 따라 AlertDialogManager.java를 만들었습니다. 이 로그인 버튼 내 코드입니다 :

try{             
      int success = json.getInt(TAG_SUCCESS); 
      //String message = json.getString(TAG_MESSAGE); 
      //Log.v("SignUp", "Checkpoint 3"); 


      if (success == 1) { 
       session.createLoginSession(email); 

       Intent i = new Intent(getApplicationContext(), Home.class); 
       startActivity (i); 

       finish(); 
      }else{ 
       //failed to login     
      } 
     } catch (JSONException e){ 
      e.printStackTrace(); 
     } 
응용 프로그램에서 사용자를 로그인에 실패 할 때 내에 AlertDialog 코드 나는 섹션의에 AlertDialog 코드를 추가하는 시도

:.

alert.showAlertDialog(Login.this,"Login failed", "Bla bla bla", false); 

를 내가 시도 할 때마다 전체 응용 프로그램이 충돌, 로그인 버튼을 클릭하고 나에게 아래의 로그 캣 보여

05-15 10:08:55.641: W/dalvikvm(2338): threadid=11: thread exiting with uncaught exception (group=0x40a71930) 
05-15 10:08:55.701: E/AndroidRuntime(2338): FATAL EXCEPTION: AsyncTask #1 
05-15 10:08:55.701: E/AndroidRuntime(2338): java.lang.RuntimeException: An error occured while executing doInBackground() 
05-15 10:08:55.701: E/AndroidRuntime(2338):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 
05-15 10:08:55.701: E/AndroidRuntime(2338): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 

난 여전히 아주 새로운 오전 안드로이드 프로그래밍>,321로를 0 그래서 누군가 나를 도울 수 있습니까? 감사! 네가 필요로하는 다른 것을 말하면 내가 여기에 올리겠습니다.

전체 코드는 다음과 같습니다 : 공용 클래스 로그인하면 UI 스레드가 아닌 스레드, 예를 들어 AsyncTask를이 대화를 만들 같이이 보이는 활동 {

private ProgressDialog pDialog; 

//Alert dialog manager 
AlertDialogManager alert = new AlertDialogManager(); 

//Session manager 
SessionManager session; 

JSONParser jsonParser = new JSONParser(); 
EditText C_Email; 
EditText C_Password; 

public static final String DOMAIN = "192.168.0.112"; //Home 
//public static final String DOMAIN = "172.18.74.146"; 
//URL to login 
private static String url_login = "http://" + DOMAIN + "/iChop/login.php"; 

//JSON Node names 
private static final String TAG_SUCCESS = "success"; 
//private static final String TAG_MESSAGE = "message"; 

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

    //Session manager 
    session = new SessionManager(getApplicationContext()); 

    //Edit Text 
    C_Email = (EditText) findViewById(R.id.C_Email); 
    C_Password = (EditText) findViewById(R.id.C_Password); 

    Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show(); 

    //Login button 
    Button Login = (Button) findViewById(R.id.Login); 

    //Button click event 
    Login.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View view) { 
      // creating new customer in background 
      new CustomerLogin().execute(); 
     } 
    }); 

} 


class CustomerLogin extends AsyncTask<String, String, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(Login.this); 
     pDialog.setMessage("Logging you in!"); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    protected String doInBackground(String... args){ 
     String email = C_Email.getText().toString(); 
     String password = C_Password.getText().toString(); 

     //Building parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("email", email)); 
     params.add(new BasicNameValuePair("password", password)); 

     /** 
     Log.d("C_Email", email); 
     Log.d("C_Password", password); 
     **/ 

     //getting JSON object 
     JSONObject json = jsonParser.makeHttpRequest(url_login, "POST", params); 
     Log.v("SignUp", "Checkpoint 1"); 

     //check log cat for response 
     Log.d("Create Response", json.toString()); 
     Log.v("SignUp", "Checkpoint 2"); 

     //check for success tag 
     try{             
      int success = json.getInt(TAG_SUCCESS); 
      //String message = json.getString(TAG_MESSAGE); 
      //Log.v("SignUp", "Checkpoint 3"); 


      if (success == 1) { 
       session.createLoginSession(email); 

       Intent i = new Intent(getApplicationContext(), Home.class); 
       startActivity (i); 

       finish(); 
      }else{ 
       //failed to login 

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

     return null; 
    } 

    protected void onPostExecute(String file_url){ 
     pDialog.dismiss(); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.login, menu); 
    return true; 
} 

public void SignUp (View view) { 
    Intent signup = new Intent (this, SignUp.class); 
    startActivity(signup); 
} 
} 

답변

1

이 코드는, 당신은 아마 텐트 또는 OnPostExceute에서 경고 대화 상자를 호출해야합니다. 당신의 OnPostExecute이를 실행

봅니다

if (success == 1) { 
       session.createLoginSession(email); 

       Intent i = new Intent(getApplicationContext(), Home.class); 
       startActivity (i); 

       finish(); 
      }else{ 
       alert.showAlertDialog(Login.this,"Login failed", "Bla bla bla", false); 

      } 

가 작동하는지 알려주세요.

+0

안녕하세요 @ 오엠, 당신의 방식대로 해봤지만 경고 대화 상자를 보여줍니다! 하지만 JSON의 응답을받는 방법에 따라 메시지를 설정하려면 어떻게해야합니까? 다음과 같이 : { "success": 0, "message": "모든 필드를 채워주세요!"} –

+0

메시지 문자열을'doInBackground'에 저장하고'showAlertDialog' 메쏘드에 그 문자열을 매개 변수로 전달하십시오. – Oam

+0

doInBackground에서 문자열 메시지 = json.getString (TAG_MESSAGE);을 작성했습니다 .... 그러나 onPostExecute에서 메시지를 사용할 때 오류를 나타냅니다 (변수를 확인할 수 없음) –

0

을 확장합니다. 대화 상자는 UI 스레드에서 표시되어야합니다. 당신의 대화 : 다시는 로그인 사점 또는 아니었다면에서 시작된 활동에 대한 당신의 AsyncTask를보고, 그때 보여주지

편집 : 당신 AsyncTask를 현재 String 반환하지만 그것은 항상 당신은 분명 돈 null이다 ' 아무것도 돌려주지 마라. AsyncTask가 '성공'에 대한 부울을 반환하도록합니다 (로그인이 성공했는지 여부). CustomerLogin extends AsyncTask<String, String, String>CustomerLogin extends AsyncTask<String, String, Boolean>으로 변경하고 지금 성공한 nullString 대신에 로그인 성공에 대한 부울을 반환합니다. 그런 다음 UI 스레드에서 다시 실행되는 onPostExecute에서이 부울을 사용할 수 있습니다. 대화 상자를 만들 수 있습니다.

+0

@Ascorbin ... 신속한 답변 주셔서 감사합니다 ...하지만 어떻게해야합니까? –

+0

수정 된 답변을 확인하십시오. – FWeigl

+0

"성공했을 때 (현재 null 문자열 대신에) 로그인 성공에 대한 부울 값을 얻었을 때 혼란스러워합니다. 그러면 UI 스레드에서 다시 실행되는 onPostExecute에서이 부울 값을 사용할 수 있습니다. 거기에서 대화. " 날 치울 수있어? –

0

사용 그것은 당신이 의도와 doInBackground에 경고 대화 상자를 호출하는 것 button.setOnClickListener()

Runnable runnable = new Runnable() { 
      @Override 
      public void run() { 
       handler.post(new Runnable() { // This thread runs in the UI 
        @Override 
        public void run() { 
         // Update the UI, call your asynctask 
        } 
       }); 
      } 
     }; 
     new Thread(runnable).start(); 
    } 
+0

처리기에서 문제가 발생했습니다 ... 거기에 오류가 표시됩니다 @@ –

+0

오류가 무엇입니까? –

+0

erm ...핸들러 아래 빨간 선 –

관련 문제