JSON将数据解析为android应用程序

时间:2014-04-07 03:41:01

标签: android json android-parser

我正在尝试将JSON解析数据导入android。

我无法理解的错误是什么。

我是java和android的初学者。

这段代码并不难,你不会无聊。

我的错误和代码显示如下:

04-07 05:19:02.305: E/AndroidRuntime(19599): FATAL EXCEPTION: main
04-07 05:19:02.305: E/AndroidRuntime(19599): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.buet_parsing/com.example.buet_parsing.MainActivity}: java.lang.NullPointerException
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.os.Looper.loop(Looper.java:137)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.app.ActivityThread.main(ActivityThread.java:5041)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at java.lang.reflect.Method.invokeNative(Native Method)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at java.lang.reflect.Method.invoke(Method.java:511)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at dalvik.system.NativeStart.main(Native Method)
04-07 05:19:02.305: E/AndroidRuntime(19599): Caused by: java.lang.NullPointerException
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.widget.ListView.setAdapter(ListView.java:462)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at com.example.buet_parsing.MainActivity.onCreate(MainActivity.java:46)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.app.Activity.performCreate(Activity.java:5104)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-07 05:19:02.305: E/AndroidRuntime(19599):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-07 05:19:02.305: E/AndroidRuntime(19599):    ... 11 more
04-07 05:19:11.135: I/Process(19599): Sending signal. PID: 19599 SIG: 9

MainAcitivity:

package com.example.buet_parsing;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.JSONObject;
import org.w3c.dom.ls.LSInput;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

    ListView lv;
    CustomAdapter adapter;

    String urlString="http://cricscore-api.appspot.com/csa";
    ArrayList<ListIteam> allNews;

   AlertDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=(ListView)findViewById(R.id.list);

        adapter=new CustomAdapter(this, allNews);
        lv.setAdapter(adapter);


        DownloadTask download=new DownloadTask();

        Log.v(getClass().getSimpleName(), "Loading data.......");

        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setMessage("Loading data..");
        builder.setView(new ProgressBar(this));
        progressDialog=builder.create();
        progressDialog.show();


        download.execute();




    }


    class DownloadTask extends AsyncTask<Void, Void, String>{

        @Override
        protected String doInBackground(Void... params) {

          String result=null;

          try {
              HttpClient client=new DefaultHttpClient();
          HttpGet get=new HttpGet(urlString);
          HttpResponse response=client.execute(get);

          if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){

              InputStream in=response.getEntity().getContent();
              BufferedReader reader=new BufferedReader(new InputStreamReader(in));
              String line=reader.readLine();
              Log.v(getClass().getSimpleName(), line);

             return line; 
          }


        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }   

            return result;
        }

        @Override
        protected void onPostExecute(String result) {

            progressDialog.dismiss();

            try {

                JSONArray array=new JSONArray(result);
                for (int i = 0; i < result.length(); i++) {
                    JSONObject object=array.getJSONObject(i);
                    String team1=object.getString("t1");
                    String team2=object.getString("t2");
                    ListIteam ls=new ListIteam(team1, team2);
                    allNews.add(ls);

                    adapter.notifyDataSetChanged();
                }


            } catch (Exception e) {
                e.printStackTrace();
            }


        }



    }


}

CustomAdapter:

package com.example.buet_parsing;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class CustomAdapter extends ArrayAdapter<ListIteam>{

    Activity context;
    ArrayList<ListIteam> ls;

    public CustomAdapter(Activity context, ArrayList<ListIteam> ls) {
        super(context, R.layout.adapter_layout, ls);
      this.context=context;
      this.ls=ls;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
          View view=convertView;

          LayoutInflater inflat=context.getLayoutInflater();
          view=inflat.inflate(R.layout.adapter_layout, null, false);

          TextView txtTeam1=(TextView)view.findViewById(R.id.team1);
          TextView txtTeam2=(TextView)view.findViewById(R.id.team2); 

          ListIteam l=ls.get(position);
          txtTeam1.setText(l.getTeam1());
          txtTeam2.setText(l.getTeam2());


        return view;
    }



}

列表项:

package com.example.buet_parsing;

public class ListIteam {

    String team1;
    String team2;

    public ListIteam(String team1, String team2) {
        super();
        this.team1 = team1;
        this.team2 = team2;
    }

    public String getTeam1() {
        return team1;
    }

    public void setTeam1(String team1) {
        this.team1 = team1;
    }

    public String getTeam2() {
        return team2;
    }

    public void setTeam2(String team2) {
        this.team2 = team2;
    }

    @Override
    public String toString() {
        return "ListIteam [team1=" + team1 + ", team2=" + team2 + "]";
    }




}

3 个答案:

答案 0 :(得分:1)

在展开ListActivity时,您需要一个ID为@android:id/list

的ListView

你的错误堆栈也说

04-07 03:01:28.856: E/AndroidRuntime(2305): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

答案 1 :(得分:1)

在执行DownloadTask之前你做错了你已经设置了你的适配器,所以你总是得到NullPinterException

 adapter=new CustomAdapter(this, allNews);
 lv.setAdapter(adapter);

因此,您必须从onCreate()方法中移除此内容,并在onPostExecute()的{​​{1}}方法中进行设置。像,

DownloadTask

此外,您刚刚声明了全局变量 @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); adapter=new CustomAdapter(this, allNews); lv.setAdapter(adapter); } ;没有初始化它。所以在ArrayList<ListIteam> allNews方法上初始化它。像

onCreate()

答案 2 :(得分:1)

当您在oncreate中为listview设置适配器时,

allNews为null,因此初始化allNews 替换ArrayList<ListIteam> allNews=new ArrayList<ListIteam>;