1

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

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

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

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

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;
    }
}
4

1 回答 1

1

您不应该在 UI 线程中执行网络操作!例如,您可以在类中创建 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);

启动异步任务。

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

于 2012-08-08T19:23:55.040 回答