我想从下一个活动传递复选框值,但它会抛出NullPointerException

时间:2013-11-10 18:54:32

标签: java android nullpointerexception

import java.util.ArrayList;

// list of item with checkbox. the value i want to parse

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;

public class Item extends Activity implements OnClickListener {

    String [] builder;
    Button button;
    ListView listView;
    String [] array = new String[] {"Baby Cot ", "Bouncer", "Bottle", "Blanket", "Stroller", "Toy", "Walker", "Thermal Bag", "Storage Bag", "Diaper", "Pacifier", "Potty", "Baby Bath" , "Baby CD", "Baby Book", "Car Seat", "Teethers", "Cooler Bag", "High Chair", "Apparel"};
    private ArrayList<String> checked;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);

        listView =  (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        button = (Button) findViewById (R.id.testbutton);
        button.setOnClickListener(this);    
    }

    @Override
    public void onClick(View v) {
        SparseBooleanArray positions = listView.getCheckedItemPositions();

        for (int index = 0; index <array.length; index++){

            if (positions.get (index) == true)
            {
                checked.add(array [index]);

            }
        }

        Intent i = new Intent(this, AndroidJSONParsingActivity.class);
        // Bundle b = new Bundle();
        i.putStringArrayListExtra("Item", checked);
        startActivity(i);   
    }


    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

    }       
}



package com.example.searching2;

// value of checkbox pass to this activity

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidJSONParsingActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> shopList;

    // url to get all products list
    private static String url="http://10.0.2.2/fyp/item.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_SHOP = "shop";
    private static final String TAG_ITEM = "Item";
    private static final String TAG_ID = "Id";
    private static final String TAG_SHOP_ID = "Shop_id";
    private static final String TAG_SHOP_NAME = "Shop_Name";


    // products JSONArray
    JSONArray shop = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Hashmap for ListView
        shopList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadShop().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

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

                // Starting new intent
               ArrayList<String> getChecked;
               Bundle extras =  getIntent().getExtras();
               if (extras!= null)
               {
                   getChecked = extras.getStringArrayList("Item");
               }
            }
        });

    }


    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadShop extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AndroidJSONParsingActivity.this);
            pDialog.setMessage("Loading shop. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url, "POST", params);

            // Check your log cat for JSON reponse
            Log.d("All Shop: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    shop = json.getJSONArray(TAG_SHOP);

                    // looping through All Products
                    for (int i = 0; i < shop.length(); i++) {
                        JSONObject s = shop.getJSONObject(i);

                        // Storing each json item in variable

                        String Id = s.getString(TAG_ID);
                        String Shop_id = s.getString(TAG_SHOP_ID);
                        String Shop_Name = s.getString(TAG_SHOP_NAME);
                        String Item = s.getString(TAG_ITEM);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, Id);
                        map.put(TAG_SHOP_ID, Shop_id);
                        map.put(TAG_SHOP_NAME,Shop_Name );
                        map.put(TAG_ITEM, Item);

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


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

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, shopList, R.layout.list_item,
                         new String [] {TAG_ID,  TAG_SHOP_ID, TAG_SHOP_NAME, TAG_ITEM}, 
                         new int [] {R.id.Id, R.id.Shop_id, R.id.Shop_Name, R.id.Item});
                         setListAdapter(adapter);
                }
            });

        }

    }
}   

我想将复选框中的项目列表传递给android JSON活动。然后,android JSON将调用PHP文件以根据用户勾选复选框

来检索数据
11-10 21:41:07.542: E/AndroidRuntime(3273): FATAL EXCEPTION: main
11-10 21:41:07.542: E/AndroidRuntime(3273): java.lang.NullPointerException
11-10 21:41:07.542: E/AndroidRuntime(3273):     at com.example.searching2.Item.onClick(Item.java:54)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at android.view.View.performClick(View.java:4204)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at android.view.View$PerformClick.run(View.java:17355)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at android.os.Handler.handleCallback(Handler.java:725)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at android.os.Looper.loop(Looper.java:137)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at android.app.ActivityThread.main(ActivityThread.java:5041)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at java.lang.reflect.Method.invokeNative(Native Method)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at java.lang.reflect.Method.invoke(Method.java:511)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-10 21:41:07.542: E/AndroidRuntime(3273):     at dalvik.system.NativeStart.main(Native Method)
11-10 21:41:15.473: E/Trace(3310): error opening trace file: No such file or directory (2)

// LOGCAT ERROR FULL

仍然有NullPointerException

1 个答案:

答案 0 :(得分:2)

checked成员永远不会被初始化,因此您有空指针异常。

更改

ListView listView;
private ArrayList<String> checked;

ListView listView = new ListView( /* whatever it takes to create object */);
private ArrayList<String> checked = new ArrayList<String>();

在跟踪运行时错误时,堆栈跟踪至关重要。在堆栈跟踪中打印的检查行,您知道哪行代码会导致问题。