[英]Android app not processing JSON correctly
package com.example.editartist;
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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText txtArtistType;
EditText txtPhoneNo;
EditText txtDescription;
Button btnSave;
Button btnDelete;
String uid="1";
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String url_profile_details = "http://10.0.2.2/android_main/get_profile_details.php";
private static final String url_update_profile = "http://10.0.2.2/android_main/update_profile.php";
private static final String url_delete_profile = "http://10.0.2.2/android_main/delete_profile.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PROFILE = "profile";
private static final String TAG_UID = "uid";
private static final String TAG_ARTIST_TYPE = "artist_type";
private static final String TAG_PHONE_NO = "phone_no";
private static final String TAG_DESCRIPTION = "description";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
new GetProfileDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// starting background task to update profile
new SaveProfileDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// deleting profile in background thread
new DeleteProfile().execute();
}
});
}
class GetProfileDetails extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading profile details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", uid));
JSONObject json = jsonParser.makeHttpRequest(
url_profile_details, "GET", params);
// check your log for json response
Log.d("Single Profile Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received profile details
JSONArray profileObj = json
.getJSONArray(TAG_PROFILE); // JSON Array
// get first profile object from JSON Array
JSONObject profile = profileObj.getJSONObject(0);
// profile with this uid found
// Edit Text
txtArtistType = (EditText) findViewById(R.id.inputArtistType);
txtPhoneNo = (EditText) findViewById(R.id.inputPhoneNo);
txtDescription = (EditText) findViewById(R.id.inputDescription);
// display profile data in EditText
txtArtistType.setText(profile.getString(TAG_ARTIST_TYPE));
txtPhoneNo.setText(profile.getString(TAG_PHONE_NO));
txtDescription.setText(profile.getString(TAG_DESCRIPTION));
}else{
// profile with uid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save profile Details
* */
class SaveProfileDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Saving profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving profile
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String artistType = txtArtistType.getText().toString();
String phoneNo = txtPhoneNo.getText().toString();
String description = txtDescription.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_UID, uid));
params.add(new BasicNameValuePair(TAG_ARTIST_TYPE, artistType));
params.add(new BasicNameValuePair(TAG_PHONE_NO, phoneNo));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
// sending modified data through http request
// Notice that update profile url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_profile,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("UPDATE","Successfully updated");
} else {
// failed to update profile
}
} 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 profile updated
pDialog.dismiss();
}
}
class DeleteProfile extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Deleting Profile...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", uid));
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "POST", params);
Log.d("Delete Profile", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("DELETE","Successfully deleted");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
package com.example.editartist;
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);
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;
}
}
該應用程序將顯示“加載配置文件”對話框2秒鍾,然后關閉,就像:EditArtist停止工作。 日志中的錯誤列表很長,開頭為
10-05 10:53:33.000: E/AndroidRuntime(1057): FATAL EXCEPTION: main
10-05 10:53:33.000:E/AndroidRuntime(1057): android.os.NetworkOnMainThreadException
為了方便起見,我采用了uid =“ 1”,因此只能編輯uid = 1的用戶。
去掉
runOnUiThread(new Runnable() {
public void run() {}
});
從asynctask的doInBackground()中獲取。
Asynctask本身就是您在其中進行網絡操作的線程。如果您在doinBackground上編寫runonUiThread(),則網絡操作將僅在主線程中執行,並且將遇到您所面臨的異常,因此將毫無意義編寫asynctask的過程。
您無法在Main UI線程中運行網絡請求...要正確處理JSON,請使用new Thread
或使用AsynTask
在其他線程上運行它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.