2010-12-20 5 views
1

다음 코드를 사용하여 서버에서 데이터를 가져오고 서버의 값이 GEEK이면 다음 클래스로로드되지만 새보기가로드되지 않습니다. 문제가 무엇인지 말할 수 있습니까?서버에서 데이터 가져 오기 및 Android를 사용하여 새 화면로드

 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     login = (Button) findViewById(R.id.login); 
     username = (EditText) findViewById(R.id.username); 
     password = (EditText) findViewById(R.id.password); 

     login.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
String Re; 
       String mUsername = username.getText().toString(); 
       String mPassword = password.getText().toString(); 

       Re=tryLogin(mUsername, mPassword); 

       if(Re=="GEEK") 
       { 
        Intent i = new Intent(); 
        i.setClassName(v.getContext(),"com.httplogin.MainScreen"); 
        startActivity(i); 

       } 
      } 
     }); 
    } 

    protected String tryLogin(String mUsername, String mPassword) 
    {   
     HttpURLConnection connection; 
     OutputStreamWriter request = null; 

      URL url = null; 
      String response = null;   
      String parameters = "username="+mUsername+"&password="+mPassword; 

      try 
      { 
       url = new URL("http://serverspace/script.php"); 
       connection = (HttpURLConnection) url.openConnection(); 
       connection.setDoOutput(true); 
       connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
       connection.setRequestMethod("POST");  

       request = new OutputStreamWriter(connection.getOutputStream()); 
       request.write(parameters); 
       request.flush(); 
       request.close();    
       String line = "";    
       InputStreamReader isr = new InputStreamReader(connection.getInputStream()); 
       BufferedReader reader = new BufferedReader(isr); 
       StringBuilder sb = new StringBuilder(); 
       while ((line = reader.readLine()) != null) 
       { 
        sb.append(line + "\n"); 
       } 
       // Response from server after login process will be stored in response variable.     
       response = sb.toString(); 

       isr.close(); 
       reader.close(); 


      } 
      catch(IOException e) 
      { 
       Toast.makeText(this,e.toString(),0).show(); 
      } 
      return response; 
    } 
} 

답변

2

이를 참조하십시오 :이 항목에 대한 자세한 내용은

new LoginTask().execute(mUsername, mPassword); 

로그인 작업은 다음과 같이 정의되어야한다 비동기 작업을 생성, 대신에서 onCreate에서 tryLogin에 전화로, this article

간단히 읽기 코드 .............., String의 공간을 없애기 위해 trim 함수를 사용하십시오 ..

public class HttpLogin extends Activity { 
    /** Called when the activity is first created. */ 
    private Button login; 
    private EditText username, password; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     login = (Button) findViewById(R.id.login); 
     username = (EditText) findViewById(R.id.username); 
     password = (EditText) findViewById(R.id.password); 

     login.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
      String Re; 
       String mUsername = username.getText().toString(); 
       String mPassword = password.getText().toString(); 

       Re=tryLogin(mUsername, mPassword); 
       Log.d(" Check ","Here"); 
       Log.d("Re",Re); 
       String temp_check=Re.trim(); 
       if(temp_check.equals("GEEK")) 
       { 
        Intent i = new Intent(); 
        i.setClassName(v.getContext(),"com.httplogin.MainScreen"); 
        startActivity(i); 

       } 
       else 
       { 
       //Toast.makeText(HttpLogin.this,"MAX Returned",0).show(); 
       displayAlert(Re); 
//     Intent i = new Intent(); 
//      i.setClassName(v.getContext(),"com.san.MainScreen"); 
//      startActivity(i); 
       } 
      } 
     }); 
    } 

    protected String tryLogin(String mUsername, String mPassword) 
    {   
     Log.d(" TryLoginCheck ","Here"); 
     HttpURLConnection connection; 
     OutputStreamWriter request = null; 

      URL url = null; 
      String response = null; 
      String temp=null; 
      String parameters = "username="+mUsername+"&password="+mPassword; 
      System.out.println("UserName"+mUsername+"\n"+"password"+mPassword); 
      Log.d("Parameters",parameters); 
      try 
      { 

       url = new URL("http://serverspace/script.php"); 
       connection = (HttpURLConnection) url.openConnection(); 
       connection.setDoOutput(true); 
       connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
       connection.setRequestMethod("POST");  

       request = new OutputStreamWriter(connection.getOutputStream()); 
       request.write(parameters); 
       request.flush(); 
       request.close();    
       String line = "";    
       InputStreamReader isr = new InputStreamReader(connection.getInputStream()); 
       BufferedReader reader = new BufferedReader(isr); 
       StringBuilder sb = new StringBuilder(); 
       while ((line = reader.readLine()) != null) 
       { 

        sb.append(line + "\n"); 
       } 
       temp=sb.toString(); 
       Log.d("Temp",temp); 
       // Response from server after login process will be stored in response variable.     
       response = sb.toString(); 
       Log.d("Response",response); 
       Log.d("Sb Value",sb.toString()); 
       isr.close(); 
       reader.close(); 


      } 
      catch(IOException e) 
      { 
       Toast.makeText(this,e.toString(),0).show(); 
      } 
      // Log.d("Response",response); 
      return response; 
    } 
    public void displayAlert(String Re) 
    { 
    new AlertDialog.Builder(this).setMessage(Re) 
     .setTitle("Returned Value") 
     .setCancelable(true) 
     .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton){ 
      finish(); 
      } 
      }) 
     .show(); 
    } 
} 
2

대소 문자 구분 대소 문자를 구분하지 않는 문자열을 비교할 때는 .equalsIgnoreCase()를 사용하고 대소 문자를 구분하지 않을 때는 .equals()를 사용해야합니다. 또한 이것을 통해 디버그하여 tryLogin(mUsername, mPassword)이 예상 값을 반환했는지 확인하십시오.

+0

코드 스 니펫을 추가 할 수 있습니까 ?? –

+0

if (Re.equals ("GEEK")) {...} 자세히 알아보기 Here-> http://developer.android.com/reference/java/lang/String.html – ninjasense

1

코드에 대해주의해야 할 중요한 사항 중 하나는 UI 스레드에서 원격 서버 액세스 (tryLogin() 호출)와 같은 오랜 시간 작업을 절대로 실행해서는 안된다는 것입니다. 이러한 종류의 프로그래밍은 응용 프로그램에서 ANR로 연결됩니다.

private class LoginTask extends AsyncTask<string, void,="" String=""> { 
    protected String doInBackground(String... login) { 
     return tryLogin((login[0],login[1]); 
    } 

    protected void onPostExecute(String result) { 
     if(result.equalsIgnoreCase("GEEK")) 
     { 
      Intent i = new Intent(); 
      i.setClassName(v.getContext(),"com.httplogin.MainScreen"); 
      startActivity(i); 
     } 
    } 
} 
+0

어떻게해야합니까 ???? –

+0

위의 예제를 내 대답에 추가하십시오. – dstefanox

관련 문제