我正在尝试使用 php、json 和 mysql 开发 Android 应用程序。我想使用某个用户的登录用户名获取用户详细信息。该场景是用户登录并定向到他的仪表板,其中包含四个按钮:一个用于他的个人资料的按钮,如果单击,他将查看他的个人信息。我有类似的问题 this ...但是我遇到了几个错误,这些错误很糟糕,我自己无法解决。我是安卓新手。请任何有爱心的人可以帮助我......???!!
这是我的java代码:
package com.myapp;
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 library.JSONParser;
import library.UserLogout;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ProfileView extends Activity implements OnClickListener{
private Button bBack, bLogout;
private TextView tvusername, tvfullname;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONArray user;
JSONObject display;
// Profile JSON url
private static final String PROFILE_URL = "http://10.0.2.2/webservice/profile.php";
// ALL JSON node names
private static final String TAG_PROFILE = "user";
// private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_FULLNAME = "fullname";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
//setup textview
tvusername=(TextView)(findViewById(R.id.tvusernamedisplay));
tvfullname=(TextView)(findViewById(R.id.tvfullname));
//settup buttons
bBack=(Button)(findViewById(R.id.bBack));
bLogout=(Button)(findViewById(R.id.blogout));
//button listener
bBack.setOnClickListener(this);
bLogout.setOnClickListener(this);
// Loading Profile in Background Thread
new LoadProfile().execute();
}
@Override
public void onClick(View args) {
// TODO Auto-generated method stub
switch (args.getId()) {
case R.id.bBack:
Intent b = new Intent(this, Dashboard.class);
startActivity(b);
break;
case R.id.blogout:
Intent out = new Intent(this, UserLogout.class);
startActivity(out);
default:
break;
}
}
class LoadProfile extends AsyncTask<String, String, JSONObject> {
public void test(JSONObject response){
display = new JSONObject();
// Storing each json item in variable
try {
String idnum = display.getString(TAG_USERNAME);
String full = display.getString(TAG_FULLNAME);
// displaying all data in textview
tvusername.setText(idnum);
tvfullname.setText(full);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileView.this);
pDialog.setMessage("Loading Profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected JSONObject doInBackground(String... args) {
// Building Parameters
JSONObject json=null;
// Building Parameters
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ProfileView.this);
String post_username = sp.getString("username", "anon");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
// getting JSON string from URL
json = jsonParser.makeHttpRequest(PROFILE_URL, "POST", params);
// Check your log cat for JSON reponse
Log.d("Profile JSON: ", json.toString());
try {
// profile json object
user = json.getJSONArray(TAG_PROFILE);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
test(result);
}
}
}
这是我的 PHP 脚本:
<?php
/*
Our "config.php" file connects to database every time we include or require
it within a php script. Since we want this script to query data from a user logged in to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("config.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
username,
CONCAT(lastname, ',' , firstname, ' ' , middlename) as lastname
FROM user
WHERE
username = :username
";
//COUNT(ftload) as ftload,
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "User Profile!";
$response["user"] = array();
foreach ($rows as $row) {
$user = array();
//this line is new:
//$post["post_id"] = $row["post_id"];
$user ["username"] = $row["username"];
$user ["lastname"] = $row["lastname"];
//update our repsonse JSON data
array_push($response["user"], $user );
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
}
?>
<form action="testprofile.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
这是我上面的测试配置文件的 json 响应:
{"success":1,"message":"User Profile!","user": [{"username":"10094","lastname":"MARTINEZ,Pot Pama"}]}
这是我的 logcat 错误:
08-09 18:35:46.373: I/ActivityManager(291): Displayed
com.myapp/.ProfileView: +3s247ms
08-09 18:35:49.173: D/Profile JSON:(841): {"message":"User
Profile!","user":[{"lastname":"MARTINEZ,Pot
Pama","username":"10094"}],"success":1}
08-09 18:35:49.213: W/System.err(841): org.json.JSONException: No value for
username
08-09 18:35:49.233: W/System.err(841): at org.json.JSONObject.get
(JSONObject.java:354)
08-09 18:35:49.233: W/System.err(841): at org.json.JSONObject.getString
(JSONObject.java:510)
08-09 18:35:49.243: W/System.err(841): at com.sjpmingfinal.ProfileView
$LoadProfile.test(ProfileView.java:102)
08-09 18:35:49.243: W/System.err(841): at com.sjpmingfinal.ProfileView
$LoadProfile.onPostExecute(ProfileView.java:164)
08-09 18:35:49.243: W/System.err(841): at com.sjpmingfinal.ProfileView
$LoadProfile.onPostExecute(ProfileView.java:1)
08-09 18:35:49.243: W/System.err(841): at android.os.AsyncTask.finish
(AsyncTask.java:631)
08-09 18:35:49.243: W/System.err(841): at android.os.AsyncTask.access$600
(AsyncTask.java:177)
08-09 18:35:49.253: W/System.err(841): at android.os.AsyncTask
$InternalHandler.handleMessage(AsyncTask.java:644)
08-09 18:35:49.253: W/System.err(841): at
android.os.Handler.dispatchMessage(Handler.java:99)
08-09 18:35:49.253: W/System.err(841): at android.os.Looper.loop
(Looper.java:137)
08-09 18:35:49.263: W/System.err(841): at android.app.ActivityThread.main
(ActivityThread.java:5041)
08-09 18:35:49.263: W/System.err(841): at
java.lang.reflect.Method.invokeNative(Native Method)
08-09 18:35:49.263: W/System.err(841): at java.lang.reflect.Method.invoke
(Method.java:511)
08-09 18:35:49.263: W/System.err(841): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:793)
08-09 18:35:49.283: W/System.err(841): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-09 18:35:49.293: W/System.err(841): at dalvik.system.NativeStart.main
(Native Method)
: E/(): Device disconnected: 1
: E/(): Device disconnected
编辑:我自己解决了。 请参阅下面我的回答......
最佳答案
是的!我自己解决。干杯! 我对发布的代码进行了更改。请耐心等待,我可能不是一个好的程序员,但是对于像我这样的缓慢的初学者,不要放弃自己,总是使用试错方法呵呵,并注意这里给出提示和的人建议...
我在我的登录 java上编写了几行代码: 使用共享首选项在我的 doinbackground 中执行此操作
// save user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.commit();
Intent i = new Intent(LoginActivity.this, ProfileView.class);
// this is where you should pass the username
i.putExtra("username", username);
//finish();
startActivity(i);
finish();
.......
在我的个人资料 java上: 使用并在 onCreate 中添加此代码,以从您的共享首选项所在的登录 java 中获取额外内容
Bundle extras = getIntent().getExtras();
if (extras.containsKey("username")) {
ngalan = extras.getString("username");
// Loading Profile in Background Thread
new LoadProfile().execute();
}
最后在 asynctask 类中使用它来获取 json 配置文件:
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json=null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", ngalan));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
我知道有更短、最快或最智能的方法来获取数据并在 TextView 上显示,但很高兴知道我的代码做得很好。希望对您也有帮助。
关于php - 如何使用我登录的用户名将 MySQL 中的数据显示到 Android TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25221854/