سؤال

I am trying JSON parse data into android.

What is my Error i can not understand.

I am beginner of java and android also.

This code is not hard, you will not boring.

My Error and Code show bellow:

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



}

ListItem:

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 + "]";
    }




}
هل كانت مفيدة؟

المحلول

allNews is null when you set adapter for the listview in oncreate so initialize allNews replace ArrayList<ListIteam> allNews=new ArrayList<ListIteam>;

نصائح أخرى

As you are extending ListActivity ,you need to have a ListView with id @android:id/list

Your error stack also saying that

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'

You are doing wrong before executing your DownloadTask you have set your adapter so you always get NullPinterException here

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

So you have to remove this from onCreate() method and set in onPostExecute() method of your DownloadTask. Like,

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

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

    }

Also you have just declared global variable ArrayList<ListIteam> allNews; not initialize it. So initialize it on onCreate() method. Like

 allNews = new ArrayList<ListIteam>():
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top