Harsh Kumar
Harsh Kumar

Reputation: 376

GridView in android not populating

I'm trying to fill my gridView using a custom adapter but I don't know what I'm doing wrong. It is not giving any error or anything. The gridView is just not populating. At first I tried to make a complex view to insert but. I thought it might be the cause of the problem. But I can't even insert a single textView in it.

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();
}

And the customAdapter class is:-

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;
    }
}

Upvotes: 0

Views: 59

Answers (2)

Yamini Balakrishnan
Yamini Balakrishnan

Reputation: 2411

Change your adapter as follows, to return count as array's length.

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;
}}

Upvotes: 1

Northern Poet
Northern Poet

Reputation: 2045

You returned 0 as number of rows.

Change getCount method to

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

Upvotes: 1

Related Questions