2013-12-13 5 views
2

내 응용 프로그램에서 누락 된 내용을 알고 싶습니다. 내 Android 응용 프로그램이 사용자 이름과 암호를 HTTP POST로 보내면 PHP 파일이 해당 사용자 이름의 데이터베이스 값에서 응답합니다. 문제는 사용자 이름을 입력하고 암호 아무것도 그것도HTTP 요청 없음 HTTP 응답

MainActivity

package com.example.postapp; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.InetAddress; 
import java.net.URL; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 



import android.os.AsyncTask; 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.CheckBox; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends Activity { 
     TextView tv; 
     EditText u,p; 
     Button login; 
     String result; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     login = (Button) findViewById(R.id.login); 

     login.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 

       u = (EditText) findViewById(R.id.username); 
       p = (EditText) findViewById(R.id.password); 


       Toast.makeText(getApplicationContext(), u.getText().toString(), Toast.LENGTH_LONG).show(); 
       Toast.makeText(getApplicationContext(), p.getText().toString(), Toast.LENGTH_LONG).show(); 
       new MyAsyncTask().execute(u.getText().toString(),p.getText().toString()); 

      } 

     }); 


    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 
    public class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{ 
     String host; 


     @Override 
     protected Boolean doInBackground(String... params) { 
      // TODO Auto-generated method stub 
      Boolean a= postData(params[0],params[1]);  
      return a; 
     } 

     protected void onPostExecute(Boolean localres){ 
      tv = (TextView) findViewById(R.id.tv); 
      if (localres){ 
        tv.setText("A Correct Username and Password"); 
       }else{ 
        tv.setText("Incorrect Username or Password"); 
       } 
      // Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT).show(); 
      // Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_SHORT).show(); 
       if(host!=null) 
       { 
       // Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show(); 
       } 
     } 

     protected void onProgressUpdate(Integer... progress){ 
      //pb.setProgress(progress[0]); 
      //Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show(); 

     } 


     public Boolean postData(String a,String b) { 
      // ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
      // postParameters.add(new BasicNameValuePair("username", a)); 
      // postParameters.add(new BasicNameValuePair("password", b)); 
       HttpURLConnection connection; 
       OutputStreamWriter request = null; 

        URL url = null; 
        String response = null;   
        String parameters = "username="+a+"&password="+b; 

        try 
        { 
         url = new URL("http://"+"192.168.1.3"+"/new/check2.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(); 
         // You can perform UI operations here 
         Toast.makeText(getApplicationContext(),"Message from Server: \n"+ response, 0).show();    
         isr.close(); 
         reader.close(); 

        } 
        catch(Exception e) 
        { 
         e.printStackTrace(); 
        } 
        return true; 
      } 


     } 



    } 

PHP

<?php 

$con = mysqli_connect("localhost", "root", "123", "pet_home"); 
if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

$username = $_POST['username']; 
$password = $_POST['password']; 
$result = mysql_query("select * from users where username='$username' and password='$password'")or die (mysql_error()); 
$count = mysql_num_rows($result); 
$row = mysql_fetch_array($result); 
if ($count > 0) { 
    echo $row['filter_st']; 
    echo "<br>"; 
    echo $row['heat_st']; 
    echo "<br>"; 
    echo $row['led_st']; 
} else { 
    echo 0; 
} 

mysqli_close($con); 
,691을 표시 아니에요 토스트에 다시 온다

로그 캣 당신은 public Boolean postData(String a,String b)에서

Boolean a= postData(params[0],params[1]); // in doInbackground 

이 당신이 잘못 토스트를 표시

12-13 20:57:45.534: W/System.err(14768): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 
12-13 20:57:45.534: W/System.err(14768): at android.os.Handler.<init>(Handler.java:197) 
12-13 20:57:45.534: W/System.err(14768): at android.os.Handler.<init>(Handler.java:111) 
12-13 20:57:45.538: W/System.err(14768): at android.widget.Toast$TN.<init>(Toast.java:324) 
12-13 20:57:45.538: W/System.err(14768): at android.widget.Toast.<init>(Toast.java:91) 
12-13 20:57:45.538: W/System.err(14768): at android.widget.Toast.makeText(Toast.java:238) 
12-13 20:57:45.538: W/System.err(14768): at com.example.postapp.MainActivity$MyAsyncTask.postData(MainActivity.java:136) 
12-13 20:57:45.538: W/System.err(14768): at com.example.postapp.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:76) 
12-13 20:57:45.538: W/System.err(14768): at com.example.postapp.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:1) 
12-13 20:57:45.538: W/System.err(14768): at android.os.AsyncTask$2.call(AsyncTask.java:287) 
12-13 20:57:45.538: W/System.err(14768): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
12-13 20:57:45.538: W/System.err(14768): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
12-13 20:57:45.538: W/System.err(14768): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
12-13 20:57:45.538: W/System.err(14768): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
12-13 20:57:45.538: W/System.err(14768): at java.lang.Thread.run(Thread.java:841) 

답변

1
Toast.makeText(getApplicationContext(),"Message from Server: \n"+ response, 0).show();   

예외가 나타납니다

당신은 아닌 백그라운드 스레드에서 UI를 업데이트하는 가능한. ui 스레드에서 ui를 업데이트하십시오.

반송 결과는 doInbackground입니다. doInbackground의 계산 결과는 param to onPostExecute입니다. 그래서 결과에 따라 ui ie display toast를 업데이트 할 수 있습니다. 당신이 doInBackground에서로드하지 않은 becz 위의 코드에서

또는 사용 runOnUiThread

runOnUiThread(new Runnable(){ 
    public void run() { 
     Toast.makeText(getApplicationContext(),"Message from Server: \n"+ response, 0).show(); 
    } 
}); 
1

는 토스트 메시지가 허용되지 않습니다. 당신이 다음 에서 onPostExecute() AsyncTask를 클래스의 방법을 토스트를 보여주는 후에 어떤 변수를 저장 토스트를 표시해야하는 경우 코멘트
가 // 당신은 여기
UI 작업을 수행 할 수 있습니다 추가 위의 포스트 데이터 방법에

즉 // Toast.makeText (getApplicationContext(), "서버로부터의 메시지 : \ n"+ response, 0) .show();
// 모든 변수

// 게시물 데이터 응답
문자열 메시지 = 응답에 대한 응답을 저장하는 단계;

보호 공극 onPostExecute (부울 localres) {
Toast.makeText (getApplicationContext() 메시지, Toast.LENGTH_LONG) .show();
}

2) 다른 방법은 doInBackground 방법에 runonUIThread에서 토스트 메시지가 입니다.