2012-07-26 131 views
0

当我想设置一个自定义适配器,因为我在这行代码NullPointerException异常的gridview的设置适配器时

gvRecipes.setAdapter(recipeAdapter); 

更多的代码

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    txtHeaderTitle = (TextView) findViewById(R.id.txtHeaderTitle); 
    imgHeader = (ImageView) findViewById(R.id.imgHeader); 
    gvRecipes = (GridView) findViewById(R.id.gvRecipes); 

    ArrayList<Recipe> listOfRecipes = new ArrayList<Recipe>(); 

    String names[] = getResources().getStringArray(R.array.recipe_name); 
    for(int i=0;i<names.length;i++){ 
     Recipe r1 = new Recipe(); 
     r1.id = i; 
     r1.name =getResources().getStringArray(R.array.recipe_name)[i]; 
     r1.image =getResources().getStringArray(R.array.recipe_image)[i]; 
     listOfRecipes.add(r1); 
    } 

    RecipeAdapter recipeAdapter = new RecipeAdapter(getApplicationContext(),R.layout.item_row,listOfRecipes); 

    gvRecipes.setAdapter(recipeAdapter); 
    txtHeaderTitle.setText("بدري و هنية"); 
    setTypeFace(txtHeaderTitle); 


    imgHeader.setImageDrawable(getResources().getDrawable(R.drawable.home)); 
    imgHeader.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      Intent i = new Intent(getApplicationContext(),BHActivity.class); 
      startActivity(i); 

     } 
    }); 
} 

错误是得到了错误网格视图:

java.lang.RuntimeException: Unable to start activity ComponentInfo{mobile.bh/mobile.bh.activities.RecipesListActivity}: java.lang.NullPointerException 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 
at android.app.ActivityThread.access$1500(ActivityThread.java:117) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:130) 
at android.app.ActivityThread.main(ActivityThread.java:3687) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:507) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException 
at mobile.bh.activities.RecipesListActivity.onCreate(RecipesListActivity.java:47) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615) 
+0

'at mobile.bh.activities.RecipesListActivity.onCreate(RecipesListActivity.java:47)'哪一行是47,它在onCreate里面? – 2012-07-26 16:14:03

回答

0

gvRecipes似乎为空。方法findViewById()可能返回null。确保GridView存在于main.xml中,并且它具有正确的ID。

相关问题