java - 如何为 android 的连接 json 调用创建线程

标签 java android json multithreading

我在第 97 行收到此错误 java.lang.NullPointerException

我认为是为了 de json 调用,因为没有获取数据,

我如何创建一个线程,首先获取这些数据然后执行下一步。

我在这方面真的很新,所以任何帮助我们都很感激。

package com.zoada;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;



public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // esconde el titlebar de la aplicaci�n
        // tiene que estar antes de colocar el mainLayout
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // esconde el statusbar de Android
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        JSONArray posiciones = null;

        // *** Comienza la comunicaci�n con el servidor

        BufferedReader in = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http://zoada.com/blah.php");
            HttpResponse response = client.execute(request);


            // leyendo "response"  un string gigantesco
            in = new BufferedReader(
                    new InputStreamReader(
                            response.getEntity().getContent()));

            // imprimpiendo el tarugo de texto linea a linea

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String page = sb.toString();
            //System.out.println(page);

            //aqui viene la parte JSON!!!

            JSONObject jObject = new JSONObject(page);
            posiciones = jObject.getJSONArray("positions");

            for (int i=0; i< posiciones.length(); i++) {
                JSONObject jo = posiciones.getJSONObject(i);
                //System.out.println(jo.getString("name"));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // *** termina comunicaci�n con el servidor


        TableLayout tl = (TableLayout)findViewById(R.id.containerTable);
        LayoutInflater inflater = getLayoutInflater();

        for (int i = 0; i < posiciones.length(); i++) {
            try {
                JSONObject jo = posiciones.getJSONObject(i);

                TableRow row = (TableRow)inflater.inflate(R.layout.tablerow, tl, false);

                TextView pos = (TextView)row.findViewById(R.id.position);
                String posTxt=jo.getString("position");
                pos.setText(posTxt);

                TextView team = (TextView)row.findViewById(R.id.team);
                String teamTxt=jo.getString("name");
                team.setText(teamTxt);

                TextView points = (TextView)row.findViewById(R.id.points);
                String pointsTxt=jo.getString("points");
                points.setText(pointsTxt);

                TextView games = (TextView)row.findViewById(R.id.games);
                String gamesTxt=jo.getString("played");
                games.setText(gamesTxt);

                TextView victories = (TextView)row.findViewById(R.id.victories);
                String victoriesTxt=jo.getString("won");
                victories.setText(victoriesTxt);

                TextView draw = (TextView)row.findViewById(R.id.draw);
                String drawsTxt=jo.getString("draw");
                draw.setText(drawsTxt);

                TextView lost = (TextView)row.findViewById(R.id.loss);
                String loseTxt=jo.getString("lost");
                lost.setText(loseTxt);

                TextView goals = (TextView)row.findViewById(R.id.goals);
                int goalsInt = Integer.parseInt(jo.getString("gol"));
                int againstInt = Integer.parseInt(jo.getString("against"));
                String goalsTxt=goalsInt+":"+againstInt;
                goals.setText(goalsTxt);

                TextView diff = (TextView)row.findViewById(R.id.difference);
                int diffInt=goalsInt-againstInt;
                String diffTxt=""+diffInt;
                diff.setText(diffTxt);
/**/
                tl.addView(row);            
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // text = (EditText) findViewById(R.id.EditText01);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

最佳答案

您不应该在 UI 线程中执行网络操作! 例如,您可以在您的类(class)中创建 AsyncTask。 它可能看起来类似于此

   private class ParseTask extends AsyncTask<Params, Progress, Result> {
   @Override
   protected Result doInBackground(Params params) {
        // get url 
        Params url = params[0];
        // create HttpClient etc.
        ...
        // get response, and parse json
        // return 
        return result;
   }

   @Override
   protected void onPostExecute (Result result) {
        // now when you have result from parsed json, 
        // update application UI or whatever you need
        someEditText.setText(value_from_result);
   }
}

然后调用onCreate方法

ParseTask task = new ParseTask();
task.execute(url);

启动 AsyncTask。

另一方面,也可以在IntentService中处理json,或者一般的服务,解析后的json通过广播返回给Activity,也可以达到同样的效果。

关于java - 如何为 android 的连接 json 调用创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11870864/

相关文章:

android - 如何以 RectangleF 为边界裁剪位图

android - 我如何从假装成微型电话的USB加速度传感器获取数据?

javascript - D3 不会加载 Tree Map

html - 需要一些 HTML 正则表达式帮助(是的,我知道这是不应该完成的)

java - 嵌入式系统的Web服务器

java - 合并两个以上外部库功能的设计模式

java - Java 代码中的 Kotlin 集成?

java - 如何将简单字符串或对象的 JSON 元素解析为类对象

java - 将路径传递给 exec

java 以下枚举中的 {{ }} 和 -> 是什么