空指针异常组件信息

时间:2014-06-28 09:41:31

标签: android json android-listview

获取空指针异常,我已经在清单中声明了所有活动但仍然发生错误请帮我解决这个问题。 错误是 06-28 14:55:55.683:E / AndroidRuntime(889):引起:java.lang.NullPointerException 06-28 14:55:55.683:E / AndroidRuntime(889):at com.androidhive.jsonparsing.SingleMenuItemActivity.onCreate(SingleMenuItemActivity.java:65)

代码 AndroidJsonparsingActivity.java

public class AndroidJSONParsingActivity<Search> extends ListActivity {

    public class HorizontalListview {

    }

    // url to make request
    private static String url ="";

    // JSON Node names
    Bitmap bitmap;
    Bitmap bitmap1;
    Bitmap bitmap2;
    Bitmap bitmap3;
    @SuppressWarnings("unused")
    private static final String TAG_MOVIE = "Movies";   
    private static final String TAG_MOVIEID = "MovieId";
    @SuppressWarnings("unused")
    private static final String TAG_MOVIEIMAGE = "MovieImage";
    private static final String TAG_DISTANCE =  "Distance";
    private static final String TAG_PINCODE = "PinCodeNo";
    private static final String TAG_THEATERS =  "Theaters";
    private static final String TAG_THEATERSNAME =  "TheaterName";
    ImageView iv;
    ListView lv1;
    // contacts JSONArray
    JSONArray movies = null;
    JSONArray theaters = null;
    ImageView i,iv1,iv2,iv3;
    TextView tv;
    JSONArray dates = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        iv=(ImageView) findViewById(R.id.imageView1);
        iv1=(ImageView) findViewById(R.id.imageView2);
        iv2=(ImageView) findViewById(R.id.imageView3);
         iv3=(ImageView)findViewById(R.id.imageView4);
         tv=(TextView)findViewById(R.id.date1);
         Spinner sp=(Spinner)findViewById(R.id.spinner1);
        //p=(ProgressBar) findViewById(R.id.loader);
        ImageLoader imageLoader = new ImageLoader(AndroidJSONParsingActivity.this);
        //i.setTag(imgUrl);
       // imageLoader.DisplayImage("http://content6.flixster.com/movie/11/17/84/11178428_pro.jpg", AndroidJSONParsingActivity.this,iv,);
        // Hashmap for ListView
        ArrayList<HashMap<String, String>> movieList = new ArrayList<HashMap<String, String>>();
        ArrayList<HashMap<String, String>> theaterList = new ArrayList<HashMap<String, String>>();
        bitmap = getBitmapFromUrl("http://content6.flixster.com/movie/11/17/75/11177548_pro.jpg");
        bitmap1 = getBitmapFromUrl("http://content6.flixster.com/movie/11/17/84/11178428_pro.jpg");
        bitmap2 = getBitmapFromUrl("http://content7.flixster.com/movie/11/17/82/11178261_pro.jpg");
        bitmap3 = getBitmapFromUrl("http://content7.flixster.com/movie/11/17/82/11178261_pro.jpg");
        iv.setImageBitmap(bitmap);
        iv1.setImageBitmap(bitmap1);
        iv2.setImageBitmap(bitmap2);
        iv3.setImageBitmap(bitmap3);
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();
        @SuppressWarnings("unused")
        JSONParser client = new JSONParser(
                WebServiceUrl.GetDatesForTheater2);
        // getting JSON string from URL
        JSONObject json = null;
        json = jParser.getJSONFromUrl(url);
        @SuppressWarnings("unused")
        String jsonString ="";
        String jResponse = client.getStrResponse();
        // dates = new ArrayList<String>();
        try {
            // Getting Array of Contacts
            JSONArray  j= json.getJSONArray(jResponse);
            //theaters = json.getJSONArray(TAG_THEATERS);
            // looping through All Contacts
            for(int i = 0; i < j.length(); i++){
                JSONObject c = j.getJSONObject(i);
                System.out.println("val of c  " +c);
                // Storing each json item in variable
                //String id = c.getString(TAG_MOVIEID);

                //String image = c.getString(TAG_MOVIEIMAGE);

                // Phone number is agin JSON Object


                // creating new HashMap
                //HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                //map.put(TAG_MOVIEID, id);
                //map.put(TAG_MOVIEIMAGE, image);

                // adding HashList to ArrayList
                //movieList.add(map);
            }

        JSONArray jsonarray = new JSONArray(jResponse);
        if(Global.showTimes.size()<=0){

        for (int i = 0; i < jsonarray.length(); i++) {

            System.out.println(jsonarray.get(i));
            Global.showTimes.add(String.valueOf(jsonarray.get(i)));
        }
        }

        System.out.println("value of dates:->" + Global.showTimes);
            tv.setText((CharSequence) Global.showTimes);


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("exception" +e);
        }
        //ArrayAdapter<CharSequence> as = new ArrayAdapter<CharSequence>(getApplicationContext(),R.id.date);
       // as.setDropDownViewResource(android.R.layout.simple_spinner_item);
        //as.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //sp.setAdapter(as);
 catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("this is the error" +e);
        }

        try {
            // Getting Array of Contacts
            movies = json.getJSONArray(TAG_MOVIE);
            //theaters = json.getJSONArray(TAG_THEATERS);
            // looping through All Contacts
            for(int i = 0; i < movies.length(); i++){
                JSONObject c = movies.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_MOVIEID);

                //String image = c.getString(TAG_MOVIEIMAGE);

                // Phone number is agin JSON Object


                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_MOVIEID, id);
                //map.put(TAG_MOVIEIMAGE, image);

                // adding HashList to ArrayList
                movieList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ListAdapter adapter1 = new SimpleAdapter(this, movieList,
                R.layout.list_item,
                new String[] { TAG_MOVIEID, TAG_MOVIEIMAGE }, new int[] {
                        R.id.name, R.id.image, });

        setListAdapter(adapter1);
        try {
            // Getting Array of Contacts

            theaters = json.getJSONArray(TAG_THEATERS);
            // looping through All Contacts
            for(int i = 0; i < theaters.length(); i++){
                JSONObject c = theaters.getJSONObject(i);

                // Storing each json item in variable
                String name = c.getString(TAG_THEATERSNAME);
                String distance = c.getString(TAG_DISTANCE);
                String pincode = c.getString(TAG_PINCODE);
                //String image = c.getString(TAG_MOVIEIMAGE);

                // Phone number is agin JSON Object


                // creating new HashMap
                HashMap<String, String> map1 = new HashMap<String, String>();

                // adding each child node to HashMap key => value

                map1.put(TAG_DISTANCE,distance);
                map1.put(TAG_PINCODE,pincode);
                map1.put(TAG_THEATERSNAME,name);
                //map.put(TAG_MOVIEIMAGE, image);

                // adding HashList to ArrayList
                theaterList.add(map1);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */

        @SuppressWarnings("unused")
        ListAdapter adapter11 = new SimpleAdapter(this, theaterList,
                R.layout.list_item,
                new String[] { TAG_THEATERSNAME,TAG_DISTANCE,TAG_PINCODE}, new int[] {
                        R.id.tname,R.id.distance,R.id.pincode }); 

        setListAdapter(adapter11);

        // selecting single ListView item
    ListView lv = getListView();

    @SuppressWarnings("unused")
    ListView lv1= getListView();
        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                //String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                //String cost = ((TextView) view.findViewById(R.id.image)).getText().toString();

                TextView tv=(TextView)findViewById(R.id.tname);
                tv.setText(TAG_THEATERSNAME);
                String name = tv.getText().toString();

                  bitmap = getBitmapFromUrl("http://content6.flixster.com/movie/11/17/84/11178428_pro.jpg");

                  bitmap1 = getBitmapFromUrl("http://content6.flixster.com/movie/11/17/84/11178428_pro.jpg");

                  bitmap2 = getBitmapFromUrl("http://content6.flixster.com/movie/11/17/84/11178428_pro.jpg");





                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);

        in.putExtra("tname", name);
        System.out.println("THEATER NAME" +TAG_THEATERSNAME);

                startActivity(in);

            }

            private Bitmap getBitmapFromUrl(String src) {
                // TODO Auto-generated method stub
                try {

                    URL url =new URL(src);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input=connection.getInputStream();
                    Bitmap mybiBitmap=BitmapFactory.decodeStream(input);
                    return mybiBitmap;


                 } catch (Exception e) {
                    // TODO: handle exception
                   e.printStackTrace();
                   return null;
                 }
            }
        });



    }

    private Bitmap getBitmapFromUrl(String src) {
        // TODO Auto-generated method stub
        try {

            URL url =new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input=connection.getInputStream();
            Bitmap mybiBitmap=BitmapFactory.decodeStream(input);
            return mybiBitmap;


         } catch (Exception e) {
            // TODO: handle exception
           e.printStackTrace();
           return null;
         }


    }

Singlemenuitemactivity.java

public class SingleMenuItemActivity  extends Activity {
    private static String url ="";

    Bitmap bitmap;
    Bitmap bitmap1,bitmap2,bitmap3;
    ImageView iv,iv1,iv2,iv3;
    private static final String TAG_DISTANCE =  "Distance";
    private static final String TAG_PINCODE = "PinCodeNo";
    private static final String TAG_THEATERS =  "Theaters";
    private static final String TAG_THEATERSNAME =  "TheaterName";
    //private static final String TAG_THEATERS =  "Theaters";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_list_item);
        JSONObject json = null;
        JSONArray theaters = null;
        @SuppressWarnings("unused")
        TextView tv=(TextView)findViewById(R.id.date1);
        ImageView iv=(ImageView)findViewById(R.id.imageView1);
        ImageView iv1=(ImageView)findViewById(R.id.imageView2);
        ImageView iv2=(ImageView)findViewById(R.id.imageView3);
        ImageView iv3=(ImageView)findViewById(R.id.imageView4);
        ArrayList<HashMap<String, String>> theaterList = new ArrayList<HashMap<String, String>>();
        bitmap = getBitmapFromUrl("http://content6.flixster.com/movie/11/17/75/11177548_pro.jpg");
        bitmap1 = getBitmapFromUrl("http://content6.flixster.com/movie/11/17/84/11178428_pro.jpg");
        bitmap2 = getBitmapFromUrl("http://content7.flixster.com/movie/11/17/82/11178261_pro.jpg");
        bitmap3 = getBitmapFromUrl("http://content7.flixster.com/movie/11/17/82/11178261_pro.jpg");
        iv.setImageBitmap(bitmap);
        iv1.setImageBitmap(bitmap1);
        iv2.setImageBitmap(bitmap2);
        iv3.setImageBitmap(bitmap3);
        try {
            // Getting Array of Contacts

            theaters = json.getJSONArray(TAG_THEATERS);
            // looping through All Contacts
            for(int i = 0; i < theaters.length(); i++){
                JSONObject c = theaters.getJSONObject(i);

                // Storing each json item in variable
                String name = c.getString(TAG_THEATERSNAME);
                String distance = c.getString(TAG_DISTANCE);
                String pincode = c.getString(TAG_PINCODE);
                //String image = c.getString(TAG_MOVIEIMAGE);

                // Phone number is agin JSON Object


                // creating new HashMap
                HashMap<String, String> map1 = new HashMap<String, String>();

                // adding each child node to HashMap key => value

                map1.put(TAG_DISTANCE,distance);
                map1.put(TAG_PINCODE,pincode);
                map1.put(TAG_THEATERSNAME,name);
                //map.put(TAG_MOVIEIMAGE, image);

                // adding HashList to ArrayList
                theaterList.add(map1);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */

        @SuppressWarnings("unused")
        ListAdapter adapter11 = new SimpleAdapter(this, theaterList,
                R.layout.list_item,
                new String[] { TAG_THEATERSNAME,TAG_DISTANCE,TAG_PINCODE}, new int[] {
                        R.id.tname,R.id.distance,R.id.pincode }); 

        setListAdapter(adapter11);





      //  ListView LV=(ListView)findViewById(R.id.listView1);
    }
    private void setListAdapter(ListAdapter adapter11) {
        // TODO Auto-generated method stub

    }
    private Bitmap getBitmapFromUrl(String src) {
        // TODO Auto-generated method stub
        try {

            URL url =new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input=connection.getInputStream();
            Bitmap mybiBitmap=BitmapFactory.decodeStream(input);
            return mybiBitmap;


         } catch (Exception e) {
            // TODO: handle exception
           e.printStackTrace();
           return null;
         }
    }

}

Jsonparser.java

public class JSONParser {
    public enum RequestMethod {
        GET, POST
    }
    private String url;
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    String strResponse;
    private ArrayList<NameValuePair> params;
    // constructor

    public JSONParser() {

    }
    public JSONParser(String url) {
        this.url= url;
        params = new ArrayList<NameValuePair>();
    }
    public String getStrResponse() {

        return strResponse;
    }

    public boolean Execute(RequestMethod method) throws Exception {
        boolean isExpired = false;
        switch (method) {
        case GET: {
            // add parameters
            String combinedParams = "";
            if (!params.isEmpty()) {
                combinedParams += "?";
                for (NameValuePair p : params) {
                    String paramString = p.getName() + "="
                            + URLEncoder.encode(p.getValue(), "UTF-8");
                    if (combinedParams.length() > 1) {
                        combinedParams += "&" + paramString;
                    } else {
                        combinedParams += paramString;

                    }
            }
            }
        }
        }
        return isExpired;
    }
    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpget);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException 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();
        } 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;

    }
    public void AddParam(String name, String value) {
        params.add(new BasicNameValuePair(name, value));
    }
}

1 个答案:

答案 0 :(得分:1)

您尚未初始化

JSONObject json = null;

之前使用

 theaters = json.getJSONArray(TAG_THEATERS);

结果你得到NullPointerException。您可能希望获取一些数据并将其存储在json