android 中的 GridView 未填充

GridView in android not populating

我正在尝试使用自定义适配器填充我的 gridView,但我不知道我做错了什么。它没有给出任何错误或任何东西。 gridView 只是没有填充。起初我试图制作一个复杂的视图来插入但是。我认为这可能是问题的原因。但是我什至无法在其中插入一个 textView。

public class MainActivity extends AppCompatActivity {

TextView v;
Button submitButton;
EditText e1,e2,e3;
DatabaseHelper dbHelper;
StringBuffer buffer;
Cursor res;
ArrayList<Book> list;
BookAdapter adapter;
GridView grid;


@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buffer = new StringBuffer();
    Toolbar toolbar = findViewById(R.id.toolbar);
    grid = findViewById(R.id.grid);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("  Book Wizard");
    getSupportActionBar().setIcon(getDrawable(R.drawable.ic_action_local_library));
    list = new ArrayList<Book>();
    dbHelper = new DatabaseHelper(this);
    grid.setAdapter(new BookAdapter(MainActivity.this));
    fetchDB();
}

而自定义适配器 class 是:-

public class BookAdapter extends BaseAdapter {

    TextView textView;
    Context context;
    String[] names={"Looking for alaska","The alchemist","Lord of the rings"};

    BookAdapter(Context c){
        context = c;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        textView = new TextView(context);
        textView.setText(names[position]);
        return textView;
    }
}

您返回了 0 作为行数。

getCount方法更改为

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

如下更改您的适配器,以 return 算作数组的长度。

public class BookAdapter extends BaseAdapter {

TextView textView;
Context context;
String[] names = {"Looking for alaska", "The alchemist", "Lord of the rings"};

BookAdapter(Context c) {
    context = c;
}

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

@Override
public Object getItem(int i) {
    return names[i];
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    textView = new TextView(context);
    textView.setText(names[position]);
    return textView;
}}