想把GridView添加到ViewPager里面。加载无效

用TabLayout和ViewPager关联后,想把GridView添加到ViewPager里面。报空指针异常。

上面那个问题解决了,没有加载layout所以空对象。
View view = this.getLayoutInflater().inflate(R.layout.grid_view,null);
现在不报错,但是GridView没有加载进来,各位大神帮忙看一下是不是适配器写错了图片说明

04-12 08:39:37.363 25278-25278/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chenshenglei.tablayouttest, PID: 25278
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chenshenglei.tablayouttest/com.example.chenshenglei.tablayouttest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.chenshenglei.tablayouttest.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)

下面贴代码MyGridViewAdapter.java

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import java.util.List;
import java.util.Map;

/**
 * Created by chenshenglei on 18-4-12.
 */

public class MyGridViewAdapter extends SimpleAdapter {

    private Context mContext;

    public MyGridViewAdapter(Context context, List<Map<String, Object>> dataLists, int layout, String[] key, int[] item){
        super(context, dataLists,layout, key, item);
        this.mContext = context;

    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView = super.getView(position, convertView, parent);

        return convertView;
    }

}

代码TabPagerAdapter.java

package com.example.chenshenglei.tablayouttest;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;

import java.security.PublicKey;
import java.util.List;

/**
 * Created by chenshenglei on 18-4-12.
 */

//自定义ViewPager页面适配器
public  class TabPagerAdapter extends PagerAdapter {

    private Context mContext;
    private String[] mTitleArray;
    private List<GridView> mList;

    public TabPagerAdapter (Context context, String[] title) {
        super();
        this.mContext = context;
        this.mTitleArray = title;
    }

    public TabPagerAdapter (Context context, String[] title, List<GridView> array) {
        super();
        this.mContext = context;
        this.mTitleArray = title;
        this.mList = array;
    }

    @Override
    public int getCount() {
        return mTitleArray.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = mList.get(position);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }


    @Override
    public CharSequence getPageTitle(int position) {
        return mTitleArray[position];
    }

}

代码 MainActivity.java
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

private TabLayout mTabLayout;
private ViewPager mViewPager;
private String[] mTitleArray = {"酒标","葡萄品种"};

private GridView gridView1;
private GridView gridView2;

private MyGridViewAdapter myGridViewAdapter;
private List<GridView> mList;

private List<Map<String, Object>> dataList;
private List<Map<String, Object>> dataList2;

private int[] img = {R.mipmap.ic_launcher_round,R.mipmap.ic_launcher};
private int[] img2 = {R.mipmap.ic_launcher_round,R.mipmap.ic_launcher};
private  String[] imgName = {"1","2"};
private  String[] imgName2 = {"3","4"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_weibo_timeline);

    gridView1 = (GridView)findViewById(R.id.grid_test);
    dataList = new ArrayList<Map<String, Object>>();
    myGridViewAdapter = new MyGridViewAdapter(this,
            getData(), R.layout.grid_item,
            new String[] {"img", "txt"},
            new int[] {R.id.img_item,R.id.txt_item});
    gridView1.setAdapter(myGridViewAdapter);

    gridView2 = (GridView)findViewById(R.id.grid_test);
    dataList2 = new ArrayList<Map<String, Object>>();
    myGridViewAdapter = new MyGridViewAdapter(this,
            getData2(), R.layout.grid_item,
            new String[] {"img", "txt"},
            new int[] {R.id.img_item,R.id.txt_item});
    gridView2.setAdapter(myGridViewAdapter);
    mList = new ArrayList<GridView>();
    mList.add(gridView1);
    mList.add(gridView2);


    mViewPager = (ViewPager) findViewById(R.id.view);
    TabPagerAdapter adapter = new TabPagerAdapter(getApplicationContext(),mTitleArray,mList);
    mViewPager.setAdapter(adapter);

    mTabLayout = (TabLayout) findViewById(R.id.tab);
    mTabLayout.setupWithViewPager(mViewPager);

}

private List<Map<String,Object>> getData() {
    for (int i=0; i<img.length; i++) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("img", img[i]);
        map.put("txt", imgName[i]);
        dataList.add(map);
    }

    return dataList;
}

private List<Map<String,Object>> getData2() {
    for (int i=0; i<img.length; i++) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("img", img2[i]);
        map.put("txt", imgName2[i]);
        dataList2.add(map);
    }

    return dataList2;
}

}

grid_view.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">

    <GridView
        android:id="@+id/grid_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numColumns="4"
        android:verticalSpacing="5dp"
        android:horizontalSpacing="5dp"
        android:layout_marginTop="40dp"/>
</LinearLayout>


grid_item.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:orientation="vertical"
    android:gravity="center"
    android:background="#ffffff">

    <ImageView
        android:id="@+id/img_item"
        android:src="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txt_item"
        android:textColor="#000000"
        android:text="文字区域"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>```


activity_weibo_timeline.xml

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


    <android.support.v4.view.ViewPager
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">
    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"/>
    </LinearLayout>

</LinearLayout>


9个回答

建议将 grid_view.xml 替换成下面的
android:id="@+id/grid_test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="4"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
>

代码里:

gridView1 = (GridView) this.getLayoutInflater().inflate(R.layout.grid_view,null);
gridView2 = (GridView) this.getLayoutInflater().inflate(R.layout.grid_view,null);

方法一:

public class MyGridViewAdapter extends SimpleAdapter {

private Context mContext;
private List<Map<String, Object>> mMataLists;

public MyGridViewAdapter(Context context, List<Map<String, Object>> dataLists, int layout, String[] key, int[] item){
    super(context, dataLists,layout, key, item);
    this.mContext = context;
     this.mMataLists = dataLists == null ? new ArrayList<Map<String, Object>>() : dataLists;

}

@Override
public int getCount() {
    return mMataLists.size();
}

// 下面方法代码不变,不粘贴了

}

方法二:
直接使用 SimpleAdapter;

private SimpleAdapter myGridViewAdapter;

myGridViewAdapter = new SimpleAdapter(MainActivity.this,
getData(), R.layout.grid_item,
new String[] {"img", "txt"},
new int[] {R.id.img_item,R.id.txt_item});
gridView1.setAdapter(myGridViewAdapter);

这样可以正常显示了

mynamecsl
mynamecsl 谢谢你,再问一下MainActivity里面,如果继续加载十个gridiew,加载数据的代码能怎么精简
一年多之前 回复

你的GridView的adapter的
@Override
public int getCount() {
return 0;
}

这里返回0在gridView是不会添加控件的,simpleAdapter已经写好了,不需要重写这么多方法。

a568478312
JabamiLight 回复mynamecsl: 兄弟,还有其他问题吗?
一年多之前 回复
mynamecsl
mynamecsl 是的,这边返回的是显示的格子数,不小心设为0,所以不显示了
一年多之前 回复

gridView1 = (GridView)findViewById(R.id.grid_test);
gridView2 = (GridView)findViewById(R.id.grid_test);
同一个控件,在同一个界面怎么能赋值两次?第二次肯定会找不到啊,gridView2报空

mynamecsl
mynamecsl 正确,确实要建两个布局文件,分别加载才可以
一年多之前 回复

最后显示的效果图

看就是 MainActivity的 调用 XXX.setAdapter 这里的XXX控件是null呀 检查一下 控件id是不是正确

mynamecsl
mynamecsl 检查过都是正确的。。。。。帮忙看一下适配器是不是写错了
一年多之前 回复

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference

gridView1.setAdapter(myGridViewAdapter);
这个GridView为空

mynamecsl
mynamecsl 就是不知道为什么空,控件引用,适配器检查过都没错阿
一年多之前 回复

需要修改代码的地方

试试下面的代码

@Override
public Object instantiateItem(ViewGroup container, int position) {
GridView gridview = mList.get(position % mList.size());
container.addView(gridview);
return gridview;
}

mynamecsl
mynamecsl Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference at com.example.chenshenglei.tablayouttest.MainActivity.onCreate(MainActivity.java:46)
一年多之前 回复
mynamecsl
mynamecsl 谢谢,还是报一样的错
一年多之前 回复

适配器重写的方法错了吧

mynamecsl
mynamecsl 应该是的,但是不知道怎么写,第一次写联动的适配器
一年多之前 回复

上面的布局代码没有粘贴完,下面重新发表一下,解决GridView内容不显示的方法还是上面的两个方法

建议将 grid_view.xml 替换成下面的

<?xml version="1.0" encoding="utf-8"?>
android:id="@+id/grid_test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="4"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
>

代码里:

gridView1 = (GridView) this.getLayoutInflater().inflate(R.layout.grid_view,null);
gridView2 = (GridView) this.getLayoutInflater().inflate(R.layout.grid_view,null);

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问