[英]Android PHP MySQL Search Results to ListView
作為序言,我想說我對Android應用程序開發領域還比較陌生。
我一直在研究一個涉及登錄/注冊系統的Android應用程序,該系統使用JSON從Android應用程序連接到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;
}
}
一種簡單的實現方法是使用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中,您可以使用Async Task從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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.