Spinner返回null

时间:2014-01-25 22:19:27

标签: android null spinner

我有4个返回null的微调器,我无法弄清楚原因。我确保我有正确的ID,并遵循我在另一个活动中使用的代码,以确保它是正确的,但它一直在崩溃说

01-25 17:02:47.464: E/AndroidRuntime(13052): java.lang.NullPointerException
01-25 17:02:47.464: E/AndroidRuntime(13052):    at com.skateconnect.AllSpotsActivity$2.onClick(AllSpotsActivity.java:157)

该类的整个代码是

public class AllSpotsActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

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

ArrayList<HashMap<String, String>> spotsList;
GPSTracker gps;

// url to get all products list
//private static String url_all = "http://72.83.78.137:8080/skate_connect/get_all.php";
private static String url_all = "http://skateconnect.no-ip.biz:8080/skate_connect/get_all.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SPOTS = "spots";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private int search_trig=0;

// products JSONArray
JSONArray spots = null;

private Spinner spinner_pavement, spinner_traffic, spinner_enviro,spinner_dist;
private String str_pavement, str_traffic, str_enviro,str_dist;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_spots);
    gps = new GPSTracker(AllSpotsActivity.this);

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

    // Loading products in Background Thread
    whattosearch();
    //new LoadAllSpots().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 pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    ViewSpotActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos,
            long id) {
        Toast.makeText(parent.getContext(),
                parent.getItemAtPosition(pos).toString(),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

public void addListenerOnSpinnerItemSelection() {

    spinner_pavement = (Spinner) findViewById(R.id.spinner_search_pavement);
    spinner_pavement
            .setOnItemSelectedListener(new CustomOnItemSelectedListener());
    spinner_traffic = (Spinner) findViewById(R.id.spinner_search_traffic);
    spinner_traffic
            .setOnItemSelectedListener(new CustomOnItemSelectedListener());
    spinner_enviro = (Spinner) findViewById(R.id.spinner_search_enviro);
    spinner_enviro
            .setOnItemSelectedListener(new CustomOnItemSelectedListener());
    spinner_dist = (Spinner) findViewById(R.id.spinner_dist);
    spinner_dist
            .setOnItemSelectedListener(new CustomOnItemSelectedListener());
}

void whattosearch(){
    final Dialog search = new Dialog(this);
    search.setContentView(R.layout.search);
    search.setTitle("What to Search For: ");
    search.setCancelable(false);

    spinner_pavement = (Spinner) findViewById(R.id.spinner_search_pavement);
    spinner_traffic = (Spinner) findViewById(R.id.spinner_search_traffic);
    spinner_enviro = (Spinner) findViewById(R.id.spinner_search_enviro);
    spinner_dist = (Spinner) findViewById(R.id.spinner_dist);

    Button dialogButton = (Button) search.findViewById(R.id.ButtonOK);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v) {
            //these are returning null...
            str_pavement = spinner_pavement.getSelectedItem().toString();
            str_traffic = spinner_traffic.getSelectedItem().toString();
            str_enviro = spinner_enviro.getSelectedItem().toString();
            str_dist = spinner_dist.getSelectedItem().toString();
            search_trig=1;
            search.dismiss(); 
            new LoadAllSpots().execute();

        }
      });
    Button dialogSeeAll = (Button) search.findViewById(R.id.ButtonAll);
    // if button is clicked, close the custom dialog
    dialogSeeAll.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v) {
            search.dismiss(); 
            search_trig=0;
            new LoadAllSpots().execute();
        }
      });
    search.show();
}



// Response from Edit Product Activity
// using longest equation to get least amount of error
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

private double getDistance(double fromLat, double fromLon, double toLat,
        double toLon) {
    Location location1 = new Location("loc1");
    location1.setLatitude(fromLat);
    location1.setLongitude(fromLon);
    Location location2 = new Location("loc2");
    location2.setLatitude(toLat);
    location2.setLongitude(toLon);

    double d = location1.distanceTo(location2) * 0.000621371;// convert to
                                                                // miles
    return d;
}

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

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

    /**
     * getting All products from url
     * */
    @Override
    protected String doInBackground(String... args) {
        double slat = gps.getLatitude();
        double slong = gps.getLongitude();
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all, "GET", params);

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

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

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

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

                    // Storing each json item in variable
                    double elong = Double.parseDouble(c
                            .getString("longitude"));
                    double elat = Double.parseDouble(c
                            .getString("latitude"));
                    double dist = getDistance(slat, slong, elat, elong);
                    String distance = String.format("%.1f", dist);
                    String id = c.getString(TAG_PID);
                    String pave = c.getString("pavement");
                    String traffic = c.getString("traffic");
                    String enviro = c.getString("environment");
                    String name = c.getString(TAG_NAME) + ": " + distance
                            + " Miles Away";
                    //need to create case statement here on search_trig
                    //0 means search all
                    //1 means search by inputs
                    // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);
                        map.put("distance", distance);

                        // adding HashList to ArrayList
                        spotsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewSpotActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {

        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllSpotsActivity.this, spotsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME, "distance" }, new int[] {
                                R.id.pid, R.id.name, R.id.distance });
                Collections.sort(spotsList,
                        new Comparator<Map<String, String>>() {

                            @Override
                            public int compare(Map<String, String> o1,
                                    Map<String, String> o2) {
                                String value1 = o1.get("distance");
                                String value2 = o2.get("distance");
                                return Double.valueOf(value1).compareTo(
                                        Double.valueOf(value2));
                            }
                        });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}

}

如果有人能帮助我,或指出我的方向是正确的,那就太好了。我想这可能是因为微调器在对话框中,但我不太确定。

提前谢谢你,

泰勒

编辑:完整的logcat

01-25 20:21:03.652: E/AndroidRuntime(18730): FATAL EXCEPTION: main
01-25 20:21:03.652: E/AndroidRuntime(18730): Process: com.skateconnect, PID: 18730
01-25 20:21:03.652: E/AndroidRuntime(18730): java.lang.NullPointerException
01-25 20:21:03.652: E/AndroidRuntime(18730):    at com.skateconnect.AllSpotsActivity$2.onClick(AllSpotsActivity.java:157)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at android.view.View.performClick(View.java:4452)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at android.view.View$PerformClick.run(View.java:18498)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at android.os.Handler.handleCallback(Handler.java:733)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at android.os.Looper.loop(Looper.java:137)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at android.app.ActivityThread.main(ActivityThread.java:5083)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at java.lang.reflect.Method.invokeNative(Native Method)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at java.lang.reflect.Method.invoke(Method.java:515)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-25 20:21:03.652: E/AndroidRuntime(18730):    at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

更改whattosearch()方法中的以下行...

spinner_pavement = (Spinner) findViewById(R.id.spinner_search_pavement);
spinner_traffic = (Spinner) findViewById(R.id.spinner_search_traffic);
spinner_enviro = (Spinner) findViewById(R.id.spinner_search_enviro);
spinner_dist = (Spinner) findViewById(R.id.spinner_dist);

...使用findViewById(...)的{​​{1}}方法。实施例...

Dialog

您似乎已经将电线穿过,并且您试图在活动的内容视图中找到旋转器而不是在对话框中。

答案 1 :(得分:0)

我会尝试在您创建getApplicationContext()的{​​{1}}方法中使用parent.getContext()代替onItemSelected()