2014-09-24 42 views
0

我有這個代碼albumsactivity擴展listactivity。我試圖做的是啓用點擊imgClick圖像,該圖像被設置爲可點擊列表中的項目以顯示彈出菜單,但是我得到運行時異常nullpointerexception。請幫我解決這個接收運行時錯誤nullPointerException

@SuppressLint({ "NewApi", "ViewHolder" }) 
public class AlbumsActivity extends ListActivity { 
    ConnectionDetector cd; 

    AlertDialogManager alert = new AlertDialogManager(); 

    private ProgressDialog pDialog; 

    JSONParser jsonParser = new JSONParser(); 

    ArrayList<HashMap<String, String>> albumsList; 


    JSONArray albums = null;   
    EditText inputSearch; 
    ImageView imgClick; 
    SimpleAdapter adapter = null;  

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

     cd = new ConnectionDetector(getApplicationContext()); 

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

     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) { 
        AlbumsActivity.this.adapter.getFilter().filter(cs.toString()); 
       } 

       @Override 
       public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, 
         int arg3) { 

       } 

       @Override 
       public void afterTextChanged(Editable arg0) { 
       } 
      }); 
     new LoadAlbums().execute(); 

    ListView lv = getListView(); 

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

     LayoutInflater inflater = getLayoutInflater(); 
     inflater.inflate(R.layout.list_item_albums, null); 
     imgClick = (ImageView)findViewById(R.id.row_click_imageView1); 

     imgClick.setOnClickListener(viewClickListener); 

    } 

    OnClickListener viewClickListener = new OnClickListener(){ 

     @Override 
     public void onClick(View v){ 
      showPopupMenu(v); 
     } 
    }; 

    private void showPopupMenu(View v){ 
     PopupMenu pop = new PopupMenu(AlbumsActivity.this, v); 
     pop.getMenuInflater().inflate(R.menu.menu,pop.getMenu()); 

     pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { 

      @Override 
      public boolean onMenuItemClick(MenuItem arg0) { 
       Toast.makeText(AlbumsActivity.this, arg0.toString(),Toast.LENGTH_LONG).show(); 
       return true; 
      } 
      }); 
     pop.show(); 
    } 




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

     if(requestCode == 2){ 
      if(resultCode == RESULT_OK){ 
      String message = data.getStringExtra("Message"); 
      TextView text = (TextView) findViewById(R.layout.activity_main); 
      text.setText(message); 
      } 
     } 
    } 
    class LoadAlbums extends AsyncTask<String, String, String> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(AlbumsActivity.this); 
      pDialog.setMessage("Loading ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     protected String doInBackground(String... args) { 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 

      String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", 
        params); 

      Log.d("Albums JSON: ", "> " + json); 

      try {    
       albums = new JSONArray(json); 

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

         String id = c.getString(TAG_ID); 
         String name = c.getString(TAG_NAME); 
         String songs_count = c.getString(TAG_SONGS_COUNT); 

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

         map.put(TAG_ID, id); 
         map.put(TAG_NAME, name); 
         map.put(TAG_SONGS_COUNT, songs_count); 

         albumsList.add(map); 
        } 
       }else{ 
        Log.d("Albums: ", "null"); 
       } 

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

      return null; 
     } 


      pDialog.dismiss(); 
      runOnUiThread(new Runnable() { 
       public void run() { 


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

     } 

    } 
} 

的logcat的是:

09-24 04:05:48.381: E/Trace(3812): error opening trace file: No such file or directory (2) 
    09-24 04:05:49.761: D/dalvikvm(3812): GC_CONCURRENT freed 147K, 10% free 2659K/2936K, paused 21ms+7ms, total 157ms 
    09-24 04:05:49.901: D/AndroidRuntime(3812): Shutting down VM 
    09-24 04:05:49.901: W/dalvikvm(3812): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 
    09-24 04:05:49.921: E/AndroidRuntime(3812): FATAL EXCEPTION: main 
    09-24 04:05:49.921: E/AndroidRuntime(3812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.projectsoftware/com.projectsoftware.AlbumsActivity}: java.lang.NullPointerException 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.app.ActivityThread.access$600(ActivityThread.java:141) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.os.Handler.dispatchMessage(Handler.java:99) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.os.Looper.loop(Looper.java:137) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.app.ActivityThread.main(ActivityThread.java:5041) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at java.lang.reflect.Method.invokeNative(Native Method) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at java.lang.reflect.Method.invoke(Method.java:511) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at dalvik.system.NativeStart.main(Native Method) 
    09-24 04:05:49.921: E/AndroidRuntime(3812): Caused by: java.lang.NullPointerException 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at com.projectsoftware.AlbumsActivity.onCreate(AlbumsActivity.java:147) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.app.Activity.performCreate(Activity.java:5104) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 
    09-24 04:05:49.921: E/AndroidRuntime(3812):  ... 11 more 

貨品XML

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#d3d6db" 
     android:orientation="vertical" > 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="fill_parent" 
      android:layout_marginLeft="@dimen/feed_item_margin" 
      android:layout_marginRight="@dimen/feed_item_margin" 
      android:layout_marginTop="@dimen/feed_item_margin" 
      android:background="@drawable/bg_parent_rounded_corner" 
      android:orientation="horizontal" > 

      <ImageView 
       android:id="@+id/flag" 
       android:layout_width="68dp" 
       android:layout_height="68dp" 
       android:layout_marginBottom="5dp" 
       android:layout_marginLeft="5dp" 
       android:layout_marginTop="5dp"/> 

        <TextView 
       android:id="@+id/album_id" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_marginLeft="10dp" 
       android:layout_marginTop="20dp" 
       android:visibility="gone" 
       android:ems="8" 
       android:textSize="16sp" 
       android:textAppearance="?android:attr/textAppearanceLarge" 
       android:textColor="#333333" /> 

      <TextView 
       android:id="@+id/album_name" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_marginLeft="10dp" 
       android:layout_marginTop="20dp" 
       android:text="Some Item" 
       android:lines="1" 
       android:ems="8" 
       android:textSize="16sp" 
       android:textAppearance="?android:attr/textAppearanceLarge" 
       android:textColor="#333333" /> 

      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:orientation="vertical" 
       android:clickable="true" > 

       <ImageView 
        android:id="@+id/row_click_imageView1" 
        android:layout_width="30dp" 
        android:layout_height="35dp" 
        android:layout_gravity="right" 
        android:layout_alignParentRight="true" 
        android:clickable="true" 
        android:focusable="true" 
        android:src="@drawable/popup" /> 


       <TextView 
       android:id="@+id/songs_count" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_marginLeft="10dp" 
       android:layout_marginTop="20dp" 
       android:visibility="gone" 
       android:lines="1" 
       android:ems="8" 
       android:textSize="16sp" 
       android:textAppearance="?android:attr/textAppearanceLarge" 
       android:textColor="#333333" /> 



      </RelativeLayout> 
     </LinearLayout> 

    </LinearLayout> 
+0

您的** imgClick爲NULL **。將其初始化爲'imgClick = findViewById(R.id.ur_image_id);' – 2014-09-24 04:34:49

+0

我該如何更改或修復此問題? – Nb12se 2014-09-24 04:35:47

+0

我已經初始化它爲imgClick =(ImageView)findViewById(R.id.row_click_imageView1);在上面的代碼 – Nb12se 2014-09-24 04:37:42

回答

2

使用此代碼來處理上點擊聽者:

imgClick.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // your code 

      } 
     }); 

onCreate上設置的佈局是activity_albums,但imgClick的ID位於佈局list_item_albums上。

OnCreate膨脹佈局必須是具有上要處理Click

相同的ImageView所以,你可以使用此代碼:

LayoutInflater inflater = getLayoutInflater(); 
View view= inflater.inflate(R.layout.list_item_albums, null); 
imgClick = (ImageView)view.findViewById(R.id.row_click_imageView1); 
+0

onCreate上設置的佈局是activity_albums,但imgClick的ID位於佈局list_item_albums上。 – Nb12se 2014-09-24 04:40:38

+0

你是否在膨脹相同的佈局或不同? – 2014-09-24 04:40:59

+0

im充氣另一個佈局。因爲activity_albums佈局包含列表視圖,而list_item_albums佈局包含我想要在列表視圖中顯示的內容 – Nb12se 2014-09-24 04:43:20

1

試試這個:

imgClick.setOnClickListener(new View.OnClickListener() { 
      @Override 
    public void onClick(View v){ 
     showPopupMenu(v); 
    } 
}); 
+0

這個答案沒有任何區別。 – Piyush 2014-09-24 04:52:58