SQLite- heading above ListView (source same as ListView source) - android

Im busy with a Bible app, I use an SQLite db from my assets folder to retrieve the data, I use 3 listviews, each in its own activity, it goes like this:
DB column names: Book name, book id, chapter number, chapter id, verse text, verse id
1st activity, user selects a book, Genesis, Exodus, Leviticus, etc... and 2nd activity starts
2nd activity, db gets filtered so user can select chapters under that book...and 3rd activity starts
3rd activity, db gets filtered and shows all the verses under that chapter...
What I want is to put a text view at the top of the 2nd list view and then after the user selected from the 1st listview and the 2nd activity starts to show all chapters, it should show the book name that was selected from the 1st activity. And in the 3rd list view it should show the book name and chapter number that was selected from the previous two activities, I've tried using the intend, but I get errors.
Adapter:
public class customAdapterHoofstuk extends BaseAdapter {
private Context mContext;
private List<defineBybeldbAlles> defineBybeldbAlles;
public customAdapterHoofstuk(Context mContext, List<defineBybeldbAlles> defineBybelDBList) {
this.mContext = mContext;
this.defineBybeldbAlles = defineBybelDBList;
}
#Override
public int getCount() {
return defineBybeldbAlles.size();
}
#Override
public Object getItem(int position) {
return defineBybeldbAlles.get(position);
}
#Override
public long getItemId(int position) {
return (defineBybeldbAlles.get(position).getHoofstuk_id());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.custom_row_hoofstuk, null);
//this works->
TextView hoofstuknommer = (TextView)v.findViewById(R.id.custom_row_hoofstuktext);
hoofstuknommer.setText (defineBybeldbAlles.get(position).getHoofstuk_nommer());
//this works-->
TextView hoofstukid = (TextView)v.findViewById(R.id.hoofstuk_id);
hoofstukid.setText(String.valueOf(defineBybeldbAlles.get(position).getHoofstuk_id()));
//this doesnt work->
TextView boeknaambyhoofstuk = (TextView)v.findViewById(R.id.boeknaambyhoofstuklys);
boeknaambyhoofstuk.setText(defineBybeldbAlles.get(position).get_hebreeus());
return v;
}
}
Activity where it should be shown:
public class BybelActivityHoofstuk extends Activity {
private ListView listviewHoofstuk;
private customAdapterHoofstuk adapter_customAdapterHoofstuk;
private List<defineBybeldbAlles> defineBybeldbAllesList;
private DBHandlerHoofstuk DBHandlerHoofstuk;
ArrayList<HashMap<String, String>> HoofstukList;
//Boek id
String boek_id_na_hoofstuk;
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bybel_hoofstuk);
listviewHoofstuk = (ListView) findViewById(R.id.BybelHoofstukListView);
DBHandlerHoofstuk = new DBHandlerHoofstuk(this);
//Check exists database
File Database = getApplicationContext().getDatabasePath(DBHandlerHoofstuk.DBNAME);
if(false == Database.exists()){
DBHandlerHoofstuk.getReadableDatabase();}
//Get boek id
Intent boekIntent = getIntent();
boek_id_na_hoofstuk = boekIntent.getStringExtra("boek_id");
//hashmap for listview
HoofstukList = new ArrayList<HashMap<String, String>>();
//Get bybel list in db when db exists
defineBybeldbAllesList = DBHandlerHoofstuk.getListHoofstuk(boek_id_na_hoofstuk);
//Init adapter
adapter_customAdapterHoofstuk = new customAdapterHoofstuk(this,defineBybeldbAllesList);
//Set adapter for listview
listviewHoofstuk.setAdapter(adapter_customAdapterHoofstuk);
//Listview item click listener
//BybelActivityVers will be launched by passing hoofstuk_id
listviewHoofstuk.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> arg0, View view, int arg2, long arg3){
//on selecting a hoofstk
//BybelActivityVers will be launched to show verse inside
Intent hoofstukIntent = new Intent(BybelActivityHoofstuk.this,BybelActivityVers.class);
//send hoofstuk_id to VersActivity to get verse under that book
String hoofstuk_id_na_vers = ((TextView)view.findViewById(R.id.hoofstuk_id)).getText().toString();
hoofstukIntent.putExtra("hoofstuk_id", hoofstuk_id_na_vers);
startActivity(hoofstukIntent);
}
});
}
}
DBHandler:
public class DBHandlerHoofstuk extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DBNAME = "pwl14082016-5.db";
public static final String DBLOCATION = "location goes here";
private Context mContext;
private SQLiteDatabase mDatabase;
public static final String COLUMN_BOEK_ID = "boek_id";
public static final String COLUMN_HEBREEUS = "_hebreeus";
public static final String COLUMN_AFRIKAANS = "_afrikaans";
public static final String COLUMN_HOOFSTUK_ID = "hoofstuk_id";
public static final String COLUMN_HOOFSTUK_NOMMER = "hoofstuk_nommer";
public static final String COLUMN_VERS_ID = "vers_id";
public static final String COLUMN_VERS_NOMMER = "vers_nommer";
public static final String COLUMN_VERS_TEXT = "vers_text";
public DBHandlerHoofstuk(Context context) {
super(context, DBNAME, null, DATABASE_VERSION);
this.mContext = context;
}
//Blank want db bestaan klaar
#Override
public void onCreate(SQLiteDatabase db) {
}
//blank want db word ekstern geupgrade
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//maak db oop
public void opendatabase(){
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase !=null && mDatabase.isOpen()) {
return;
}
//verander dalk na 'mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);' as OPEN_READONLY nie werk nie
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
//maak db toe
public void closeDatabase(){
if (mDatabase!=null) {
mDatabase.close();
}
}
public List<defineBybeldbAlles> getListHoofstuk(String boek_id_na_hoofstuk){
defineBybeldbAlles defineBybeldbHoofstuk = null;
List<defineBybeldbAlles> defineBybeldbAllesList = new ArrayList<>();
opendatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM PWLBybel WHERE " + COLUMN_BOEK_ID + " = '" + boek_id_na_hoofstuk + "'GROUP BY hoofstuk_id ORDER BY hoofstuk_id * 1 ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
defineBybeldbHoofstuk = new defineBybeldbAlles(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getInt(3),cursor.getString(4),cursor.getInt(5),cursor.getString(6),cursor.getString(7));
defineBybeldbAllesList.add(defineBybeldbHoofstuk);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return defineBybeldbAllesList;
}
}
XML where it gets displayed:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".defineBybeldbAlles">
<ListView
android:id="#+id/BybelHoofstukListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#ff303030"
android:dividerHeight="1dp"
android:layout_marginTop="21dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Boek naam:"
android:id="#+id/boeknaambyhoofstuklys"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="#000063"
android:textSize="20dp" />
</RelativeLayout>

You can send the string through intent using
String KEY = "PUT_ANY_KEY_HERE";
String VALUE = "BOOK_NAME/CHAPTER_NAME";
Intent i = new Intent(FROM_CLASS.this, TO_CLASS.class);
i.putExtra(KEY,VALUE);
startActivity(i);
and get the string in the 2nd activity using
Intent intent = getIntent();
if(intent!=null)
String VALUE = intent.getExtras().getString(KEY);
now set the VALUE string in your textview. Also you need to put the chapterName textview above your listview or add the VALUE string as your 1st entry in the arraylist that you might be using to populate listview in 2nd and 3rd activity.

If someone might come across this, I wasn't able to pass the book and chapter name to the heading or bar, but I was able to figure out to set a title.
In your manifest under each activity, just put in android:label="title here"
to at least get a heading or title you want.

Related

ListView with CheckBoxes filled with SQL values

I have created SQL database in my Android project and managed to populate ListView with data that I inserted. Next part of the project is to enable CheckBoxes for every item (from SQL database) in my ListView. I have found a way how to do it with String values, but I am not sure how to do it with values from SQL database.
Is it somehow possible to put SQL values into String ? Or I need to use different data values to populate my ListView ?
I am still nooby with SQL in Android, so every advice would be helpfull.
Here is code:
public class ModelBreakfast {
public String name; //This String need to be filled with SQL datas. If it's possible.
public boolean checked;
public ModelBreakfast(String name, boolean checked){
this.name = name;
this.checked = checked;
}
}
Just need to say that I tried to replace public String name; with my ContractClass
public FoodContract.FoodEntry entry; where I defined all String values for my database rows.
(_ID, NAME, etc). (I only saw that way to solve my problem). So, code is now looking like this:
public ModelBreakfast(FoodContract.FoodEntry entry, boolean checked){
this.entry = entry;
this.checked = checked;
}
Next class is CustomAdapter
public class CustomAdapterBreakfast extends ArrayAdapter<ModelBreakfast> {
private ArrayList<ModelBreakfast> dataSet;
Context mContext;
private static class ViewHolder {
TextView txtName;
CheckBox checkBox;
}
public CustomAdapterBreakfast(ArrayList<ModelBreakfast> data, Context context){
super(context, R.layout.activity_breakfast_checkbox, data);
this.dataSet = data;
this.mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_breakfast_checkbox, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.txtName);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
ModelBreakfast item = getItem(position);
viewHolder.txtName.setText(item.name); //Need to replace or modify this part
viewHolder.checkBox.setChecked(item.checked);
return result;
}}
Last part is the MainActivity
public class BreakfastActivity extends AppCompatActivity {
ArrayList<ModelBreakfast> modelBreakfastArrayList;
private CustomAdapterBreakfast customAdapterBreakfast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_breakfast);
ListView listView = (ListView) findViewById(R.id.listBreakfast);
modelBreakfastArrayList = new ArrayList<>();
modelBreakfastArrayList.add(new ModelBreakfast("This string will show in ListView. So I need to somehow replace that String with SQL datas.", false));
customAdapterBreakfast = new CustomAdapterBreakfast(modelBreakfastArrayList, getApplicationContext());
listView.setAdapter(customAdapterBreakfast);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ModelBreakfast modelBreakfast= modelBreakfastArrayList.get(position);
modelBreakfast.checked = !modelBreakfast.checked;
customAdapterBreakfast.notifyDataSetChanged();
}
});
}}
After I replaced public String name; with my ContractClass public FoodContract.FoodEntry entry; I understand that I can't use
modelBreakfastArrayList.add(new ModelBreakfast("This string will show in ListView", false));. But than what do I need to set, so my ListView with CheckBoxes will displaying my SQL database values ?
Should I use ArrayList instead String? And how?
Again as I said before in the last question. Look at the for loops. So within your SQLDB Activity and in the function that is taking the values out of the database, you need to populate an array list that you will call in the MainActivity.
public ArrayList<String> getAirportRegion(String code)
Cursor cursor = db.rawQuery("SELECT "+ AIRPORT_NAME +
" FROM " + AIRPORT_TABLE + " WHERE " + AIRPORT_CODE + " = " + code, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
arrayList.add(cursor.getString(cursor.getColumnIndex(AIRPORT_NAME)));
cursor.moveToNext();
}
}
cursor.close();
return arrayList;
}
Now in the Main Activity get a reference to the database and set it to modelBreakfastArrayList like so
airportArrayList = mdb.getAirportRegion();
Voila it is done
Do you see how I am extracting the data? For the most part, this is the best way to extract lists from the local database. Keep these Activities separate, also I hope you have the Database activity as a singleton, otherwise, you will have multiple databases and that will guzzle up resources. Look below for how I start these database activities.
private DBHelper(Context context) {
super(context, "db", null, DATABASE_VERSION);
}
private static DBHelper INSTANCE;
public static DBHelper getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}

How to hide one view within a layout in an Android ListView backed by database cursor adapter

The goal of the sample application is to display items from a SQLite database, but hide the second text view if the database record has a hide flag active (otherwise display the second text view).
The problem is that it doesn't hide the right things. And as scroll actions cause items to go out of view, and back into view, the second text view gets hidden and and shown on various list items in an erratic manner.
The hidden flag has been set on items 5, 10, 15, 20, and here is how it comes-up:
Scrolling down, various other strange items are hidden, and it doesn't seem to be the same each time. Entry 14, Entry 16, are hidden, for instance.
After Scrolling to the top, we see the first set of items no longer has the same hidden second lines.
Then a whole new set of entries are hidden scrolling back and forth. Not quite random, but inexplicable. You've got to see it to believe it.
The 'real' application that this sample is based-upon (not shown here) actually is attempting to show and hide an ImageView, but the same kind of problem surrounds hiding a TextView, so that's what's I've shown here.
Below is the application. Everything you need should be included (including sample data), should you wish to run this crazy thing. Or you can find it on github: https://github.com/sengsational/LvCaApp
LvCaActivity.java:
public class LvCaActivity extends AppCompatActivity {
private SimpleCursorAdapter dataAdapter;
private DbAdapter dbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lv_ca);
dbHelper = new DbAdapter(this);
dbHelper.open();
dbHelper.deleteAll();
dbHelper.insertSome();
Cursor bCursor = dbHelper.fetchAll(DbAdapter.bColumns);
dataAdapter = new MySimpleCursorAdapter(
this, R.layout.b_item,
bCursor,
DbAdapter.bColumns,
ViewHolder.viewsArray,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(dataAdapter);
}
}
activity_lv_ca.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
b_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip"
android:id="#+id/b_item_layout">
<TextView
android:id="#+id/bName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceListItem"
android:ellipsize="end"
android:singleLine="true"
android:paddingTop="30dp"/>
<TextView
android:id="#+id/bSecondLine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bName"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/bDbItem"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:visibility="gone"
/>
<TextView
android:id="#+id/bHidden"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:visibility="gone"
/>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.company.cpp.lvcaapp"
xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".LvCaActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
DbAdapter.java:
public class DbAdapter {
private static final String TAG = "DbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "adbname";
private static final String SQLITE_TABLE = "atablename";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
public static final String[] bColumns = new String[] {
"_id",
"NAME",
"SECOND_LINE",
"HIDDEN",
};
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"NAME TEXT, " +
"SECOND_LINE, " +
"HIDDEN" +
");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public DbAdapter(Context ctx) {
this.mCtx = ctx;
}
public DbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public Cursor fetchAll(String[] fields) {
Cursor mCursor = mDb.query(SQLITE_TABLE, fields, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertSome() {
AListItem.getInstance();
String sampleData = "[{\"name\":\"Entry 1\",\"second_line\":\"Second Line 1\",\"hidden\":\"F\"},{\"name\":\"Entry 2\",\"second_line\":\"Second Line 2\",\"hidden\":\"F\"},{\"name\":\"Entry 3\",\"second_line\":\"Second Line 3\",\"hidden\":\"F\"},{\"name\":\"Entry 4\",\"second_line\":\"Second Line 4\",\"hidden\":\"F\"},{\"name\":\"EntryH 5\",\"second_line\":\"Second Line 5\",\"hidden\":\"T\"},{\"name\":\"Entry 6\",\"second_line\":\"Second Line 6\",\"hidden\":\"F\"},{\"name\":\"Entry 7\",\"second_line\":\"Second Line 7\",\"hidden\":\"F\"},{\"name\":\"Entry 8\",\"second_line\":\"Second Line 8\",\"hidden\":\"F\"},{\"name\":\"Entry 9\",\"second_line\":\"Second Line 9\",\"hidden\":\"F\"},{\"name\":\"EntryH 10\",\"second_line\":\"Second Line 10\",\"hidden\":\"T\"},{\"name\":\"Entry 11\",\"second_line\":\"Second Line 11\",\"hidden\":\"F\"},{\"name\":\"Entry 12\",\"second_line\":\"Second Line 12\",\"hidden\":\"F\"},{\"name\":\"Entry 13\",\"second_line\":\"Second Line 13\",\"hidden\":\"F\"},{\"name\":\"Entry 14\",\"second_line\":\"Second Line 14\",\"hidden\":\"F\"},{\"name\":\"EntryH 15\",\"second_line\":\"Second Line 15\",\"hidden\":\"T\"},{\"name\":\"Entry 16\",\"second_line\":\"Second Line 16\",\"hidden\":\"F\"},{\"name\":\"Entry 17\",\"second_line\":\"Second Line 17\",\"hidden\":\"F\"},{\"name\":\"Entry 18\",\"second_line\":\"Second Line 18\",\"hidden\":\"F\"},{\"name\":\"Entry 19\",\"second_line\":\"Second Line 19\",\"hidden\":\"F\"},{\"name\":\"EntryH 20\",\"second_line\":\"Second Line 20\",\"hidden\":\"T\"},{\"name\":\"Entry 21\",\"second_line\":\"Second Line 21\",\"hidden\":\"F\"},{\"name\":\"Entry 22\",\"second_line\":\"Second Line 22\",\"hidden\":\"F\"},{\"name\":\"Entry 23\",\"second_line\":\"Second Line 23\",\"hidden\":\"F\"}]";
String[] items = sampleData.split("\\},\\{");
for(String item: items){
AListItem.clear();
AListItem.load(item);
if(AListItem.getName().contains("Hide")){
AListItem.setHidden("T");
}
mDb.insert(SQLITE_TABLE, null, AListItem.getContentValues());
ContentValues values = AListItem.getContentValues();
Log.v(TAG, "values.toString()" + values.toString());
}
}
public boolean deleteAll() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
}
AListItem.java:
public class AListItem {
static String rawInputString;
static String name;
static String second_line;
static String hidden;
static AListItem aListItem;
private AListItem() {
}
public static AListItem getInstance(){
if (aListItem == null) {
aListItem = new AListItem();
}
return aListItem;
}
public static void clear() {
rawInputString = null;
name = null;
second_line = null;
hidden = null;
}
public static ContentValues getContentValues() {
ContentValues values = new ContentValues();
values.put("NAME", name);
values.put("SECOND_LINE", second_line);
values.put("HIDDEN", hidden);
return values;
}
public static void load(String string) {
StringBuffer buf = new StringBuffer(string);
if (buf.substring(0,2).equals("[{")){
buf.delete(0,2);
}
rawInputString = buf.toString();
parse();
}
public static void parse() {
if (rawInputString == null) {
System.out.println("nothing to parse");
return;
}
rawInputString = rawInputString.replaceAll("\"\\:null,", "\"\\:\"null\",");
String[] nvpa = rawInputString.split("\",\"");
for (String nvpString : nvpa) {
String[] nvpItem = nvpString.split("\":\"");
if (nvpItem.length < 2) continue;
String identifier = nvpItem[0].replaceAll("\"", "");
String content = nvpItem[1].replaceAll("\"", "");
switch (identifier) {
case "name":
setName(content);
break;
case "second_line":
setSecond_line(content);
break;
case "hidden":
setHidden(content);
break;
default:
System.out.println("nowhere to put [" + nvpItem[0] + "] " + nvpString + " raw: " + rawInputString);
break;
}
}
}
public static String getName() {
return name;
}
public static void setName(String name) { AListItem.name = name; }
public static void setSecond_line(String second_line) {
AListItem.second_line = second_line;
}
public static String getSecond_line() {
return second_line;
}
public static void setHidden(String hidden) {
AListItem.hidden = hidden;
}
public static String getHidden() {
return hidden;
}
public String toString() {
return getName() + ", " +
getSecond_line() + ", " +
getHidden();
}
}
MySimpleCursorAdapter.java:
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
Context context;
Cursor cursor;
public static final String TAG = "MySimpleCursorAdapter";
public MySimpleCursorAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to, int flags) {
super(context, layout, cursor, from, to, flags);
this.context = context;
this.cursor = cursor;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.v(TAG,"getView() >>>>>>STARTING");
ViewHolder viewHolder;
LayoutInflater inflater = LayoutInflater.from(context);
if (null == convertView || null == convertView.getTag()) {
convertView = inflater.inflate(R.layout.b_item, null);
viewHolder = new ViewHolder(convertView);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
for (int i = 0; i < cursor.getColumnCount(); i++) {
Log.v(TAG, "getView cursor " + i + ": " + cursor.getString(i));
}
String hidden = cursor.getString(ViewHolder.HIDDEN);
if (hidden == null) hidden = "F";
Log.v(TAG,"Hidden State: " + hidden);
switch (hidden) {
case "F":
viewHolder.showSecondLine(); // DRS 20160827 - Added line suggested by aiwiguna
break;
case "T":
Log.v(TAG,">>>>>Hidden was TRUE<<<<<<<: " + cursor.getString(ViewHolder.NAME));
viewHolder.hideSecondLine();
break;
}
convertView.setTag(viewHolder);
View returnView = super.getView(position, convertView, parent);
Log.v(TAG,"getView() ENDING<<<<<<<<<");
return returnView;
}
}
ViewHolder.java:
class ViewHolder {
public static final String TAG = "ViewHolder";
public static final int DB_ITEM = 0;
public static final int NAME = 1;
public static final int SECOND_LINE = 2;
public static final int HIDDEN = 3;
public static final int[] viewsArray = new int[] {
R.id.bDbItem,
R.id.bName,
R.id.bSecondLine,
R.id.bHidden,
};
public static final TextView[] textViewArray = new TextView[viewsArray.length];
public ViewHolder( final View root ) {
Log.v(TAG, "ViewHolder constructor");
for (int i = 0; i < viewsArray.length; i++) {
textViewArray[i] = (TextView) root.findViewById(viewsArray[i]);
Log.v(TAG, " textViewArray[" + i + "]: " + textViewArray[i]);
}
}
public void hideSecondLine() {
textViewArray[SECOND_LINE].setVisibility(View.INVISIBLE);
}
//DRS 20160827 - Addition recommended by aiwiguna
public void showSecondLine() {
textViewArray[SECOND_LINE].setVisibility(View.VISIBLE);
}
}
In order to get this application working,
the ListView must be replaced by a RecyclerView, plus
the SimpleCursorAdapter implementation needs to be replaced by a RecyclerCursorAdapter implementation.
MyRecyclerCursorAdapter, a new class in the example, extends RecyclerView.Adapter:
//DRS 20160829 - Added class. Replaces MySimpleCursorAdapter
public class MyRecyclerCursorAdapter extends RecyclerView.Adapter{
private Cursor cursor;
private Context context;
private static final String TAG = MyRecyclerCursorAdapter.class.getSimpleName();
public MyRecyclerCursorAdapter(Context context, Cursor cursor) {
this.cursor = cursor;
this.context = context;
}
//DRS 20160829 - Critical method within new class
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.v(TAG, "onCreateViewHolder ");
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.b_item, parent, false);
ViewHolder viewHolder = new ViewHolder(itemView, cursor);
return viewHolder;
}
//DRS 20160829 - Critical method within new class
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
cursor.moveToPosition(position);
((ViewHolder)holder).bindFields(cursor);
}
#Override
public int getItemCount() {
return cursor.getCount();
}
}
Note that this class carries a Cursor object, which is the link to the SQLite database entries that will be populating the list.
Also, in order to gain access to the Recycler View, a dependency must be added to build.gradle:
// DRS 20160829 - Added recyclerview
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:recyclerview-v7:24.2.0'
}
b_item.xml required no changes.
activity_lv_ca.xml required a RecyclerView in place of the old ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<!-- DRS 20160829 - Commented ListView, Added RecyclerView
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" / -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
The ViewHolder class now extends Recycler.ViewHolder. Beyond the standard ViewHolder implementation, this customized ViewHolder also has a Cursor which is used to set the text for the TextViews that appear on each row of the list. And this is where the visibility is managed (in a method I called bindFields():
public class ViewHolder extends RecyclerView.ViewHolder {
public static final String TAG = "ViewHolder";
private final Cursor cursor;
public TextView bDbItem;
public TextView bName;
public TextView bSecondLine;
public TextView bHidden;
public static final int DB_ITEM = 0;
public static final int NAME = 1;
public static final int SECOND_LINE = 2;
public static final int HIDDEN = 3;
public ViewHolder(View root, Cursor cursor ) {
super(root);
this.cursor = cursor;
Log.v(TAG, "ViewHolder constructor");
bDbItem = (TextView) itemView.findViewById(R.id.bDbItem);
bName = (TextView) itemView.findViewById(R.id.bName);
bSecondLine = (TextView) itemView.findViewById(R.id.bSecondLine);
bHidden = (TextView) itemView.findViewById(R.id.bHidden);
}
public void bindFields(Cursor cursor) {
bDbItem.setText("" + cursor.getInt(DB_ITEM));
bName.setText(cursor.getString(NAME));
bSecondLine.setText(cursor.getString(SECOND_LINE));
String hidden = cursor.getString(HIDDEN);
bHidden.setText(hidden);
if ("F".equals(hidden)) {
bSecondLine.setVisibility(View.VISIBLE);
} else {
bSecondLine.setVisibility(View.INVISIBLE);
}
}
}
AListItem.java required no changes.
DBAdapter.java required no changes.
The working application may be found on github: RecyclerViewSqlite
In your current solution, you need to "unhide" the second line in a recycled view. The easiest way to do this is in your switch statement. FWIW, you could store your "hidden" flag in your SQLite table as an integer value. This will make the comparison easier, and probably slightly faster.
Another possible solution is to have two different layouts one for the normal situation (hidden is false) and one for the "hidden" situation (hidden is true). In MySimpleCursorAdapter.getView(), an if statement decides which layout to inflate. You would still encounter the same problem when views are recycled: checking to make sure the recycled view is the correct type before reusing it.
switch (hidden) {
case "F":
viewHolder.showSecondLine();
break;
case "T":
Log.v(TAG,">>>>>Hidden was TRUE<<<<<<<: " + cursor.getString(ViewHolder.NAME));
viewHolder.hideSecondLine();
break;
}

Accessing DB from list adapter

I have a listview that contains some data which I got from the web. Now I can make changes in the list item and once I make changes to the item, I am storing the updated value in the db. When i login in next time to the app, I am downloading the content from net and showing it in the listview with the changes that I have done last time. So my approach here is, I am querying the db for each item in the getview method of the list adapter to check for changes. Is it a good practice to do a db query for each item's getview method of the adapter? If not could you please suggest me some alternative. Thanks.
Never, really, never do that.
If you put your data download code in the getView method of the adapter it will make a network call for each row of the list.
Even worst, it will call it anytime that row appears on the screen, not only one time for row.
You should get all your data first, then use the adapter only to draw it.
You can at anytime call the db to check for changes and, if needed, notify the adapter to redraw the list to show the changes.
Hope this helps.
In Android development, any time you want to show a vertical list of items you will want to use a ListView which is populated using an Adapter to a data source. When we want the data for the list to be sourced directly from a SQLite database query we can use a CursorAdapter.
The CursorAdapter fits in between a Cursor (data source from SQLite query) and the ListView (visual representation) and configures two aspects:
Which layout template to inflate for an item
Which fields of the cursor to bind to views in the template
Creating the View Template
When we want to display a series of items into a list using a custom representation of the items, we need to use our own custom XML layout template for each item. We can simply create an XML layout template in res/layout/item_todo.xml representing a particular cursor row:
<?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="horizontal" >
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Defining the Adapter
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return favoriteList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem,null);
}
final TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
nameText.setText("Name : "+favoriteList.get(position).getName());
final TextView ageText = (TextView) convertView.findViewById(R.id.ageText);
ageText.setText("Age : "+favoriteList.get(position).getAge());
final Button edit = (Button) convertView.findViewById(R.id.edit);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.row);
dialog.setTitle("Add Data to Database");
final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText age = (EditText) dialog.findViewById(R.id.age);
Button Add = (Button) dialog.findViewById(R.id.Add);
Add.setText("Add");
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(name.getText().toString() != null && name.getText().toString().length() >0 ){
if(age.getText().toString() != null && age.getText().toString().length() >0 ){
db.updateRow(favoriteList.get(position).getId(), name.getText().toString(), age.getText().toString());
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
dialog.dismiss();
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Age", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Name", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
});
final Button delete = (Button) convertView.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.removeFav(favoriteList.get(position).getId());
notifyDataSetChanged();
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
});
return convertView;
}
}
Create database
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "Test";
//Table Name
private static final String TABLE_TEST = "TestTable";
//Column Name
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Create Table
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_AGE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}
//Insert Value
public void adddata(Context context,String movieId,String songId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, movieId);
values.put(KEY_AGE, songId);
db.insert(TABLE_TEST, null, values);
db.close();
}
//Get Row Count
public int getCount() {
String countQuery = "SELECT * FROM " + TABLE_TEST;
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}
//Delete Query
public void removeFav(int id) {
String countQuery = "DELETE FROM " + TABLE_TEST + " where " + KEY_ID + "= " + id ;
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(countQuery);
}
//Get FavList
public List<FavoriteList> getFavList(){
String selectQuery = "SELECT * FROM " + TABLE_TEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
List<FavoriteList> FavList = new ArrayList<FavoriteList>();
if (cursor.moveToFirst()) {
do {
FavoriteList list = new FavoriteList();
list.setId(Integer.parseInt(cursor.getString(0)));
list.setName(cursor.getString(1));
list.setAge(cursor.getString(2));
FavList.add(list);
} while (cursor.moveToNext());
}
return FavList;
}
}
Enojoys.... :)
It is better to use cursor adapter to bind the list view.You can use Loader to get the list updated even if there is a change in the data base.
onLoadFinished (Loader loader, D data) of the Loader call back would be monitor for changes to the data, and report them to you through new calls. You should not monitor the data yourself.

NullPointerException while passing data through Intent

I wanted to pass a selected menu name in listview to another intent class so that the new submenu is recognized by its parent-menu. So I used the getExtras to get Menu name as belows in KatagoriPengeluaran.java
public void displayListView() {
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("katagori_label"));
Intent ourIntent = new Intent(KatagoriPengeluaran.this, Pengeluaran.class);
ourIntent.putExtra("cek", countryCode);
startActivity(ourIntent);
}
});
And in the new class which is Pengeluaran.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pengeluaran);
dbHelper = new Database(this);
dbHelper.open();
Bundle extras = this.getIntent().getExtras();
String sub = extras.getString("cek");
// dbHelper.deleteAllData();
//dbHelper.insertSomeData();
//Generate ListView from SQLite Database
displayListView(sub);
}
private void displayListView(final String su) {
cursor = dbHelper.fetchPengeluaran(su);
// The desired columns to be bound
allAdapter = new PengeluaranCursorAdapter(this, cursor);
ListView listView = (ListView) findViewById(android.R.id.list);
// Assign adapter to ListView
listView.setAdapter(allAdapter);
Here's my database and the fetch function
public class Database {
// Katagori Pengeluaran
public static final String RIK = "_id";
public static final String RLK = "katagori_label";
public static final String RJK = "katagori_jumlah";
//Pengeluaran
public static final String KEY_RPI = "_id";
public static final String KEY_RLP = "pengeluaran_label";
public static final String KEY_RSK = "pengeluaran_sub";
public static final String KEY_RNP = "nominal";
public static final String KEY_RTP = "tanggal";
public Cursor fetchPengeluaran(String su) {
Cursor mCursor = mDb.query(PENGELUARAN_TABLE, new String[] {KEY_RPI,
KEY_RLP, KEY_RSK, KEY_RNP, KEY_RTP}, "KEY_RLP like " + su
,null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
But while executing it says NullPointerException, Unable to Inisiate Activity Component in the log cat. Please help.
Use this method to getExtra
sub = (String) getIntent().getSerializableExtra("cek");
EDIT
Just you Log.i("Activity", countryCode );
To make your your countrycode is not null
Why do you get a cursor back from your listView? That doesn't look like a good idea to me. You should separate presentation and data.
You can try using the following in the first class instead. Use putString() instead of putExtra()
ourIntent.putString("cek", countryCode);
ListView & Adapter
Other than that I can't find anything I would do different. But like I said in the first place, review having a cursor object in your presentation (listView). Instead have String objects in an ArrayAdapter for example so you can get the String countryCode directly.
More information on listViews here: http://www.vogella.com/articles/AndroidListView/article.html
Debug
Anyway I would double check in debug mode that the object returned from your Cursor is what you expect and most of all not null.

Gridview using custom adapter not displaying all results

firstly a big thanks to all the experts that answer questions and provide insight into challenges. Your work is appreciated.
Now, i'm a newbie and just started using java and Android....but i'm loving it.
secondly,
do forgive my code. its my very first Android app...moving from 13yrs of vb and vba :) and much of it is modified from user questions here on stackoverflow.
Background:
I have a gridview that i want to display contact data (name and number) from the Call Log.
In order to eliminate duplicate numbers, i loop through the cursor and compare phone numbers after of course, sorting the incoming cursor data by CallLog.Calls.NUMBER + " ASC";
i have also created my own class (ContactObj) that holds the name,number and ID of a contact and i pass this class to an ArrayList. eventually i pass this ArrayList to a custom adapter which uses layout inflater to populate the grid.
The issue:
For some reason, the program runs fine but the first ten contacts are repeated over and over. ie. the total contacts on my phone log are 113 unique. however the grid displays only the first 10 over and over for the total 113.
The question:
perhaps the "old hands" at this could point me on where i'm going wrong? i'm guessing is something to do with my implementation of the custom adapter that feeds the gridview.
as i debug, noticed that the value of mChildrenCount is fixed at 11 which is the count of the cells in the gridview in design mode. for some reason whenever this number is reached the gridview starts from 0 again and that repeats the data. it seems i'm missing some setting to allow the grid to go beyond the cells shown during design. ...any ideas anyone?
Thanks.
here's the code for the main activity
public class CallLogActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
final Context myContext = CallLogActivity.this;
final CustomAdapter mAdapter;
ArrayList<ContactObj> arrToPassToGrid = new ArrayList<ContactObj>();
String strNameHolder = "";
String strCurrentName;
String strNumber;
String strCallDate;
String ID;
int i = 0;
int ComparisonResult;
// first find the grid
GridView callLogGrid = (GridView) findViewById(R.id.callLogGrid);
// next get the contents to display
Long yourDateMillis = System.currentTimeMillis()- (30 * 24 * 60 * 60 * ' `1000);
Time yourDate = new Time();
yourDate.set(yourDate);
String[] YourDateMillistring = {String.valueOf(yourDateMillis)};
String formattedDate = yourDate.format("%Y-%m-%d %H:%M:%S");
Time tempDate;
Cursor Tempcursor;
Cursor cursor;
cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI,
new String[]{CallLog.Calls._ID,
CallLog.Calls.CACHED_NAME,
CallLog.Calls.NUMBER,
CallLog.Calls.DATE},
null,
null,
CallLog.Calls.NUMBER + " ASC");
startManagingCursor(cursor);
// intialize nameholder ----will be used to remove duplicate names in
strNameHolder = "";
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
// place contents in variables for easier reading later on;
strCurrentName =
cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
strNumber = cursor.getString(
cursor.getColumnIndex(CallLog.Calls.NUMBER)).trim();
strCallDate = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
ID = cursor.getString(cursor.getColumnIndex(CallLog.Calls._ID));
if (strCurrentName == null && strNumber == null) {
ComparisonResult = 0;
} else {
ComparisonResult = strNameHolder
.compareToIgnoreCase(strNumber);
}
if (ComparisonResult != 0) {
ContactObj contList = new ContactObj();
contList.setIndex(i);
contList.setContactName(strCurrentName);
contList.setContactDialledNumber(strNumber);
contList.setContact_ID(ID);
contList.setCallDate(strCallDate);
arrToPassToGrid.add(i, contList);
i++;
}
strNameHolder = cursor.getString(
cursor.getColumnIndex(CallLog.Calls.NUMBER)).trim();
};
};
try {
// Collections.sort(arrToPassToGrid)
mAdapter = new CustomAdapter(this, arrToPassToGrid);
callLogGrid.setAdapter(mAdapter);
} catch (Exception e)
{
Log.d("Kush", e.getMessage());
e.printStackTrace();
}
}
This code is my custom adapter
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<ContactObj> mItems;
public CustomAdapter(Context c, ArrayList<ContactObj> items)
{
mContext = c;
mItems = items;
}
public int getCount()
{
return mItems.size();
}
public Object getItem(int position)
{
return mItems.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater li = (LayoutInflater)
mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.calllog_layout, null);
Log.d("Kush",String.valueOf(getCount()));
TextView txtContactName = (TextView)v.findViewById(R.id.txtContactName);
txtContactName.setText(mItems.get(position).getContactName() );
TextView txtNumber = (TextView)v.findViewById(R.id.txtContactNumber);
txtNumber.setText(mItems.get(position).getContactDialledNumber());
TextView txtDate = (TextView)v.findViewById(R.id.txtCallDate);
txtNumber.setText(String.valueOf(position) );
}
return v;
}
public static String getDate(long milliSeconds, String dateFormat)
{
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
}
This is the object holding the contact details
public class ContactObj {
private String ContactName;
private String ContactDialledNumber;
private String Contact_ID;
private String CallDate;
public final String getCallDate()
{
return CallDate;
}
public final void setCallDate(String callDate)
{
CallDate = callDate;
}
private int index;
// #return the contactName
public final String getContactName()
{
return ContactName;
}
// #param contactName the contactName to set
public final void setContactName(String contactName)
{
ContactName = contactName;
}
//#return the contactDialledNumber
public final String getContactDialledNumber()
{
return ContactDialledNumber;
}
//#param contactDialledNumber the contactDialledNumber to set
public final void setContactDialledNumber(String contactDialledNumber)
{
ContactDialledNumber = contactDialledNumber;
}
//#return the contact_ID
public final String getContact_ID()
{
return Contact_ID;
}
// #param contact_ID the contact_ID to set
public final void setContact_ID(String contact_ID)
{
Contact_ID = contact_ID;
}
//#return the index
public final int getIndex()
{
return index;
}
//#param index the index to set
public final void setIndex(int index)
{
this.index = index;
}
}
Finally the gridview and layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_horizontal"
android:id="#+id/GridItem"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:scaleType="centerCrop" />
<TextView
android:gravity="center_horizontal"
android:id="#+id/txtContactName"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/contactName"
android:textColor="#000000" />
<TextView
android:gravity="center_horizontal"
android:id="#+id/txtContactNumber"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/contactNumber"
android:textColor="#000000" />
<TextView
android:gravity="center_horizontal"
android:id="#+id/txtCallDate"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/CallDate"
android:textColor="#000000" />
</LinearLayout>
and Gridview
txtContactName.setText(mItems.get(position).getContactName() );
These statements should be outside the if condition. Also check the viewholder usageonce.
Probably you will get the solution.

Categories

Resources