2014-01-25 3 views
1

나는 4 개의 스피너가 null을 반환하고 왜 그럴 수 없는지를 설명합니다. 난 지금 내가 ID를 가지고 있는지했고 나는 확실히 그것을 옳다고하기 위해 다른 활동에 사용하고 있음을 내 코드를 다음하지만 클래스의 전체 코드가Spinner return null

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

    } 

} 

} 
입니다

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) 

말을 충돌 계속

누군가가 나를 도와 주거나 올바른 방향으로 나를 가르키면 좋을 것입니다. 스피너가 대화 상자에 있기 때문에 그럴 수 있다고 생각하지만 실제로는 잘 모르겠습니다. 당신이 Toast를 만들 어디 당신의 onItemSelected() 방법에 getApplicationContext() 대신 parent.getContext()의를 사용하려고 할 것입니다 전체 로그 캣

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) 
+0

어느 라인이 157입니까? –

+0

모든 회 전자에 실제로 선택한 항목이 있습니까? getSelectedItem()에 대한 문서에 따르면 ... ** "현재 선택된 항목에 해당하는 데이터이거나 아무것도 선택되지 않은 경우 null입니다. ** – Squonk

+0

157 : spinner_pavement = (Spinner) findViewById (R.id. spinner_search_pavement); 나는 스피너를 클릭하고 다른 것을 클릭하기 때문에 무언가가 선택되었다고 확신한다. – TylerM

답변

1
DialogfindViewById(...) 방법을 사용하는 ... ... 당신의 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); 

를 다음 줄을 변경

. 예 ... 당신은 것

spinner_pavement = (Spinner) search.findViewById(R.id.spinner_search_pavement); 

길을 따라 교차하여 선을 가지고하고 당신은 당신의 활동의 내용보기 대신 대화의에서 스피너를 찾기 위해 노력하고 있습니다.

+1

고맙습니다. D 해결! – TylerM

0

:

타일러에게 사전에

편집을 주셔서 감사합니다.

+0

이것은'dialogButton'의'OnClickListener'의'onClick (...)'메소드에서 NPE와 어떤 관련이 있습니까? – Squonk