2014-03-31 88 views
0

作爲前言,我想說我對Android應用程序開發場景比較陌生。Android PHP MySQL搜索結果到ListView

我一直在研究一個Android應用程序,它涉及一個登錄/註冊系統,它使用JSON連接到使用JSON的PHP應用程序和MySQL腳本。登錄/註冊功能,但我試圖有一個活動,能夠搜索註冊用戶,並顯示在同一個xml佈局的ListView結果。我的PHP腳本用於搜索功能。

我幾乎看到網上無處不在,無濟於事的相關結果。如果有人能夠幫助我或指引我正確的方向,將不勝感激。

在此先感謝。

編輯: 這是我使用JSON解析器腳本 -

公共類JSONParser {

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 


public JSONObject getJSONFromUrl(final String url) { 

    // Making HTTP request 
    try { 
     // Construct the client and the HTTP request. 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     // Execute the POST request and store the response locally. 
     HttpResponse httpResponse = httpClient.execute(httpPost); 
     // Extract data from the response. 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     // Open an inputStream with the data content. 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     // Create a BufferedReader to parse through the inputStream. 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     // Declare a string builder to help with the parsing. 
     StringBuilder sb = new StringBuilder(); 
     // Declare a string to store the JSON object data in string form. 
     String line = null; 

     // Build the string until null. 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 

     // Close the input stream. 
     is.close(); 
     // Convert the string builder data to an actual string. 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // Try to parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // Return the JSON Object. 
    return jObj; 

} 


// function get json from url 
// by making HTTP POST or GET mehtod 
public JSONObject makeHttpRequest(String url, String method, 
     List<NameValuePair> params) { 

    // Making HTTP request 
    try { 

     // check for request method 
     if(method == "POST"){ 
      // request method is POST 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     }else if(method == "GET"){ 
      // request method is GET 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      String paramString = URLEncodedUtils.format(params, "utf-8"); 
      url += "?" + paramString; 
      HttpGet httpGet = new HttpGet(url); 

      HttpResponse httpResponse = httpClient.execute(httpGet); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 
     }   

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 

}

+0

也許[此帖](http://stackoverflow.com/questions/5530672/connecting-android-apps-to-mysql-database)可以提供幫助。 – Joel

+0

感謝您的快速回復。我會看看這篇文章。 – cmk0803

+0

我忘了提及搜索是通過AsyncTask完成的,搜索結果顯示在同一活動的ListView中。 – cmk0803

回答

0

實現是使用的AsyncTask一個簡單的方法,像如下:

package <your package>; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET mehtod 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if (method == "POST") { 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      } else if (method == "GET") { 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      } 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      /*BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8);*/ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "utf-8"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 

和在你的login.java你可以se異步任務從PHP和MySql獲取用戶數據,下面是我已經實現的

注意:您需要從中學習而不是複製代碼,因爲.xml是不同的,我不來到這裏的PHP代碼

package com.ecnu.vendingmachine.login; 

import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.CompoundButton; 
import android.widget.CompoundButton.OnCheckedChangeListener; 
import android.widget.EditText; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.widget.ToggleButton; 

import com.ecnu.vendingmachine.MainActivity; 
import com.ecnu.vendingmachine.MyApplication; 
import com.ecnu.vendingmachine.R; 
import com.ecnu.vendingmachine.widgets.JSONParser; 

public class LoginActivity extends Activity implements OnClickListener { 

    private String Tag = "LoginActivity"; 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    JSONParser jsonParser = new JSONParser(); 

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

    private TextView headTitle; 
    private EditText loginAccount; 
    private EditText loginPassword; 
    private Button autoButton; 

    private ToggleButton isShowPassword; 

    private boolean isAutoLogin = false; 

    private LinearLayout registerButton; 
    private LinearLayout enterButton; 

    private Intent intent; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.system_login); 

     findViewById(); 
     initView(); 
    } 

    protected void findViewById() { 

     loginAccount = (EditText) this 
       .findViewById(R.id.login_account_EditText); 
     loginPassword = (EditText) this 
       .findViewById(R.id.login_password_EditText); 

     isShowPassword = (ToggleButton) this.findViewById(R.id.isShowPassword); 
     headTitle = (TextView) findViewById(R.id.headbar_Center_Title); 

     registerButton = (LinearLayout) findViewById(R.id.login_Regist_Button); 
     enterButton = (LinearLayout) findViewById(R.id.login_Button); 
     autoButton = (Button) findViewById(R.id.login_Auto_Button); 
    } 

    protected void initView() { 

     headTitle.setText(R.string.login); 
     registerButton.setOnClickListener(this); 
     enterButton.setOnClickListener(this); 
     autoButton.setOnClickListener(this); 

     isShowPassword 
       .setOnCheckedChangeListener(new OnCheckedChangeListener() { 
        @Override 
        public void onCheckedChanged(CompoundButton buttonView, 
          boolean isChecked) { 

         String getPassword = loginPassword.getText().toString(); 

         if (getPassword.equals("") || getPassword.length() <= 0) { 
         } 

         if (isChecked) { 
          loginPassword.setInputType(0x81); 
          // loginpassword.setTransformationMethod(PasswordTransformationMethod.getInstance()); 
         } else { 
          loginPassword.setInputType(0x90); 
          // loginpassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); 
         } 
         Log.i("togglebutton", "" + isChecked); 
         // loginpassword.postInvalidate(); 
        } 
       }); 
    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     switch (v.getId()) { 
     case R.id.login_Regist_Button: 
      intent = new Intent(); 
      intent.setClass(LoginActivity.this, RegisterActivity.class); 
      startActivity(intent); 
      break; 

     case R.id.login_Button: 
      if (checkPassword() == true && checkAccount() == true) { 
       new login().execute(); 
       break; 
      } else { 
       break; 
      } 

     case R.id.login_Auto_Button: 
      if (isAutoLogin == false) { 
       autoButton.setBackgroundResource(R.drawable.checkbox_focus); 
       isAutoLogin = true; 
       break; 
      } else { 
       autoButton.setBackgroundResource(R.drawable.checkbox); 
       isAutoLogin = false; 
       break; 
      } 

     default: 
      break; 
     } 
    } 

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

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(LoginActivity.this); 
      pDialog.setMessage("loading.."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
      Log.i(Tag, "pDialog"); 
     } 

     protected String doInBackground(String... args) { 
      String loginAccountText = loginAccount.getText().toString(); 
      String loginPasswordText = loginPassword.getText().toString(); 

      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 

      params.add(new BasicNameValuePair("cellphone", loginAccountText)); 
      params.add(new BasicNameValuePair("password", loginPasswordText)); 

      // url to create new product 
      MyApplication myApplication = (MyApplication) getApplication(); 
      String url_login = myApplication.getIP() 
        + "vendingmachine/system_login.php"; 

      JSONObject json = jsonParser.makeHttpRequest(url_login, "POST", 
        params); 

      // check for success tag 
      try { 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // successfully created product 
        String userID = json.getString("userID"); 
        int userIntID = Integer.parseInt(userID); 
        myApplication.setUserID(userIntID); 
        finish(); 
       } else { 
        // failed to create product 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once done 
      pDialog.dismiss(); 
     } 

    } 

    private boolean checkPassword() { 
     String getPassword = loginPassword.getText().toString(); 
     Log.i(Tag, String.valueOf(getPassword.length())); 
     if (getPassword.length() > 5) 
      return true; 
     else 
      return false; 
    } 

    private boolean checkAccount() { 
     String getAccount = loginAccount.getText().toString(); 
     Log.i(Tag, String.valueOf(getAccount.length())); 
     if (getAccount.length() == 11) 
      return true; 
     else 
      return false; 
    } 
} 
+0

謝謝,我來看看。 – cmk0803