2

I am trying to display data from SQLite database to custom listview but it is not displaying. When I am using simple list view with single data then it's working but not working when I am trying to display on custom listview.

MainActivity.java

package com.example.addressbook;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.AddressBook.MESSAGE";

private ListView lv;
List<Listcollection> collectionlist;
DBHelper mydb;
private Context context = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lv = (ListView) findViewById(R.id.listView1);
    mydb = new DBHelper(this);

    // CustomListAdapter customListAdapter = new
    // CustomListAdapter(MainActivity.this, );
    lv.setAdapter(new ViewAdapter(mydb.listfromdb()));
    // lv.setAdapter(ViewAdapter);
    // adding it to the list view.

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            int id_To_Search = arg2 + 1;
            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", id_To_Search);
            Intent intent = new Intent(getApplicationContext(),
                    com.example.addressbook.Display.class);
            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });
}

public class ViewAdapter extends BaseAdapter {
    LayoutInflater mInflater;
    List<Listcollection> collectionlist;

    public ViewAdapter(List<Listcollection> c) {
        collectionlist = c;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return collectionlist.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater)                     getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.list_item, null);
        }
        Listcollection o = collectionlist.get(position);

        if (o != null) {
            TextView idText = (TextView) convertView
                    .findViewById(R.id.lvid);
            TextView nameText = (TextView) convertView
                    .findViewById(R.id.lvname);

            TextView dateText = (TextView) convertView
                    .findViewById(R.id.lvdate);
            TextView phoneText = (TextView) convertView
                    .findViewById(R.id.lvphone);

            if (idText != null) {
                idText.setText(Integer.toString(o.getId()));
            }
            if (nameText != null) {
                nameText.setText("Name : "
                        + collectionlist.get(position).getName());
            }
            if (dateText != null) {
                dateText.setText("Date: "
                        + collectionlist.get(position).getDate());
            }
            if (phoneText != null) {
                phoneText.setText("Phone: "
                        + collectionlist.get(position).getPhone());
            }
        }

        return convertView;
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mainmenu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
    case R.id.item1:
        Bundle dataBundle = new Bundle();
        dataBundle.putInt("id", 0);
        Intent intent = new Intent(getApplicationContext(),
                com.example.addressbook.Display.class);
        intent.putExtras(dataBundle);
        startActivity(intent);
        return true;
    default:
        return super.onOptionsItemSelected(item);

    }

}

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}}

DBHelper.java

      public class DBHelper extends SQLiteOpenHelper {

  public static final String DATABASE_NAME = "MyDBName.db";
  public static final String CONTACTS_TABLE_NAME = "contacts";
  public static final String CONTACTS_COLUMN_ID = "id";
  public static final String C_NAME = "name";
  public static final String C_TYPE = "type";
  public static final String C_ADDRESS = "address";
  public static final String C_DATE = "date";
  public static final String C_PHONE = "phone";

  private HashMap hp;

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("create table contacts "
            + "(id integer primary key, name text,phone text,type text, address text,date       text)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS contacts");
    onCreate(db);
}

public boolean insertContact(String name, String phone, String type,
        String address, String date) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put("name", name);
    contentValues.put("phone", phone);
    contentValues.put("type", type);
    contentValues.put("address", address);
    contentValues.put("date", date);

    db.insert("contacts", null, contentValues);
    return true;
}

public Cursor getData(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery("select * from contacts where id=" + id + "",
            null);
    return res;
}

public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db,
            CONTACTS_TABLE_NAME);
    return numRows;
}

public boolean updateContact(Integer id, String name, String phone,
        String type, String address, String date) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", name);
    contentValues.put("phone", phone);
    contentValues.put("type", type);
    contentValues.put("address", address);
    contentValues.put("date", date);
    db.update("contacts", contentValues, "id = ? ",
            new String[] { Integer.toString(id) });
    return true;
}

public Integer deleteContact(Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete("contacts", "id = ? ",
            new String[] { Integer.toString(id) });
}


public ArrayList<Listcollection> listfromdb() {
    SQLiteDatabase db = this.getReadableDatabase();

    Listcollection lcollection;
    Listcollection list = new Listcollection();
    ArrayList<Listcollection> results = new ArrayList<Listcollection>();
    Cursor crs = db.rawQuery("select * from contacts", null);

    crs.moveToFirst();

    list.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID)));
    list.setName(crs.getString(crs.getColumnIndex(C_NAME)));
    list.setDate(crs.getString(crs.getColumnIndex(C_DATE)));
    list.setPhone(crs.getString(crs.getColumnIndex(C_PHONE)));

    db.close();
    return results;

}

}

enter code here

Listcollection.java

  public class Listcollection {

// private variables
int id;
String name;
String type;
String address;
String date;
String phone;

// Empty constructor
public Listcollection(Parcel in) {

}

// constructor
public Listcollection(int id, String name, String type, String address,
        String date, String phone) {
    this.id = id;
    this.name = name;
    this.type = type;
    this.address = address;
    this.phone = phone;
    this.date = date;
}

public Listcollection() {
    // TODO Auto-generated constructor stub
}

// getting id
public int getId() {
    return this.id;
}

// setting id
public void setId(int id) {
    this.id = id;
}

// getting name
public String getName() {
    return this.name;
}

// setting name
public void setName(String name) {
    this.name = name;
}

public String getType() {
    return this.type;
}

public void setType(String type) {
    this.type = type;
}

public String getAddress() {
    return this.address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getDate() {
    return this.date;
}

public void setDate(String date) {
    this.date = date;
}

public String getPhone() {
    return this.phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String toString() {
    return "Complain [id=" + id + ", name=" + name + ", type=" + type
            + ", address=" + address + ", date=" + date + ", phone="
            + phone + ",";
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Listcollection other = (Listcollection) obj;
    if (id != other.id)
        return false;
    return true;
}

public int describeContents() {
    return 0;
}

public void writeToParcel(Parcel parcel, int flags) {
    parcel.writeInt(getId());
    parcel.writeString(getName());
    parcel.writeString(getType());
    parcel.writeString(getAddress());
    parcel.writeString(getPhone());
    parcel.writeString(getDate());
}

public static final Parcelable.Creator<Listcollection> CREATOR = new Parcelable.Creator<Listcollection>() {
    public Listcollection createFromParcel(Parcel in) {
        return new Listcollection(in);

    }

    public Listcollection[] newArray(int size) {
        return new Listcollection[size];
    }
};

}

1 Answer 1

1

You're not actually adding the database records to the results collection in listfromdb().

Should be something like:

public ArrayList<Listcollection> listfromdb() {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<Listcollection> results = new ArrayList<Listcollection>();

    Cursor crs = db.rawQuery("select * from contacts", null);
    while (crs.moveToNext()) {
        Listcollection item = new Listcollection();
        item.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID)));
        item.setName(crs.getString(crs.getColumnIndex(C_NAME)));
        item.setDate(crs.getString(crs.getColumnIndex(C_DATE)));
        list.setPhone(crs.getString(crs.getColumnIndex(C_PHONE)));
        results.add(item);
    }

    db.close();
    return results;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@user3809785 Er, look a the code? :) I just checked where you were loading the adapter from. It was clear that there should be a loop there if you were returning a collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.