2013-12-13 175 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); 

logcat的出現有一個例外

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();   

你有

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

public Boolean postData(String a,String b)您顯示敬酒這是不對的

你在後臺線程這是不更新用戶界面可能。在ui線程上更新ui。

返回結果於doInbackground。計算doInbackground的結果參數爲onPostExecute。因此,根據結果,您可以更新UI,即相應地顯示烤麪包。

,或者使用runOnUiThread

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

在上面的代碼中不允許吐司消息becz你沒有在doInBackground加載。如果你必須表明敬酒,然後顯示onPostExecute()中的AsyncTask類方法敬酒之後存儲的任何變量

即在上述職位數據的方法添加註釋
//你可以在這裏進行
UI操作// Toast.makeText(getApplicationContext(),「來自服務器的消息:\ n」+ response,0).show();
//存儲響應於任何可變

//在後數據響應
字符串消息=響應;

保護無效onPostExecute(布爾localres){
Toast.makeText(getApplicationContext(),消息,Toast.LENGTH_LONG).show();
}

2)另一種方法是 你在必須吐司消息runonUIThread在doInBackground方法。