这是我的UserInfo.java(已编辑)
public class UserInfo extends ActionBarActivity implements OnClickListener {
// Progress Dialog
private ProgressDialog pDialog;
EditText name, email, password, mobilenumber, address,
city, postcode, state;
Button update;
//private JSONArray userinfo=null;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String USERINFO_URL = "http://192.168.1.10:1234/PMSS/userinfo.php";
private static final String UPDATEUSERINFO_URL = "http://192.168.1.10:1234/PMSS/updateuserinfo.php";
// ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POSTS = "posts";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PASSWORD = "password";
private static final String TAG_MOBILENUMBER = "mobilenumber";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CITY = "city";
private static final String TAG_POSTCODE = "postcode";
private static final String TAG_STATE = "state";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_info);
// Show the Up button in the action bar.
update = (Button) findViewById(R.id.update);
name = (EditText) findViewById(R.id.nametext);
email = (EditText) findViewById(R.id.useridtext);
password = (EditText) findViewById(R.id.passwordtext);
mobilenumber = (EditText) findViewById(R.id.mobilenumbertext);
address = (EditText) findViewById(R.id.addresstext);
city = (EditText) findViewById(R.id.citytext);
postcode = (EditText) findViewById(R.id.postcodetext);
state = (EditText) findViewById(R.id.statetext);
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String MobileNumber = mobilenumber.getText().toString();
String Address = address.getText().toString();
String City = city.getText().toString();
String PostCode = postcode.getText().toString();
String State = state.getText().toString();
new UpdateUser(Name, Email, Password, MobileNumber, Address,
City, PostCode, State).execute();
}
});
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new RetrieveUser().execute();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_info, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
String Name, Email, Password, MobileNumber, Address, City, PostCode, State;
public void updateJSONdata() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(UserInfo.this);
String post_username = sp.getString("username", "anon");
// String post_username = "jiaweitan05@gmail.com";
JSONParser jsonParser = new JSONParser();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", post_username));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(USERINFO_URL, "GET",
params);
// I know I said we would check if "Posts were Avail."
// (success==1)
// before we tried to read the individual posts, but I lied...
// mComments will tell us how many "posts" or comments are
// available
JSONArray userinfo = json
.getJSONArray(TAG_POSTS);
JSONObject c = userinfo.getJSONObject(0);
Name = c.getString(TAG_NAME);
Email = c.getString(TAG_EMAIL);
Password = c.getString(TAG_PASSWORD);
MobileNumber = c.getString(TAG_MOBILENUMBER);
Address = c.getString(TAG_ADDRESS);
City = c.getString(TAG_CITY);
PostCode = c.getString(TAG_POSTCODE);
State = c.getString(TAG_STATE);
name.setText(Name);
email.setText(Email);
password.setText(Password);
mobilenumber.setText(MobileNumber);
address.setText(Address);
city.setText(City);
postcode.setText(PostCode);
state.setText(State);
} catch (JSONException e) {
e.printStackTrace();
}
}
public class RetrieveUser extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UserInfo.this);
pDialog.setMessage("Loading User Info...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
class UpdateUser extends AsyncTask<String, String, Integer> {
boolean failure = false;
String res;
int success;
String Name, Email, Password, MobileNumber, Address, City, PostCode,
State, Position = "hahaha", CardBalance = "3456";
public UpdateUser(String Name, String Email, String Password,
String MobileNumber, String Address, String City,
String PostCode, String State) {
this.Name = Name;
this.Email = Email;
this.Password = Password;
this.MobileNumber = MobileNumber;
this.Address = Address;
this.City = City;
this.PostCode = PostCode;
this.State = State;
}
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UserInfo.this);
pDialog.setMessage("Updating User Info...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
// Check for success tag
try {
// Building Parameters
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
params2.add(new BasicNameValuePair("name", Name));
params2.add(new BasicNameValuePair("email", Email));
params2.add(new BasicNameValuePair("password", Password));
params2.add(new BasicNameValuePair("mobilenumber", MobileNumber));
params2.add(new BasicNameValuePair("address", Address));
params2.add(new BasicNameValuePair("postcode", PostCode));
params2.add(new BasicNameValuePair("city", City));
params2.add(new BasicNameValuePair("state", State));
params2.add(new BasicNameValuePair("state", Position));
params2.add(new BasicNameValuePair("state", CardBalance));
Log.d("request!", "starting");
// Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
UPDATEUSERINFO_URL, "POST", params2);
// full json response
Log.d("Update attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
res = json.getString(TAG_MESSAGE);
return success;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer success) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (success != null && success == 1) {
Log.d("User Updated!", res);
Intent r = new Intent(UserInfo.this, Login.class);
startActivity(r);
finish();
Toast.makeText(
UserInfo.this,
res == null ? "Please enter the require field that marked with **"
: res, Toast.LENGTH_LONG).show();
} else {
Log.d("Update Failure!", "res: " + res);
Toast.makeText(
UserInfo.this,
res == null ? "Please enter the require field that marked with **"
: res, Toast.LENGTH_LONG).show();
}
}
}
}
这是我的logcat(编辑)
12-13 21:47:32.199: D/request!(1387): starting
12-13 21:47:35.629: E/JSON Parser(1387): Error parsing data org.json.JSONException: Value <h1>User of type java.lang.String cannot be converted to JSONObject
12-13 21:47:35.669: W/System.err(1387): org.json.JSONException: No value for name
12-13 21:47:35.679: W/System.err(1387): at org.json.JSONObject.get(JSONObject.java:354)
12-13 21:47:35.709: W/System.err(1387): at org.json.JSONObject.getString(JSONObject.java:510)
12-13 21:47:35.709: W/System.err(1387): at com.pmss.UserInfo.updateJSONdata(UserInfo.java:165)
12-13 21:47:35.709: W/System.err(1387): at com.pmss.UserInfo$RetrieveUser.doInBackground(UserInfo.java:203)
12-13 21:47:35.709: W/System.err(1387): at com.pmss.UserInfo$RetrieveUser.doInBackground(UserInfo.java:1)
12-13 21:47:35.709: W/System.err(1387): at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-13 21:47:35.709: W/System.err(1387): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-13 21:47:35.709: W/System.err(1387): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-13 21:47:35.709: W/System.err(1387): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-13 21:47:35.709: W/System.err(1387): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-13 21:47:35.709: W/System.err(1387): at java.lang.Thread.run(Thread.java:1019)
12-13 21:48:09.449: W/IInputConnectionWrapper(1387): showStatusIcon on inactive InputConnection
我想做的是,当我点击UserInfo界面时,它会加载用户详细信息,并放置在UserInfo界面中提供的每个EditText
中。但不知何故,我的UserInfo界面中的每个EditText
都不显示任何内容。我的编码没有编译错误和运行时错误
这是我在Login.java 中启动SharedPreferences
的地方
if (success == 1) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("email", Username);
edit.commit();
}
有人能帮我吗?我检查了两天,但仍然不知道为什么EditText
什么都不显示。
从日志中可以看出,E/JSON Parser(971):解析数据org.JSON.JSONException时出错:java.lang.String类型的Value User无法转换为JSONObject??我应该如何解决它?
这是我的JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
// 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;
}
public JSONObject makeHttpRequest(String registerUrl, String method,
String[] params) {
// TODO Auto-generated method stub
return null;
}
}
这是我的userinfo.php
<?php
require("config.inc.php");
if (!empty($_POST)) {
//initial query
$query = "Select name, email, password, mobilenumber, address, city, postcode, state FROM user WHERE email = :email ";
$query_params = array(':email' => $_POST['email']);
//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
$row = $stmt->fetchAll();
if ($row) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
$post = array();
do {
// $post = $row["position"];
// $post = $row["state"];
// array_push($response["posts"], $post);
array_push($response["posts"], $row);
} while ($row = $stmt->fetch());
die(json_encode($response));
}
else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
}
else {
?>
<h1>User Info</h1>
<form action="userinfo.php" method="post">
Email:<br />
<input type="email" name="email" value="" />
<br /><br />
<input type="submit" value="Search User" />
</form>
<?php
}
你说你是json
{ // json object
"success": 1,
"message": "Post Available!",
"posts": [ // json array posts
[ // json array node
{ // json object node
"name": "Jiawei", // string
"email": "jiaweitan05@gmail.com",
"password": "123456abcd",
"mobilenumber": "0124331292",
"address": "Bunga Raya",
"city": "Bukit Beruang",
"postcode": "75450",
"state": "Melaka"
}
]
]
}
[
表示JSONArray节点
{
表示JSONObject节点
假设你有上面的json
JSONObject json = jsonParser.makeHttpRequest(USERINFO_URL, "GET",
params);
现在解析
String success =json.getString("success");
String message= json.getString("message");
JSONArray jar = json.getJSONArray("posts");
JSONArray jr = jar.getJSONArray(0);
JSONObject jb = jr.getJSONObject(0);
String name = jb.getString("name");
//similarly for email, password and so on.
现在另一个json
[ // json array node
{ // json object node
"address": "Bunga Raya", // string
"mobilenumber": "0124331292",
"email": "jiaweitan05@gmail.com",
"name": "Jiawei",
"state": "Melaka",
"postcode": "75450",
"password": "123456abcd",
"city": "Bukit Beruang"
}
]
日志显示
org.json.JSONArray cannot be converted to JSONObject
这意味着您正在尝试将json数组转换为json对象。
错误:
您的响应是JSONArray,并且您正在尝试创建一个具有接收到的响应的JSONObject。
JSONObject json = jsonParser.makeHttpRequest(USERINFO_URL, "POST", params);
另一个令人大开眼界的句子异常是给出:"org.json.JSONArray无法转换为JSONObject"。
解决方案:
JSONArray arrayJSON = jsonParser.makeHttpRequest(USERINFO_URL, "POST", params);
这是实际的json格式
{"countrylist":[{"id":"241","country":" India"}]}
使用json对象,如countylist