当我想为网格视图设置自定义适配器时,我在这行代码中遇到错误
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 :(得分:0)
gvRecipes
似乎是空的。方法findViewById()
可能返回null。确保GridView存在于main.xml中,并且它具有正确的ID。