2015-01-28 2 views
0

나는 사용자를 확인할 수 있도록 로그인 기능을 만들려고합니다. 나는 AsyncTask 클래스에 Username, Password 변수를 전달하지만, 그것을 사용하기 위해 결과를 얻기 위해 뜨겁다. 어떤 도움이 필요합니까?안드로이드 로그인 HTTP 게시물, 결과를 얻으십시오

btnLogin.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      if(txtUsername.getText().toString().trim().length() > 0 && txtPassword.getText().toString().trim().length() > 0) 
      { 
       // Retrieve the text entered from the EditText 
       String Username = txtUsername.getText().toString(); 
       String Password = txtPassword.getText().toString(); 
       /*Toast.makeText(MainActivity.this, 
         Username +" + " + Password+" \n Ready for step to post data", Toast.LENGTH_LONG).show();*/ 

       String[] params = {Username, Password}; 
       // we are going to use asynctask to prevent network on main thread exception 
       new PostDataAsyncTask().execute(params); 

       // Redirect to dashboard/home screen. 
       login.dismiss(); 
      } 
      else 
      { 
       Toast.makeText(MainActivity.this, 
       "Please enter Username and Password", Toast.LENGTH_LONG).show(); 

      } 
     } 
    }); 

그런 다음 내가 검사를 수행 할 AsynkTask를 사용하지만 결과를 얻을 수와 변수에 저장하는 방법을 모른다 (I 때문에 웹 사이트의 제한으로 소스 코드의 일부를 게시하고있다). 어떤 도움이 필요합니까?

public class PostDataAsyncTask extends AsyncTask<String, String, String> { 

    protected void onPreExecute() { 
     super.onPreExecute(); 
     // do stuff before posting data 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     try { 
      // url where the data will be posted 
      String postReceiverUrl = "http://server.com/Json/login.php"; 
      Log.v(TAG, "postURL: " + postReceiverUrl); 
      String line = null; 
      String fail = "notok"; 

      // HttpClient 
      HttpClient httpClient = new DefaultHttpClient(); 

      // post header 
      HttpPost httpPost = new HttpPost(postReceiverUrl); 

      // add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("UserName", params[0])); 
      nameValuePairs.add(new BasicNameValuePair("Password", params[1])); 

      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // execute HTTP post request 
      HttpResponse response = httpClient.execute(httpPost); 
      HttpEntity resEntity = response.getEntity(); 
      line = resEntity.toString(); 
      Log.v(TAG, "Testing response: " + line); 

      if (resEntity != null) { 

       String responseStr = EntityUtils.toString(resEntity).trim(); 
       Log.v(TAG, "Response: " + responseStr); 
       Intent Hotels_btn_pressed = new Intent(MainActivity.this, Hotels.class); 
       startActivity(Hotels_btn_pressed); 
       // you can add an if statement here and do other actions based on the response 
       Toast.makeText(MainActivity.this, 
         "Error! User does not exist", Toast.LENGTH_LONG).show(); 
      }else{ 
       finish(); 
      } 

     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String lenghtOfFile) { 
     // do stuff after posting data 
    } 
} 
+0

[AsyncTask Android 예제] (http://stackoverflow.com/questions/9671546/asynctask-android-example) –

+0

어디에서 응답을 사용할 수 있습니까? 'PostDataAsyncTask'가 별도의 클래스 인 경우에는 onPostExecute가 호출 될 때 Activity에서 실행되는 사용자 정의 리스너를 사용합니다. –

+0

다음 응답에 전달하기 위해 변수에 저장된 응답을 받고 싶습니다. –

답변

0

최고의 코드 리팩토링이 아니라 힌트를 제공합니다.

public interface LoginListener { 
    void onSuccessfulLogin(String response); 
    void onFailedLogin(String response); 
} 

'MainActivity'클래스는 해당 인터페이스를 구현하고 청취자 'PostDataAsyncTask'로 자신을 설정합니다 :

내가 인터페이스를 만들 것이라고는 ('LogInListener'를 호출 할 수 있습니다). 그래서, 주요 활동에서 비동기 작업을 생성하는 것은 같을 것이다 :

내가 새 파일에 'PostDataAsyncTask'클래스를 움직일 것입니다
String[] params = {Username, Password}; 
// we are going to use asynctask to prevent network on main thread exception 
PostDataAsyncTask postTask = new PostDataAsyncTask(this); 
postTask.execute(params); 

: 그래서

public class PostDataAsyncTask extends AsyncTask<String, String, String> { 
    private static final String ERROR_RESPONSE = "notok"; 

    private LoginListener listener = null; 

    public PostDataAsyncTask(LoginListener listener) { 
     this.listener = listener; 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     String postResponse = ""; 
     try { 
      // url where the data will be posted 
      String postReceiverUrl = "http://server.com/Json/login.php"; 

      // HttpClient 
      HttpClient httpClient = new DefaultHttpClient(); 

      // post header 
      HttpPost httpPost = new HttpPost(postReceiverUrl); 

      // add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("UserName", params[0])); 
      nameValuePairs.add(new BasicNameValuePair("Password", params[1])); 

      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // execute HTTP post request 
      HttpResponse response = httpClient.execute(httpPost); 
      HttpEntity resEntity = response.getEntity(); 

      postResponse = EntityUtils.toString(resEntity).trim(); 
     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return postResponse; 
    } 

    @Override 
    protected void onPostExecute(String postResponse) { 
     if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE)) { 
      listener.onFailedLogin(postResponse); 
     } else { 
      listener.onSuccessfulLogin(postResponse); 
     } 
    } 
} 

는 'doInBackground은'에 대한 응답을 반환 'LogInListener'방법을 구현하는 MainActivity에 (UI 스레드에서 실행) 'onPostExecute'및 'onPostExecute'경로 결과 (성공 또는 실패) :

@Override 
public void onSuccessfulLogin(String response) { 
    // you have access to the ui thread here - do whatever you want on suscess 
    // I'm just assuming that you'd like to start that activity 
    Intent Hotels_btn_pressed = new Intent(this, Hotels.class); 
    startActivity(Hotels_btn_pressed); 
} 

@Override 
public void onFailedLogin(String response) { 
    Toast.makeText(MainActivity.this, 
      "Error! User does not exist", Toast.LENGTH_LONG).show(); 
} 

을 나는 단지 새로운 활동을 시작하고 실패한 축배를 보여 주면서 성공을 위해 무엇을하고 싶다고 생각합니다.

+0

당신의 충고에 감사드립니다 !! 한 가지, 응용 프로그램이 응답하지 못하게 게시물을 게시 한 후 ... "LogInListener"메서드를 실행하려고하면 멈추는 것 같습니다. –

+0

어떤 예외가 발생했는지 또는 어떤 일이 일어날 것인가를 설명해 주시겠습니까? – Spiri

+0

비록 PostDataAsyncTask를 e 파일로 이동하지 않았지만 (시간 만 절약하기 위해), 결과를 얻고 계속 진행했습니다. 도와 주셔서 대단히 감사합니다! 좋은 하루 되세요!! –

관련 문제