2014-09-23 479 views
0

好吧,我實現了一個可搜索的列表視圖。它沒關係,但我希望listview項目具有popupmenu。所以我試着用一些代碼在listview上實現這個popupmenu,並在另一個activity上顯示完整的item詳細信息。但是我得到了一個runtimeexception,我不知道該怎麼做。它說「無法啓動albusmActivity java.lang.NullPointerException」上的componentInfo。任何幫助都會很棒。謝謝。PopupMenu RuntimeException

@SuppressLint("NewApi") 

    public class AlbumsActivity extends ListActivity {ConnectionDetector cd; 
    AlertDialogManager alert = new AlertDialogManager(); 

    private ProgressDialog pDialog; 

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

    ArrayList<HashMap<String, String>> albumsList; 

    // albums JSONArray 
    JSONArray albums = null;      
    EditText inputSearch; 
    ImageView imgClick; 
    SimpleAdapter adapter = null;    
    // albums JSON url       
    private static final String URL_ALBUMS = "http://api.androidhive.info/songs/album.php"; 

    // ALL JSON node names 
    private static final String TAG_ID = "id"; 
    private static final String TAG_NAME = "name"; 
    private static final String TAG_SONGS_COUNT = "songs_count"; 

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

     getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998"))); 
     getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent))); 

     cd = new ConnectionDetector(getApplicationContext()); 

     // Check for internet connection 
     if (!cd.isConnectingToInternet()) { 
      // Internet Connection is not present 
      alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error", 
        "Please connect to working Internet connection", false); 
      // stop executing code by return 
      return; 
     } 

     // Hashmap for ListView 
     albumsList = new ArrayList<HashMap<String, String>>(); 
     inputSearch = (EditText) findViewById(R.id.inputSearch); 

      inputSearch.addTextChangedListener(new TextWatcher() { 

       @Override 
       public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { 
        // When user changed the Text 
        AlbumsActivity.this.adapter.getFilter().filter(cs.toString()); 
       } 

       @Override 
       public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, 
         int arg3) { 
        // TODO Auto-generated method stub 

       } 

       @Override 
       public void afterTextChanged(Editable arg0) { 
        // TODO Auto-generated method stub       
       } 
      }); 
     // Loading Albums JSON in Background Thread 
     new LoadAlbums().execute(); 

     // get listview 
    ListView lv = getListView(); 

     /** 
     * Listview item click listener 
     * TrackListActivity will be lauched by passing album id 
     * */ 
     lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> arg0, View view, int arg2, 
        long arg3) { 
       // on selecting a single album 
       // TrackListActivity will be launched to show tracks inside the album 
       Intent i = new Intent(getApplicationContext(), TrackListActivity.class); 

       // send album id to tracklist activity to get list of songs under that album 
       String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString(); 
       i.putExtra("album_id", album_id);    

       startActivity(i); 
      } 
     });  

     imgClick = (ImageView) findViewById(R.id.row_click_imageView1); 
     imgClick.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v){ 
       PopupMenu pop = new PopupMenu(AlbumsActivity.this,imgClick); 
       pop.getMenuInflater().inflate(R.menu.menu,pop.getMenu()); 

       pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ 

        @Override 
        public boolean onMenuItemClick(MenuItem item){ 
         Toast.makeText(AlbumsActivity.this,"text"+item.getTitle(),Toast.LENGTH_SHORT).show(); 
         Intent intent = new Intent(AlbumsActivity.this,NexActivity.class); 
         startActivityForResult(intent, 2); 
         return true; 
        } 
       }); 
       pop.show(); 
      } 
     }); 

    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data){ 
     super.onActivityResult(requestCode, resultCode, data); 

     if(requestCode == 2){ 
      String message = data.getStringExtra("Message"); 
      TextView text = (TextView) findViewById(R.layout.activity_main); 
      text.setText(message); 
     } 
    } 


    /** 
    * Background Async Task to Load all Albums by making http request 
    * */ 
    class LoadAlbums extends AsyncTask<String, String, String> { 

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

     /** 
     * getting Albums JSON 
     * */ 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 

      // getting JSON string from URL 
      String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", 
        params); 

      // Check your log cat for JSON reponse 
      Log.d("Albums JSON: ", "> " + json); 

      try {    
       albums = new JSONArray(json); 

       if (albums != null) { 
        // looping through All albums 
        for (int i = 0; i < albums.length(); i++) { 
         JSONObject c = albums.getJSONObject(i); 

         // Storing each json item values in variable 
         String id = c.getString(TAG_ID); 
         String name = c.getString(TAG_NAME); 
         String songs_count = c.getString(TAG_SONGS_COUNT); 

         // 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_NAME, name); 
         map.put(TAG_SONGS_COUNT, songs_count); 

         // adding HashList to ArrayList 
         albumsList.add(map); 
        } 
       }else{ 
        Log.d("Albums: ", "null"); 
       } 

      } 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 albums 
      pDialog.dismiss(); 
      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        /** 
        * Updating parsed JSON data into ListView 
        * */ 
       /* ListAdapter adapter = new SimpleAdapter(
          AlbumsActivity.this, albumsList, 
          R.layout.list_item_albums, new String[] { TAG_ID, 
            TAG_NAME, TAG_SONGS_COUNT }, new int[] { 
            R.id.album_id, R.id.album_name, R.id.songs_count }); 

        // updating listview 
        setListAdapter(adapter);*/ 

        AlbumsActivity.this.adapter = new SimpleAdapter(AlbumsActivity.this, albumsList, R.layout.list_item_albums, new String[] { TAG_ID, TAG_NAME, TAG_SONGS_COUNT }, new int[] {R.id.album_id, R.id.album_name, R.id.songs_count }); 
        // updating listview 
        setListAdapter(AlbumsActivity.this.adapter); 

       } 
      }); 

     } 

    } 

}

this is the line from 138-144 



    @Override 
     public boolean onMenuItemClick(MenuItem item){ 
      Toast.makeText(AlbumsActivity.this,"text"+item.getTitle(),Toast.LENGTH_SHORT).show(); 
      Intent intent = new Intent(AlbumsActivity.this,NexActivity.class); 
      startActivityForResult(intent, 2); 
      return true; 
     } 

這裏是我的日誌詳細

09-23 21:29:54.161: D/dalvikvm(867): Not late-enabling CheckJNI (already on) 
09-23 21:29:55.721: E/Trace(867): error opening trace file: No such file or directory (2) 
09-23 21:29:57.711: D/dalvikvm(867): GC_CONCURRENT freed 146K, 10% free 2626K/2912K, paused 10ms+16ms, total 138ms 
09-23 21:29:57.882: D/AndroidRuntime(867): Shutting down VM 
09-23 21:29:57.892: W/dalvikvm(867): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 
09-23 21:29:57.992: E/AndroidRuntime(867): FATAL EXCEPTION: main 
09-23 21:29:57.992: E/AndroidRuntime(867): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.projectsoftware/com.projectsoftware.AlbumsActivity}: java.lang.NullPointerException 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.app.ActivityThread.access$600(ActivityThread.java:141) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.os.Handler.dispatchMessage(Handler.java:99) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.os.Looper.loop(Looper.java:137) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.app.ActivityThread.main(ActivityThread.java:5041) 
09-23 21:29:57.992: E/AndroidRuntime(867): at java.lang.reflect.Method.invokeNative(Native Method) 
09-23 21:29:57.992: E/AndroidRuntime(867): at java.lang.reflect.Method.invoke(Method.java:511) 
09-23 21:29:57.992: E/AndroidRuntime(867): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
09-23 21:29:57.992: E/AndroidRuntime(867): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
09-23 21:29:57.992: E/AndroidRuntime(867): at dalvik.system.NativeStart.main(Native Method) 
09-23 21:29:57.992: E/AndroidRuntime(867): Caused by: java.lang.NullPointerException 
09-23 21:29:57.992: E/AndroidRuntime(867): at com.projectsoftware.AlbumsActivity.onCreate(AlbumsActivity.java:138) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.app.Activity.performCreate(Activity.java:5104) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 
09-23 21:29:57.992: E/AndroidRuntime(867): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 
09-23 21:29:57.992: E/AndroidRuntime(867): ... 11 more 
09-23 21:30:06.961: I/Process(867): Sending signal. PID: 867 SIG: 9 
+0

行你能分享你的日誌細節嗎? – santalu 2014-09-23 21:59:16

+0

@santalu - 這是我的日誌細節 – Jonathan 2014-09-23 22:03:55

回答

0

當onPostExecute找你上UiThread運行了。

protected void onPostExecute(String file_url) { 
     pDialog.dismiss(); 
     AlbumsActivity.this.adapter = new SimpleAdapter(AlbumsActivity.this, albumsList, R.layout.list_item_albums, new String[] { TAG_ID, TAG_NAME, TAG_SONGS_COUNT }, new int[] {R.id.album_id, R.id.album_name, R.id.songs_count }); 
     setListAdapter(AlbumsActivity.this.adapter); 

    } 

和找你的TextView定義是錯誤的使用這個

TextView text = (TextView) findViewById(R.id.textView1); 

,而不是

TextView text = (TextView) findViewById(R.layout.activity_main); 
+0

它仍然無法正常工作。它仍然有錯誤 – Jonathan 2014-09-23 22:14:44

+0

它是哪一行? com.projectsoftware.AlbumsActivity.onCreate(AlbumsActivity.java:138) – santalu 2014-09-23 22:16:11

+0

這是公共布爾onMenuItemClick(MenuItem項目)與覆蓋 – Jonathan 2014-09-23 22:25:50

0

@santalu - 這是從138-144

@Override 
         public boolean onMenuItemClick(MenuItem item){ 
          Toast.makeText(AlbumsActivity.this,"text"+item.getTitle(),Toast.LENGTH_SHORT).show(); 
          Intent intent = new Intent(AlbumsActivity.this,NexActivity.class); 
          startActivityForResult(intent, 2); 
          return true; 
         }