通过JSON显示数据的TextView [英] Displaying data in textview through json
问题描述
我想通过PHP来显示从MySQL数据库用户的详细信息和Android中的TextView显示。该方案是这样的:当用户登录到他的帐户,他将被重定向到包含4个按钮分别是仪表板:新闻源,配置文件,日历和有关。当用户点击该配置文件按钮,用户细节,如他的姓氏,名字,middleinitial等将显示在TextView的。当我运行我的应用程序,它不显示任何东西,但在我的PHP脚本返回用户的详细信息。什么似乎是这里的问题?
下面是我的Java code:
包sscr.stag;进口的java.util.ArrayList;
进口的java.util.List;
进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Shared preferences;
进口android.os.AsyncTask;
进口android.os.Bundle;
。进口的Android preference preferenceManager。
进口android.util.Log;
进口android.widget.TextView;公共类AdProfile延伸活动{
//所有的XML标签TextView的txtFname;
TextView的txtMname;
TextView的txtLname;//进度对话框
私人ProgressDialog pDialog;//创建JSON解析器对象
JSONParser jsonParser =新JSONParser();//简介JSON对象
JSONArray用户;
干草的JSONObject;
//简介JSON网址
私有静态最后弦乐PROFILE_URL =http://www.stagconnect.com/StagConnect/admin/TestProfile.php;//所有JSON节点名称
私有静态最后弦乐TAG_PROFILE =用户;
//私有静态最后弦乐TAG_ID =ID;
私有静态最后弦乐TAG_USERNAME =用户名;
私有静态最后弦乐TAG_FIRSTNAME =FIRST_NAME;
私有静态最后弦乐TAG_MIDDLENAME =MIDDLE_INITIAL;
私有静态最后弦乐TAG_LASTNAME =姓氏;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.adminprofile);
txtFname =(的TextView)findViewById(R.id.fname);
txtMname =(的TextView)findViewById(R.id.mname);
txtLname =(的TextView)findViewById(R.id.lname);//在后台线程加载配置文件
新LoadProfile()执行();
}类LoadProfile扩展的AsyncTask<字符串,字符串,字符串> {
公共无效测试(){ 干草=新的JSONObject(); //存储在变量中的每个JSON项目
尝试{
字符串名字= hay.getString(TAG_FIRSTNAME);
字符串中间名= hay.getString(TAG_MIDDLENAME);
字符串姓氏= hay.getString(TAG_LASTNAME); //显示在TextView中的所有数据 txtFname.setText(名字:+姓名);
txtMname.setText(中间名+中间名);
txtLname.setText(姓+姓氏); }赶上(JSONException E){
// TODO自动生成catch块
e.printStackTrace();
} }@覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(AdProfile.this);
pDialog.setMessage(载入配置文件...);
pDialog.setIndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
/ **
*越来越简介JSON
* * /
保护字符串doInBackground(字符串参数... args){
//大厦参数共享preferences SP = preferenceManager.getDefaultShared preferences(AdProfile.this);
字符串post_username = sp.getString(用户名,匿名);
清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
params.add(新BasicNameValuePair(用户名,post_username));
// URL从获取JSON字符串
JSONObject的JSON = jsonParser.makeHtt prequest(PROFILE_URL,POST,
PARAMS);//检查JSON效应初探日志的猫
Log.d(档案JSON:json.toString());尝试{
//简介JSON对象
用户= json.getJSONArray(TAG_PROFILE);
}赶上(JSONException E){
e.printStackTrace();
}返回null;
}
保护无效onPostExecute(字符串FILE_URL){
//让所有的产品后,关闭该对话框
pDialog.dismiss();
//从后台线程更新界面
测试();}}
}
这是我的PHP脚本:
< PHP
需要('admin.config.inc.php');
如果(!空($ _ POST)){ //初始查询
$查询=选择姓氏,FIRST_NAME,MIDDLE_INITIAL,从指定管理其中username =:用户; $ query_params =阵列(':用户=> $ _ POST ['用户名']); //执行查询
尝试{
$语句= $ DB - > prepare($查询);
$结果= $语句 - >执行($ query_params);
}赶上(PDOException $前){
$响应[成功] = 0;
$响应[消息] =数据库错误!;
死亡(json_en code($响应));
} //最后,我们可以检索所有找到的行成使用使用fetchall数组
$行= $语句 - >使用fetchall(); 如果($行){
$响应[成功] = 1;
$响应[消息] =后可用!
$响应[用户] =阵列(); 的foreach($行作为$行){
$ USER =阵列();
$用户[名称] = $行[名称];
$用户[中间名] = $行[MIDDLE_INITIAL];
$用户[名字] = $行[如first_name];
$用户[姓氏] = $行[姓氏]; //更新我们的repsonse JSON数据
array_push($响应[用户],$用户);
} //呼应JSON响应
回声json_en code($响应); }其他{
$响应[成功] = 0;
$响应[消息] =没有可用的用户!
死亡(json_en code($响应));
}}其他{}
?> <形式的行动=TestProfile.php方法=POST>
用户名:其中;输入类型=文本名称=用户名>
<输入类型=提交值=提交>
< /表及GT;
下面我的PHP脚本(JSON响应)的输出:
{成功:1,消息:后可用!,用户:[{称号:学生事务办公室负责,中间名 :,名字:测试,姓氏:测试}]}
这是JSON对象
JSONObject的JSON = jsonParser.makeHtt prequest(PROFILE_URL,POST,
PARAMS);
您需要返回 JSON
在 doInbackground
。返回的结果参数去 onPostExecute
然后
试验(JSON);
和再测试,你可以解析JSON
编辑:
您还需要修改
的AsyncTask<字符串,字符串,字符串>
到
的AsyncTask<字符串,字符串,JSONObject的>
然后
受保护的JSONObject doInBackground(字符串参数... args){JSONObject的JSON = NULL;
//大厦参数共享preferences SP = preferenceManager.getDefaultShared preferences(AdProfile.this);
字符串post_username = sp.getString(用户名,匿名);
清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
params.add(新BasicNameValuePair(用户名,post_username));
// URL从获取JSON字符串
JSON = jsonParser.makeHtt prequest(PROFILE_URL,POST,
PARAMS);//检查JSON效应初探日志的猫
Log.d(档案JSON:json.toString());尝试{
//简介JSON对象
用户= json.getJSONArray(TAG_PROFILE);
}赶上(JSONException E){
e.printStackTrace();
}返回JSON;
}
然后在onPostExecute
@覆盖
保护无效onPostExecute(JSONObject的结果){
super.onPOstExecute(结果);
//让所有的产品后,关闭该对话框
pDialog.dismiss();
//从后台线程更新界面
测试结果);
}
在测试
公共无效测试(JSONObject的响应){
{
//此处解析响应,并设置文本的TextView
}
或者
你的 doInbackgrond
解析在onPostExecute更新的TextView
编辑:
code:
公共类AddProfile延伸活动{
//所有的XML标签 TextView的txtFname;
TextView的txtMname;
TextView的txtLname; //进度对话框
私人ProgressDialog pDialog; //简介JSON对象
JSONArray用户;
干草的JSONObject;
//简介JSON网址
私有静态最后弦乐PROFILE_URL =http://www.stagconnect.com/StagConnect/admin/TestProfile.php; //所有JSON节点名称
私有静态最后弦乐TAG_PROFILE =用户;
//私有静态最后弦乐TAG_ID =ID;
私有静态最后弦乐TAG_USERNAME =用户名;
私有静态最后弦乐TAG_FIRSTNAME =FIRST_NAME;
私有静态最后弦乐TAG_MIDDLENAME =MIDDLE_INITIAL;
私有静态最后弦乐TAG_LASTNAME =姓氏; @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.adminprofile); txtFname =(的TextView)findViewById(R.id.fname);
txtMname =(的TextView)findViewById(R.id.lname);
txtLname =(的TextView)findViewById(R.id.mname); //在后台线程加载配置文件
新LoadProfile()执行();
} 类LoadProfile扩展的AsyncTask<字符串,字符串,字符串> { @覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(AddProfile.this);
pDialog.setMessage(载入配置文件...);
pDialog.setIndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
} / **
*越来越简介JSON
* * /
保护字符串doInBackground(字符串参数... args){
//大厦参数
JSON字符串= NULL;
尝试{
清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
params.add(新BasicNameValuePair(用户名,管理员)); HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新HttpPost(PROFILE_URL);
httppost.setEntity(新UrlEn codedFormEntity(PARAMS)); //执行HTTP POST请求
HTT presponse响应= httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
JSON = EntityUtils.toString(resEntity); Log.i(档案JSON:json.toString());
}赶上(例外五){
e.printStackTrace();
} 返回JSON;
} @覆盖
保护无效onPostExecute(JSON字符串){
super.onPostExecute(JSON);
//让所有的产品后,关闭该对话框
pDialog.dismiss();
尝试
{
干草=新的JSONObject(JSON);
JSONArray用户= hay.getJSONArray(用户);
的JSONObject JB = user.getJSONObject(0);
字符串名字= jb.getString(名字);
字符串中间名= jb.getString(中间名);
字符串姓氏= jb.getString(姓氏); //显示在TextView中的所有数据 txtFname.setText(名字:+姓名);
txtMname.setText(中间名+中间名);
txtLname.setText(姓+姓氏);
}赶上(例外五)
{
e.printStackTrace();
} } }
}
将JSON
{// JSON对象节点
成功:1,
消息:后可用!
用户:[// JSON数组用户
{// JSON对象节点
称号:学生事务办公室负责
中间名字: ,
名字:何塞·帕特里克
姓氏:奥坎波
}
]
}
浏览器快照
I want to display user details from mysql database through php and display it in android textview. The scenario is like this: When the user logged in to his account he will be redirected to the dashboard which contains of 4 buttons namely: newsfeed, profile, calendar and about. When the user clicks the profile button the user details like his lastname, firstname, middleinitial etc will be displayed in the textview. When i run my app, it doesnt display anything but in my php script it returns the user details. What seems to be the problem here?
Here is my java code:
package sscr.stag;
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.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.TextView;
public class AdProfile extends Activity {
// All xml labels
TextView txtFname;
TextView txtMname;
TextView txtLname;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONArray user;
JSONObject hay;
// Profile JSON url
private static final String PROFILE_URL ="http://www.stagconnect.com/StagConnect/admin/TestProfile.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_FIRSTNAME = "first_name";
private static final String TAG_MIDDLENAME = "middle_initial";
private static final String TAG_LASTNAME = "last_name";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adminprofile);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.mname);
txtLname = (TextView) findViewById(R.id.lname);
// Loading Profile in Background Thread
new LoadProfile().execute();
}
class LoadProfile extends AsyncTask<String, String, String> {
public void test(){
hay = new JSONObject();
// Storing each json item in variable
try {
String firstname = hay.getString(TAG_FIRSTNAME);
String middlename = hay.getString(TAG_MIDDLENAME);
String lastname = hay.getString(TAG_LASTNAME);
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AdProfile.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.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
JSONObject 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 null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
test();
}
}
}
And here is my php script:
<?php
require('admin.config.inc.php');
if (!empty($_POST)) {
//initial query
$query = "Select last_name, first_name, middle_initial, designation FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
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"] = "Post Available!";
$response["user"] = array();
foreach($rows as $row) {
$user = array();
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["user"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
<form action="TestProfile.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
Here the output of my php script(JSON Response):
{"success":1,"message":"Post Available!","user":[{"designation":"Student Affairs Office in charge","middlename":"","firstname":"test","lastname":"test"}]}
This is the json object
JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",
params);
You need to return json
in doInbackground
. The result returned is param to onPostExecute
Then
test(json);
And then in test you can parse the json
Edit:
You would also need to change
AsyncTask<String, String, String>
to
AsyncTask<String, String, JSONObject>
Then
protected JSONObject doInBackground(String... args) {
JSONObject json=null;
// Building Parameters
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.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;
}
Then in onPostExecute
@Override
protected void onPostExecute(JSONObject result) {
super.onPOstExecute(result);
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
test(result);
}
In test
public void test(JSONObject response){
{
// parse response here and set text to textview
}
Or
Do you parsing in doInbackgrond
update textview in onPostExecute
Edit:
Code:
public class AddProfile extends Activity {
// All xml labels
TextView txtFname;
TextView txtMname;
TextView txtLname;
// Progress Dialog
private ProgressDialog pDialog;
// Profile json object
JSONArray user;
JSONObject hay;
// Profile JSON url
private static final String PROFILE_URL = "http://www.stagconnect.com/StagConnect/admin/TestProfile.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_FIRSTNAME = "first_name";
private static final String TAG_MIDDLENAME = "middle_initial";
private static final String TAG_LASTNAME = "last_name";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adminprofile);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
// Loading Profile in Background Thread
new LoadProfile().execute();
}
class LoadProfile extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddProfile.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* 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", "admin"));
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;
}
@Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
The json
{ // json object node
"success": 1,
"message": "Post Available!",
"user": [ // json array user
{ // json object node
"designation": "Student Affairs Office in-charge",
"middlename": "",
"firstname": "Jose Patrick",
"lastname": "Ocampo"
}
]
}
Browser snap shot
这篇关于通过JSON显示数据的TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!