我想通过PHP从mysql数据库中显示用户详细信息,并在android textvIEw中显示它.场景是这样的:当用户登录到他的帐户时,他将被重定向到仪表板,该仪表板包含4个按钮,即:新闻源,个人资料,日历和关于.当用户单击配置文件按钮时,用户详细信息(例如他的姓,名,中间名等)将显示在文本视图中.当我运行我的应用程序时,它什么都不显示,但是在我的PHP脚本中它返回用户详细信息.这里似乎是什么问题?
这是我的Java代码:
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 labelsTextVIEw txtFname;TextVIEw txtMname;TextVIEw txtLname;// Progress Dialogprivate ProgressDialog pDialog;// Creating JsON Parser objectJsONParser JsonParser = new JsONParser();// Profile Json objectJsONArray user;JsONObject hay;// Profile JsON urlprivate static final String PROfile_URL ="http://www.stagconnect.com/StagConnect/admin/TestProfile.PHP";// ALL JsON node namesprivate 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";@OverrIDepublic 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 Threadnew 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(); } }@OverrIDeprotected 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 ParametersSharedPreferences 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 URLJsONObject Json = JsonParser.makehttpRequest(PROfile_URL, "POST", params);// Check your log cat for JsON reponseLog.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 productspDialog.dismiss();// updating UI from Background Threadtest();}}}
这是我的PHP脚本:
<?PHPrequire('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>
这是我的PHP脚本(JsON响应)的输出:
{"success":1,"message":"Post Available!","user":[{"designation":"Student Affairs Office in charge","mIDdlename":"","firstname":"test","lastname":"test"}]}
解决方法:
这是Json对象
JsONObject Json = JsonParser.makehttpRequest(PROfile_URL, "POST", params);
您需要在doInbackground中返回Json.返回的结果是onPostExecute的参数
然后
test(Json);
然后在测试中,您可以解析Json
编辑:
您还需要更改
AsyncTask<String, String, String>
至
AsyncTask<String, String, JsONObject>
然后
protected JsONObject doInBackground(String... args) {JsONObject Json=null; // Building ParametersSharedPreferences 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 URLJson = JsonParser.makehttpRequest(PROfile_URL, "POST", params);// Check your log cat for JsON reponseLog.d("Profile JsON: ", Json.toString());try { // profile Json object user = Json.getJsONArray(TAG_PROfile);} catch (JsONException e) { e.printstacktrace();}return Json;}
然后在onPostExecute
@OverrIDeprotected voID onPostExecute(JsONObject result) {super.onPOstExecute(result);// dismiss the dialog after getting all productspDialog.dismiss();// updating UI from Background Threadtest(result);}
在测试中
public voID test(JsONObject response){{ // parse response here and set text to textvIEw}
要么
您是否在doInbackgrond中解析onPostExecute中的textvIEw
编辑:
码:
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(); } } }}
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" } ]}
浏览器快照
总结以上是内存溢出为你收集整理的android-通过json在textview中显示数据全部内容,希望文章能够帮你解决android-通过json在textview中显示数据所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)