0

当我想为网格视图设置自定义适配器时,这行代码出现错误

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

1 回答 1

0

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

于 2012-07-26T16:20:25.407 回答