Android 应用程序无法正确处理 JSON

标签 android json

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;

}
}

该应用程序将显示加载配置文件对话框两秒钟,然后它会简单地关闭,如: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() {}
});

来自异步任务的 doInBackground()。

Asynctask本身就是一个线程,你在里面做网络操作。如果你在doinBackground上写runonUiThread()那么网络操作只会在主线程中执行,它会遇到你所面临的异常。因此会有编写异步任务毫无意义。

关于Android 应用程序无法正确处理 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32947321/

相关文章:

java - Android 应用程序的 android.os.NetworkOnMainThreadException

c# - 如何返回带有状态码的响应 JSON 数据?

android - Syncadapter 最后更新日期

android - 以编程方式关闭首选项 header

java - Android Studio 无法解析符号 ITelephony

ruby-on-rails - 如何将 ActiveModel::Serializer 与 PostgreSQL JSON 列一起使用

java - 在 Python 中检索 JSON 以响应 POST

ios - 快速函数调用中是否有必需的参数顺序

arrays - 如何在JSON Schema中定义一个二维矩形数组?

java - 如何删除 Firebase 数据库数组中的项目?