Android 异步任务+;JSON(如何获取一些值)

Android 异步任务+;JSON(如何获取一些值),android,json,android-asynctask,Android,Json,Android Asynctask,我使用JSONparser在一个远程mySQL数据库中获取一些值,在我在Android 3.0+(蜂巢)中测试之前,它工作得很好,因为有Guardian,它不允许进程在其主线程上执行网络操作 所以我发现我需要一个异步任务: 并尝试了以下主题: 现在我知道asynctask不能返回值,但我需要得到这个json值,因为我在不同的活动中有许多调用,等待它处理和/或在屏幕上显示信息(我想这就是为什么我不能在OnPostExecute中执行) 下面是一些类,它们是对我以前的JsonParser


我使用JSONparser在一个远程mySQL数据库中获取一些值,在我在Android 3.0+(蜂巢)中测试之前,它工作得很好,因为有Guardian,它不允许进程在其主线程上执行网络操作

所以我发现我需要一个异步任务


并尝试了以下主题:


现在我知道asynctask不能返回值,但我需要得到这个json值,因为我在不同的活动中有许多调用,等待它处理和/或在屏幕上显示信息(我想这就是为什么我不能在OnPostExecute中执行)


下面是一些类,它们是对我以前的JsonParser的一些修改

JSONParser.java

public class JSONParser extends AsyncTask<List<NameValuePair>, Void, JSONObject> {

    static InputStream is = null;
    static JSONObject jObj = null;
    static JSONObject result = null;
    static String json = "";

    private static String jsonURL = "http://192.168.1.119/Server/db/json/";

    private ProgressDialog progressDialog;

    // constructor
    public JSONParser() {

    }

    @Override
    protected void onPreExecute() {
        //progressDialog = new ProgressDialog();
        progressDialog.setMessage("Aguarde...");
        progressDialog.show();
    }

    protected JSONObject doInBackground(List<NameValuePair>... params) {

        // Making HTTP request
        try {

            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(jsonURL);
            httpPost.setEntity(new UrlEncodedFormEntity(params[0]));

            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();
        } catch (Exception 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();
            Log.e("JSON", json);
        } 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;

    }


    protected void onPostExecute(JSONObject jObj) {

        result = jObj;
        progressDialog.dismiss();

    }

    public JSONObject getJson(List<NameValuePair> params){

        this.execute(params);

        return result;

    }

}
公共类JSONParser扩展了异步任务{
静态InputStream为空;
静态JSONObject jObj=null;
静态JSONObject结果=null;
静态字符串json=“”;
私有静态字符串jsonURL=”http://192.168.1.119/Server/db/json/";
私有进程对话;
//建造师
公共JSONParser(){
}
@凌驾
受保护的void onPreExecute(){
//progressDialog=新建progressDialog();
progressDialog.setMessage(“Aguarde…”);
progressDialog.show();
}
受保护的JSONObject doInBackground(列表…参数){
//发出HTTP请求
试一试{
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(jsonURL);
setEntity(新的UrlEncodedFormEntity(参数[0]);
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(例外e){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.附加(第+行“n”);
}
is.close();
json=sb.toString();
Log.e(“JSON”,JSON);
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
受保护的void onPostExecute(JSONObject jObj){
结果=jObj;
progressDialog.disclose();
}
公共JSONObject getJson(列表参数){
执行(params);
返回结果;
}
}

UserFunctions.java(一些调用示例)

(…)
公共用户函数(){
JSONParser JSONParser=新的JSONParser();
}
公共JSONObject登录用户(字符串电子邮件、字符串密码){
List params=new ArrayList();
添加(新的BasicNameValuePair(“标签”,登录标签));
参数添加(新的BasicNameValuePair(“电子邮件”),电子邮件);
添加(新的BasicNameValuePair(“密码”,password));
JSONObject json=jsonParser.getJson(参数);
//JSONObject json=jsonParser.execute(params);//不返回
返回json;
}
公共JSONObject列表项目(字符串电子邮件){
List params=new ArrayList();
添加参数(新的BasicNameValuePair(“标签”,列出项目));
参数添加(新的BasicNameValuePair(“电子邮件”),电子邮件);
JSONObject json=jsonParser.getJson(参数);
返回json;
}
公共JSONObject setDisp(字符串dispID、字符串disp、字符串注释){
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“标记”,设置显示));
添加(新的BasicNameValuePair(“dispID”,dispID));
参数add(新的BasicNameValuePair(“disp”,disp));
添加(新的BasicNameValuePair(“注释”,注释));
JSONObject json=jsonParser.getJson(参数);
返回json;
}
(...)


我试图将值传递给var(jsonobjectresult),但没有效果。(NullPointerException,我猜它会在异步完成之前尝试访问var,因为它是“异步的”)

我需要做什么才能得到这些值?有什么想法吗



非常感谢大家

习惯使用
AsyncTask
,您将非常需要它

如果任务完成后需要触发某些事件,请广播。每个感兴趣的人(包括其他活动)都需要为广播注册一个接收器

您的
异步任务

new AsyncTask<Void,Void,List<Result>>() {
  @Override
  public List<Result> doInBackground(Void... voids) {
    final List<Result> results = ...; // get from network, or whatever
  }

  @Override
  public void onPostExecute(List<Result> results) {
    Intent intent = new Intent("com.my.action.RESULTS_READY"); // or whatever
    intent.putExtra("com.my.extra.RESULTS", new ArrayList<Result>(results);
    sendBroadcast(intent);
  }
}.execute();
newasynctask(){
@凌驾
公共列表doInBackground(作废…作废){
最终列表结果=…;//从网络获取,或其他
}
@凌驾
public void onPostExecute(列出结果){
Intent Intent=new Intent(“com.my.action.RESULTS_READY”);//或者其他什么
intent.putExtra(“com.my.extra.RESULTS”),新的ArrayList(RESULTS);
发送广播(意图);
}
}.execute();
现在,在您的其他活动中,在
onCreate()
onDestroy()
中为此注册/注销。我假设您希望在暂停时接收广播并更新一些实例数据

请注意,还有其他选项。例如,您可以将结果写入数据库,然后仅广播结果已准备就绪,并期望每个感兴趣的方在需要时从数据库检索结果。这可能会更好,因为它不依赖于接收广播来获得有效数据(这也是
new AsyncTask<Void,Void,List<Result>>() {
  @Override
  public List<Result> doInBackground(Void... voids) {
    final List<Result> results = ...; // get from network, or whatever
  }

  @Override
  public void onPostExecute(List<Result> results) {
    Intent intent = new Intent("com.my.action.RESULTS_READY"); // or whatever
    intent.putExtra("com.my.extra.RESULTS", new ArrayList<Result>(results);
    sendBroadcast(intent);
  }
}.execute();