Why getView not getting called? [closed] - android

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have an adapter that extends simplecursoradapter. For some reason I can't seem to see, my getView is not even being called. I have a breakpoint inside getView and it never gets there and the list just shows up empty. Can anyone take a look thru and see what I've done wrong?
package com.example.ok1;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.app.ListActivity;
public class MainActivity extends Activity {
// Button btnCalendar;
//*******************************************8
String[] names = {"Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
"Костя", "Игорь", "Анна", "Денис", "Андрей"};
//Button buttonAddTask;
final String Tag="States";
final String Ten = "Ten";
TextView txtDataTaskToday;
String id_for_listtsk_today;
ListView lvMain_today;
String[] arr_date;
SharedPreferences sPref;
static Cursor c;
private ListView listView = null;
//public static String id_for_listtsk_today;
// static SQLiteDatabase db;
MySqlCursorAdapter adapter = null;
//***********************************************8
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// btnCalendar = (Button) findViewById(R.id.btnActTwo);
// btnCalendar.setOnClickListener(this);
//*********************************************
// переменные для query
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
//*********работа с БД****************
// создаем объект для данных
// txtDataTaskToday = (TextView) findViewById(R.id.txtDataTaskToday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
//final String b = id_for_listtsk_today;
// txtDataTaskToday.setText(id_for_listtsk_today.toString());
Log.d(Tag, "id_for_listtsk_today ="+id_for_listtsk_today );
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(this);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
columns = new String[] {"name"};
selection = "data_id = ?";
selectionArgs = new String[] {id_for_listtsk_today};
//c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
try {
c=dbHelper.getCursor();
} catch (SQLException sqle) {
Log.d(Tag, "неудача");
throw sqle;
}
String[] arr_date = logCursor(c);
//*********работа с БД****************
lvMain_today = (ListView) findViewById(R.id.list);
// lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//this.listView=getl
//listView = MainActivity.this.getlgetListView();
lvMain_today.setItemsCanFocus(false);
lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, arr_date);// R.layout.item, my_list_item
startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME };
Log.d(Tag, "трассировка" );
MainActivity.this.adapter = new MySqlCursorAdapter(
this, R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
//
lvMain_today.setAdapter(MainActivity.this.adapter);
// setListAdapter(MainActivity.this.adapter);
names = arr_date;
c.close();
db.close();
dbHelper.close();
lvMain_today.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SparseBooleanArray chosen = ((ListView) parent).getCheckedItemPositions();
for (int i = 0; i < chosen.size(); i++) {
int key = chosen.keyAt(i);
if (chosen.get(key))
Log.d(Tag, "выделены ====="+names[key]);
Log.d(Tag, "itemClick: position = " + position + ", id = "
+ id);}
//****************nen пробная фигня**************
// String[] columns = null;
// String selection = null;
// String[] selectionArgs = null;
// String groupBy = null;
// String having = null;
// String orderBy = null;
// columns = new String[] {"name"};
// selection = "data_id = ?";
// selectionArgs = new String[] {id_for_listtsk_today};//id_for_listtsk_today
// Cursor c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
// String[] arr = logCursor(c);
//**************************************************
// String s=test();
}
});
// lvMain_today.setOnItemSelectedListener(new OnItemSelectedListener() {
// public void onItemSelected(AdapterView<?> parent, View view,
// int position, long id) {
// Log.d(Tag, "Было выделение позиции меню!!!!position = " + position + ", id = "
// + id);
// }
//
// public void onNothingSelected(AdapterView<?> parent) {
// Log.d(Tag, "itemSelect: nothing");
// }
// });
}
private String[] logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
String[] arr_date = new String[c.getCount()];//String[] arr_date = new String[] {};
Log.d(Tag,"мы в курсоре");
if (c!=null) {
if (c.moveToFirst()) {
// Log.d(Tag,"мы в курсоре1");
String str;
int i=-1;
do {
// Log.d(Tag,"мы в курсоре2");
str="";
i=i+1;
for (String cn: c.getColumnNames()) {
str = str.concat(c.getString(c.getColumnIndex(cn)));
}
Log.d(Tag, "++++"+str);
arr_date[i]=String.valueOf(str);
} while (c.moveToNext());
}
}
return arr_date;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "календарь");
menu.add(0, 2, 0, "Убрать выполненные");
menu.add(0, 3, 3, "Уйти");
// menu.add(1, 4, 1, "copy");
// menu.add(1, 5, 2, "paste");
// menu.add(1, 6, 4, "exit");
return super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.main, menu);
//return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
// Выведем в TextView информацию о нажатом пункте меню
// txtDataTaskToday.setText("Item Menu");
// txtDataTaskToday.setText(item.getGroupId());
//// txtDataTaskToday.setText("\r\n itemId: " + String.valueOf(item.getItemId()));
// txtDataTaskToday.setText("\r\n order: " + String.valueOf(item.getOrder()));
// txtDataTaskToday.setText("\r\n title: " + item.getTitle());
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, ToDoCalendarActivity.class);
startActivity(intent);
break;
case 2:
SparseBooleanArray sbArray = lvMain_today.getCheckedItemPositions();
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key))
Log.d(Tag, "выделены "+names[key]);
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString(Ten, "1");
ed.commit();
Log.d(Tag, "ставим константу для скрытия");
}
break;
case 3:
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(Ten, "");
Log.d(Tag, "ten= "+ savedText);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// switch (v.getId()) {
// case R.id.btnActTwo:
//
// Intent intent = new Intent(this, ToDoCalendarActivity.class);
// startActivity(intent);
// break;
// }
// }
}
MySqlCursorAdapter
package com.example.ok1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener {
final String Tag="States";
private Context context;
private DBHelper dbHelper;
private Cursor currentCursor;
public MySqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, DBHelper dbHelper) {
super(context, layout, c, from, to);
Log.d(Tag, "трассировка1" );
this.currentCursor = c;
this.context = context;
this.dbHelper = dbHelper;
Log.d(Tag, "MySqlCursorAdapter()");
Integer b = c.getCount();
Log.d(Tag, "b="+b);
}
public View getView(int pos, View inView, ViewGroup parent) {
Log.d(Tag, "getView() + posss=" + pos);
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.my_list_item, null);
}
this.currentCursor.moveToPosition(pos);
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
cBox.setTag(Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_ID))));
Log.d(Tag, "tag="+cBox.getTag().toString());
if (this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS)) != null
&& Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS))) != 0) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
cBox.setOnClickListener(this);
TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_NAME)));
return (v);
}
public void ClearSelections() {
Log.d(Tag, "ClearSelections()");
//this.dbHelper.clearSelections();
//this.currentCursor.requery();
}
#Override
public void onClick(View v) {
Log.d(Tag, "onClick");
CheckBox cBox = (CheckBox) v;
Integer _id = (Integer) cBox.getTag();
Log.d(Tag, "Integer _id="+_id.toString());
ContentValues values = new ContentValues();
values.put(" selected", cBox.isChecked() ? 1 : 0);
//this.dbHelper.dbSqlite.update(SqlHelper.TABLE_NAME, values, "_id=?",
// new String[] { Integer.toString(_id) });
}
}
DBHelper
package com.example.ok1;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
final String Tag="States";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATA = "data_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_STATUS = "status";
public static final String TABLE_NAME = "mytable";
public SQLiteDatabase dbSqlite;
public DBHelper(Context context) {
// конструктор суперкласса
super(context, "myDB", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(Tag, "--- onCreate database ---");
// создаем таблицу с полями
db.execSQL("create table mytable ("
+ "_id integer primary key autoincrement,"
+ "data_id text,"
+ "name text,"
+ "task text,"
+ "status integer"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getCursor() {
Log.d(Tag, "getCursor() получили курсор с базы");
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
// SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// queryBuilder.setTables(TABLE_NAME);
// String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
// COLUMN_DATA, COLUMN_STATUS };
// Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
// null, null, null, "title ASC");
// Log.d(Tag, "getCursor() получили курсор с базы конец");
final SQLiteDatabase db = this.getWritableDatabase();
columns = new String[] { COLUMN_ID, COLUMN_DATA, COLUMN_NAME, COLUMN_STATUS };
// selection = "data_id = ?";
// selectionArgs = new String[] {id_for_listtsk_today};
Cursor c = db.query("mytable", columns, null, null, null, null, null);
return c;
}
}
ActivityMain.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#81BEF7" android:scrollbars="vertical">
<TableLayout android:id="#+id/TableLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" >
<TableRow>
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</TableRow>
</TableLayout>
</LinearLayout>
my_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/bcheck"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:focusable="false">
</CheckBox>
<TextView
android:id="#+id/txtTitle"
android:layout_width="138dp"
android:layout_height="?android:attr/listPreferredItemHeight"
android:focusable="false"
android:gravity="left|center_vertical"
android:text="Test" >
</TextView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right|center_vertical"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:clickable="true" >
</ImageButton>
</LinearLayout>
</LinearLayout>

I removed
c.close();
db.close();
and now its working fine.

Related

SimpleCursorAdapter not populating a ListView

I'm trying to populate a ListView from an SQLiteDatabase using a SimpleCursorAdapter. There are no errors, and I know the database has data in it, but nothing shows up on the ListView.
Can anyone help find what is going wrong?
1) Layout for the ListView(activity_profilelist.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_profilelist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation= "vertical"
android:paddingBottom="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
tools:context="com.corvus.corvusenterprises.digimonapp.Profilelist">
<TextView
android:id="#+id/textView_names"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.1"
android:gravity="center"
android:textAppearance="#android:style/TextAppearance.Theme"
android:textSize="25sp"
android:text="Digimon"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation= "horizontal">
<ListView
android:id="#+id/ListView_names"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="100" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_weight="0.1">
<Button
android:id="#+id/button_update"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="Update List">
</Button>
</LinearLayout>
</LinearLayout>
2)Layout for the individual entries in the ListView(activity_list_example.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/Digimon_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28sp" />
<TextView
android:id="#+id/Digimon_favourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28sp" />
</LinearLayout>
3)Java for the ListView(ProfileList.java)
package com.corvus.corvusenterprises.digimonapp;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import static com.corvus.corvusenterprises.digimonapp.R.id.button_update;
public class Profilelist extends Digimon2 {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profilelist);
DBHelper dbHelper = DBHelper.getInstance(MyApp.getContext());
Cursor cursor = dbHelper.defaultMainMenu();
String[]columns = new String[] {"name","favourite","path"};
ListView theListView = (ListView) findViewById(R.id.listView_names);
int[]to = new int[] {R.id.Digimon_name,R.id.Digimon_favourites};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.activity_list_example,cursor,columns,to,0);
theListView.setAdapter(adapter);
}
}
4)Java for the Database Helper(DBHelper.java)
package com.corvus.corvusenterprises.digimonapp;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import org.jsoup.Jsoup;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import static android.graphics.Bitmap.Config.ARGB_8888;
import static android.graphics.Bitmap.createBitmap;
/**
* Created by Jack on 28-Mar-17.
*/
public class DBHelper extends SQLiteOpenHelper {
private static final int version = 1;
private static final String DATABASE_NAME = "DigimonDatabase.db";
private static final String DIGIMON_TABLE_NAME = "Digimon";
private static final String DIGIMON_COLUMN_NAME = "name";
private static final String DIGIMON_COLUMN_DUB_NAME = "dub_name";
private static final String DIGIMON_COLUMN_LEVEL = "level";
private static final String DIGIMON_COLUMN_ATTRIBUTE = "attribute";
private static final String DIGIMON_COLUMN_DESCRIPTION = "description";
private static final String DIGIMON_COLUMN_FAVOURITE = "favourite";
private static final String EVOLUTIONS_TABLE_NAME = "Evolutions";
private static final String EVOLUTIONS_COLUMN_FROM = "\"from\"";
private static final String EVOLUTIONS_COLUMN_TO = "\"to\"";
private static final String EVOLUTIONS_COLUMN_CONDITIONS = "conditions";
private static final String ATTACKS_TABLE_NAME = "Attacks";
private static final String ATTACKS_COLUMN_NAME = "name";
private static final String ATTACKS_COLUMN_DUB_NAME = "dub_name";
private static final String ATTACKS_COLUMN_DIGIMON = "digimon";
private static final String ATTACKS_COLUMN_DESCRIPTION = "description";
private static final String PICTURES_TABLE_NAME = "Pictures";
private static final String PICTURES_COLUMN_DIGIMON = "digimon";
private static final String PICTURES_COLUMN_PATH = "path";
private static String[]digimonArray = {/*19MB worth of Digimon names removed for length constraints.*/};
private static boolean[]presentDigimon = new boolean[digimonArray.length];
private static DBHelper instance;
private DBHelper(Context context)
{
super(context, DATABASE_NAME, null, version);
}
public static DBHelper getInstance(Context ctx)
{
if(instance == null)
instance = new DBHelper(ctx);
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
//Create and define the tables
db.execSQL("CREATE TABLE "+DIGIMON_TABLE_NAME+" ("+DIGIMON_COLUMN_NAME+" TEXT PRIMARY KEY, "+DIGIMON_COLUMN_DUB_NAME+" TEXT NULL, "+DIGIMON_COLUMN_LEVEL+" TEXT NULL, "+DIGIMON_COLUMN_ATTRIBUTE+" TEXT NULL, "+DIGIMON_COLUMN_DESCRIPTION+" TEXT NULL, "+DIGIMON_COLUMN_FAVOURITE+" TEXT DEFAULT 'FALSE')");
db.execSQL("CREATE TABLE "+EVOLUTIONS_TABLE_NAME+" ("+EVOLUTIONS_COLUMN_FROM+" TEXT, "+EVOLUTIONS_COLUMN_TO+" TEXT, "+EVOLUTIONS_COLUMN_CONDITIONS+" TEXT NULL, primary key("+EVOLUTIONS_COLUMN_FROM+", "+EVOLUTIONS_COLUMN_TO+"))");
db.execSQL("CREATE TABLE "+ATTACKS_TABLE_NAME+" ("+ATTACKS_COLUMN_NAME+" TEXT, "+ATTACKS_COLUMN_DUB_NAME+" TEXT NULL, "+ATTACKS_COLUMN_DIGIMON+" TEXT, "+ATTACKS_COLUMN_DESCRIPTION+" TEXT NULL, primary key("+ATTACKS_COLUMN_NAME+", "+ATTACKS_COLUMN_DIGIMON+"))");
db.execSQL("CREATE TABLE "+PICTURES_TABLE_NAME+" ("+PICTURES_COLUMN_DIGIMON+" TEXT PRIMARY KEY, "+PICTURES_COLUMN_PATH+" TEXT)");
//Fill in some default Digimon
insertDigimon("Guilmon", "Guilmon", "Child/Rookie", "Virus", "Dinosaur", "TRUE");
insertDigimon("Growmon", "Growlmon", "Adult/Champion", "Virus", "Bigger Dinosaur", "FALSE");
insertDigimon("Terriermon", "terriermon", "Child/Rookie", "Vaccine", "Dogbunny", "FALSE");
insertDigimon("Galgomon", "Gargomon", "Adult/Champion", "Vaccine", "Gunbunny", "FALSE");
insertDigimon("Kyubimon", "Kyubimon", "Adult/Champion", "Data", "9-Tailed Fox", "FALSE");
insertDigimon("Taomon", "Taomon", "Perfect/Ultimate", "Data", "Kitsune Miko", "FALSE");
insertDigimon("Impmon", "Impmon", "Child/Rookie", "Virus", "Kid in a purple onesie", "FALSE");
insertDigimon("Beelzebumon", "Beelzemon", "Ultimate/Mega", "Virus", "Demon Lord of Gluttony", "FALSE");
presentDigimon[460] = true; presentDigimon[454] = true;
presentDigimon[1019] = true; presentDigimon[374] = true;
presentDigimon[572] = true; presentDigimon[1013] = true;
presentDigimon[507] = true; presentDigimon[100] = true;
insertEvolution("Guilmon", "Growmon");
insertEvolution("Terriermon", "Galgomon");
insertEvolution("Kyubimon", "Taomon");
insertEvolution("Impmon", "Beelzebumon", "(Warp Evolution)");
insertAttack("Fireball", "Pyro Sphere", "Guilmon", "Explosive Fireball");
insertAttack("Rock Breaker", "Rock Breaker", "Guilmon", "Claw Swipe");
insertAttack("Exhaust Flame", "Pyro Blaster", "Growmon", "Fire Laser");
insertAttack("Plasma Blade", "Dragon Slash", "Growmon", "Forearm Blades");
insertAttack("Blazing Fire", "Bunny Blast", "Terriermon", "Energy Blast");
insertAttack("Petit Twister", "Terrier Tornado", "Terriermon", "Throws Tornado");
insertAttack("Gatling Arm", "Gargo Laser", "Galgomon", "Fires Guns");
insertAttack("Dum Dum Upper", "Bunny Pummel", "Galgomon", "Fires Guns While Punching");
insertAttack("Koenryu", "Dragon Wheel", "Kyubimon", "Fire Dragon");
insertAttack("Onibidama", "Fox-Tail Inferno", "Kyubimon", "Fireballs from the tails");
insertAttack("Bonhitsusen", "Talisman of Light", "Taomon", "Energy Seal Laser");
insertAttack("Oṃ", "Talisman Spell", "Taomon", "Makes a dome shield");
insertAttack("Night of Fire", "Badaboom", "Impmon", "Mini-Fireballs");
insertAttack("Pillar of Fire", "", "Impmon", "Wall of Flames");
insertAttack("Double Impact", "Double Impact", "Beelzebumon", "Fires two bullets");
insertAttack("Darkness Claw", "", "Beelzebumon", "Kills Leomon");
insertPicture("Guilmon","R.mipmap.guilmon.jpg");
insertPicture("Growmon","R.mipmap.growmon.jpg");
insertPicture("Terriermon","R.mipmap.terriermon.jpg");
insertPicture("Galgomon","R.mipmap.galgomon.jpg");
insertPicture("Kyubimon","R.mipmap.kyubimon.jpg");
insertPicture("Taomon","R.mipmap.taomon.jpg");
insertPicture("Impmon","R.mipmap.impmon.jpg");
insertPicture("Beelzebumon","R.mipmap.beelzebumon.jpg");
//Populate Tables
new Downloader().start();
}
private class Downloader extends Thread
{
public void run()
{
int digimonToGetAtOnce = 20;
HttpURLConnection connection;
URL url;
String wikimonAddress, downloadResult;
BufferedInputStream in;
for(int i=0;i<digimonToGetAtOnce;)
{
int rand = (int)(Math.random()*digimonArray.length);
if(!presentDigimon[rand])
{
wikimonAddress = "https://wikimon.net/api.php?action=parse&format=json&page=" + digimonArray[rand] + "&prop=text";
try {
url = new URL(wikimonAddress);
connection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(connection.getInputStream());
downloadResult = readStream(in);
connection.disconnect();
i++;
presentDigimon[rand] = true;
sortInput(downloadResult);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private String readStream(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(is),1000);
for (String line = r.readLine(); line != null; line =r.readLine()){
sb.append(line);
}
is.close();
return sb.toString();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldver, int newVer)
{
db.execSQL("DROP TABLE IF EXISTS "+DIGIMON_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS "+ATTACKS_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS "+EVOLUTIONS_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS "+PICTURES_TABLE_NAME);
onCreate(db);
}
public void insertDigimon(String name, String dub_name, String level, String attribute, String description, String favourite)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DIGIMON_COLUMN_NAME,name);
values.put(DIGIMON_COLUMN_DUB_NAME,dub_name);
values.put(DIGIMON_COLUMN_LEVEL,level);
values.put(DIGIMON_COLUMN_ATTRIBUTE,attribute);
values.put(DIGIMON_COLUMN_DESCRIPTION,description);
values.put(DIGIMON_COLUMN_FAVOURITE, favourite);
db.insert(DIGIMON_TABLE_NAME, null, values);
db.close();
}
public void insertAttack(String name, String dub_name, String digimon, String description)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ATTACKS_COLUMN_NAME, name);
values.put(ATTACKS_COLUMN_DUB_NAME,dub_name);
values.put(ATTACKS_COLUMN_DIGIMON, digimon);
values.put(ATTACKS_COLUMN_DESCRIPTION, description);
db.insert(ATTACKS_TABLE_NAME, null, values);
db.close();
}
public void insertEvolution(String from, String to, String conditions)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(EVOLUTIONS_COLUMN_TO,to);
values.put(EVOLUTIONS_COLUMN_FROM,from);
values.put(EVOLUTIONS_COLUMN_CONDITIONS,conditions);
db.insert(EVOLUTIONS_TABLE_NAME, null, values);
db.close();
}
public void insertEvolution(String from, String to)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(EVOLUTIONS_COLUMN_TO,to);
values.put(EVOLUTIONS_COLUMN_FROM,from);
db.insert(EVOLUTIONS_TABLE_NAME, null, values);
db.close();
}
public void insertPicture(String digimon, String path)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PICTURES_COLUMN_DIGIMON,digimon);
values.put(PICTURES_COLUMN_PATH,path);
db.insert(PICTURES_TABLE_NAME, null, values);
db.close();
}
public Cursor defaultMainMenu()
{
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT "+DIGIMON_TABLE_NAME+".ROWID AS _id, "+DIGIMON_COLUMN_NAME+", "+DIGIMON_COLUMN_FAVOURITE+" FROM "+DIGIMON_TABLE_NAME;
Cursor cursor = db.rawQuery(query,null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor searchMenuQuery(String search)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, "+DIGIMON_COLUMN_NAME+", "+DIGIMON_COLUMN_FAVOURITE+", "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_PATH+" FROM "+DIGIMON_TABLE_NAME+" JOIN "+PICTURES_TABLE_NAME+" ON "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_DIGIMON+"="+DIGIMON_TABLE_NAME+"."+DIGIMON_COLUMN_NAME +" WHERE "+DIGIMON_COLUMN_NAME+" LIKE '%"+search+"%' UNION SELECT ROWID AS _id, "+DIGIMON_COLUMN_NAME+", "+DIGIMON_COLUMN_FAVOURITE+", "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_DIGIMON+" FROM "+DIGIMON_TABLE_NAME+" JOIN "+PICTURES_TABLE_NAME+" ON "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_DIGIMON+"="+DIGIMON_TABLE_NAME+"."+DIGIMON_COLUMN_NAME +" WHERE "+DIGIMON_COLUMN_DUB_NAME+" LIKE '%"+search+"%'";
Cursor cursor = db.rawQuery(query,null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor favouritesMenuQuery()
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, "+DIGIMON_COLUMN_NAME+", "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_PATH+" FROM "+DIGIMON_TABLE_NAME+" JOIN "+PICTURES_TABLE_NAME+" ON "+PICTURES_TABLE_NAME+"."+PICTURES_COLUMN_DIGIMON+"="+DIGIMON_TABLE_NAME+"."+DIGIMON_COLUMN_NAME +" WHERE "+DIGIMON_COLUMN_FAVOURITE+" = 'TRUE'";
Cursor cursor = db.rawQuery(query,null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonProfileQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, * FROM "+DIGIMON_TABLE_NAME+" WHERE "+DIGIMON_COLUMN_NAME+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonAttacksQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, * FROM "+ATTACKS_TABLE_NAME+" WHERE "+ATTACKS_COLUMN_DIGIMON+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonEvolutionFromQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, * FROM "+EVOLUTIONS_TABLE_NAME+" WHERE "+EVOLUTIONS_COLUMN_FROM+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonEvolutionToQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, * FROM "+EVOLUTIONS_TABLE_NAME+" WHERE "+EVOLUTIONS_COLUMN_TO+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public Cursor digimonPictureQuery(String name)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT ROWID AS _id, "+PICTURES_COLUMN_PATH+" FROM "+PICTURES_TABLE_NAME+" WHERE "+PICTURES_COLUMN_DIGIMON+" = '"+name+"'";
Cursor cursor = db.rawQuery(query, null);
int dummy = cursor.getCount();
db.close();
return cursor;
}
public void sortInput(String input)
{
int index1, index2;
String name, dubName, level, attribute, description, imageUrl, imagePath;
String attackName="", attackDubName="", attackDescription="No description given.";
String from = "", to = "", conditions = "";
ArrayList<String[]> attacks = new ArrayList<String[]>();
ArrayList<String[]> evolvesFrom = new ArrayList<String[]>();
ArrayList<String[]> evolvesTo = new ArrayList<String[]>();
boolean tableEnded = false, rowEnded = false;
index2 = input.indexOf("\",\n\"pageid\":");
name = input.substring(20,index2);
index1 = input.indexOf("Japanese</b></span></span><br />")+32;
index2 = input.indexOf("\\n</td></tr>\\n<tr>\\n<td style=\\\"border-top:1px solid gray\\\" align=\\\"center\\\"><span class=\\\"plainlinks\\\">",index1);
description = input.substring(index1, index2);
description = Jsoup.parse(description).text();
if(input.contains("<b>Dub:</b>\\n</td>\\n<td>\\n</td>\\n<td>\\n</td>\\n<td valign=\\\"center\\\"><i>"))
{
index1 = input.indexOf("<b>Dub:</b>\\n</td>\\n<td>\\n</td>\\n<td>\\n</td>\\n<td valign=\\\"center\\\"><i>")+72;
index2 = input.indexOf("</i>",index1);
dubName = input.substring(index1,index2);
}
else dubName = name;
index1 = input.indexOf("Level</font></a></b>\\n</td>\\n<td style=\\\"background:#252525;width:175px;border-bottom:1px solid #808080\\\"><a href=\\\"/")+118;
index2 = input.indexOf("\\\" title=\\\"",index1);
level = input.substring(index1,index2);
index1 = input.indexOf("Attribute</font></a></b>\\n</td>\\n<td style=\\\"background:#252525;width:175px;border-bottom:1px solid #808080\\\"><a href=\\\"/Category:")+136;
index2 = input.indexOf("\\\" title=\\\"",index1);
attribute = input.substring(index1,index2);
index2 = input.indexOf("width=\\\"320\\\" height=\\\"320\\\"");
index1 = input.lastIndexOf("src=\\\"",index2);
imageUrl = "https://wikimon.net"+input.substring(index1,index2);
index1 = input.indexOf("<i><b>")+6;
index2 = input.indexOf("</b></i>",index1);
for(int i = 0;!tableEnded;i++)
{
//name, dub_name, digimon, description
attackName = input.substring(index1,index2);
index1 = input.indexOf("<i>",index2)+3;
index2 = input.indexOf("</i>",index1);
attackDubName = input.substring(index1,index2);
index1 = input.indexOf("</td>",index2);
index1 = input.indexOf("</td>",index1);
index1 = input.indexOf("</td>",index1);
index1 = input.indexOf("<i>",index1)+3;
index2 = input.indexOf("</i>",index1);
if(input.substring(index1,index2).compareTo("<br />")!=0)
attackDubName = input.substring(index1,index2);
else if(attackDubName.compareTo("<br />")==0)
attackDubName = attackName;
index1 = input.indexOf("<td style",index2);
index1 = input.indexOf("\\\">",index1)+3;
index2 = input.indexOf("\\n</td></tr>");
attackDescription = input.substring(index1,index2);
attacks.add(i,new String[]{attackName,attackDubName,name,attackDescription});
if(input.substring(index2,index2+64).contains("</table>"))
{
tableEnded = true;
}
}
tableEnded = false;
for(int i = 0;!tableEnded;i++)
{
index1 = input.indexOf("<li>",index2);
index1 = input.indexOf("\\\"/",index1)+3;
index2 = input.indexOf("\\\" title",index1);
from = input.substring(index1,index2);
index1 = input.indexOf("</a>",index2);
index2 = input.indexOf("</li>",index1);
if(Jsoup.parse(input.substring(index1,index2)).text().contains("("))
{
conditions = Jsoup.parse(input.substring(index1,index2)).text();
evolvesFrom.add(new String[]{from,name,conditions});
}
else evolvesFrom.add(new String[]{from,name});
if(input.substring(index1,index1+9).contains("</ul>"))
{
tableEnded = true;
}
}
tableEnded = false;
for(int i = 0;!tableEnded;i++)
{
index1 = input.indexOf("<li>",index2);
index1 = input.indexOf("\\\"/",index1)+3;
index2 = input.indexOf("\\\" title",index1);
to = input.substring(index1,index2);
index1 = input.indexOf("</a>",index2);
index2 = input.indexOf("</li>",index1);
if(Jsoup.parse(input.substring(index1,index2)).text().contains("("))
{
conditions = Jsoup.parse(input.substring(index1,index2)).text();
evolvesTo.add(new String[]{name,to,conditions});
}
else evolvesTo.add(new String[]{name,to});
if(input.substring(index1,index1+9).contains("</ul>"))
{
tableEnded = true;
}
}
insertDigimon(name,dubName,level,attribute,description,"FALSE");
for(int i=0;i<attacks.size();i++)
{
insertAttack(attackName,attackDubName,name,attackDescription);
}
for(int i=0;i<evolvesFrom.size();i++)
{
if(evolvesFrom.get(i).length==3)
insertEvolution(evolvesFrom.get(1)[0],name,evolvesFrom.get(1)[2]);
else
insertEvolution(evolvesFrom.get(1)[0],name);
}
for(int i=0;i<evolvesTo.size();i++)
{
if(evolvesTo.get(i).length==3)
insertEvolution(name,evolvesTo.get(1)[1],evolvesTo.get(1)[2]);
else
insertEvolution(name,evolvesTo.get(1)[1]);
}
new DownloadFile().execute(imageUrl,name);
insertPicture(name,"/res/mipmap/xxxhdpi/"+name+".jpg");
}
class DownloadFile extends AsyncTask<String,Integer,Long> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
String targetFileName=aurl[1]+".jpg";
int lengthOfFile = connection.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/res/mipmap/xxxhdpi/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
}
}
Any and all help is welcome.
There is problem with your simple cursor adapter,
Here you provide three columns
String[]columns = new String[] {"name","favourite","path"};
but here you supply only two views:
int[]to = new int[] {R.id.Digimon_name,R.id.Digimon_favourites};
also in your raw query
String query = "SELECT "+DIGIMON_TABLE_NAME+".ROWID AS _id,
"+DIGIMON_COLUMN_NAME+", "+DIGIMON_COLUMN_FAVOURITE+" FROM
"+DIGIMON_TABLE_NAME;
you provided only "_id", "name" and "favorite" columns and not the "path".

Android multiple contacts from groups and images

I want to do the following.
Pick up three to five contacts out of a special group of contacts or all contacts.
In the list it would be nice to show the contact image.
The selected contacts should have the following information (contact-id, first name, the small version of the contact image to save it as a blob in the database)
I found solutions for the different aspects.
-select multiple contacts:
How to obtain the checked rows in a custom view list
-show contacts from one group
getting contacts from a specified group in android
- photo problem
Getting a Photo from a Contact
But I dont know how to put those together. It would be great if someone could help me putting it together.
Thank you very much!
Frank J.
Solved it, but cant post the answer for some hours.
Solution (not prettyfied yet)
package com.pinkpony.frankj.contactpicker2;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Frank on 28.07.2014.
*/
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> name2 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> img1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadGroups();
//Toast.makeText(MainActivity.this, toString(), Toast.LENGTH_LONG).show();
Log.d("LongValue", toString());
getAllCallLogs(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
//Toast.makeText(getApplicationContext(), checkedcontacts, 1000).show();
Toast.makeText(MainActivity.this, checkedcontacts, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
/* Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
Cursor phones = cr.query(uri, projection, selection, selectionArgs,
sortOrder);
*/
// long groupId = id;
String[] cProjection = { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID };
Cursor groupCursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
cProjection,
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
new String[] { String.valueOf(6) }, null);
if (groupCursor != null && groupCursor.moveToFirst())
{
do
{
int nameCoumnIndex = groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = groupCursor.getString(nameCoumnIndex);
String szFullname=name;
//long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
// Log.d("your tag", "contact " + name + ":"+String.valueOf(contactId));
name1.add(name);
phno1.add(String.valueOf(contactId));
boolean foundToken = false;
// IDENTIFY Contact based on name and token
String szLookupKey = "";
Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, szFullname);
ContentResolver cr2 = getContentResolver();
Cursor idCursor = getContentResolver().query(lkup, null, null, null, null);
// get all the names
while (idCursor.moveToNext()) {
// get current row/contact ID = ID's are unreliable, so we will go for the lookup key
String szId = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
String szName = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
szLookupKey = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
// for this contact ID, search the custom field
Log.d("", "Searching token:" + szId + " Name:" + szName + " LookupKey:" + szLookupKey);
//Log.d(LOG_TAG, "search: "+lid + " key: "+key + " name: "+name);
}
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?";
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, String.valueOf(contactId) };
Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Log.d("your tag", "Vorname " + ":" + given);
name2.add(given);
}
nameCur.close();
} while (groupCursor.moveToNext());
groupCursor.close();
}
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
ImageView im1;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void retrieveContactPhoto(Long contactID) {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public Bitmap openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
// tv1= (TextView) vi.findViewById(R.id.textView2);
im1= (ImageView) vi.findViewById(R.id.imageView1);
Bitmap photo = null;
Long contactID=Long.valueOf(phno1.get(position));
im1.setImageBitmap(openPhoto(contactID));
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(""+ name1.get(position));
// tv1.setText(""+phno1.get(position));//
// retrieveContactPhoto(Long.valueOf(phno1.get(position)));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private class GroupInfo {
String id;
String title;
#Override
public String toString() {
return title+ " ("+id+")";
}
public String getId() {
return id;
}
}
List<GroupInfo> groups = new ArrayList<GroupInfo>();
public void loadGroups() {
final String[] GROUP_PROJECTION = new String[] {
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE,
ContactsContract.Groups.SUMMARY_WITH_PHONES
};
Cursor c = getContentResolver().query(
ContactsContract.Groups.CONTENT_SUMMARY_URI,
GROUP_PROJECTION,
ContactsContract.Groups.DELETED+"!='1' AND "+
ContactsContract.Groups.GROUP_VISIBLE+"!='0' "
,
null,
null);
final int IDX_ID = c.getColumnIndex(ContactsContract.Groups._ID);
final int IDX_TITLE = c.getColumnIndex(ContactsContract.Groups.TITLE);
Map<String,GroupInfo> m = new HashMap<String, GroupInfo>();
while (c.moveToNext()) {
GroupInfo g = new GroupInfo();
g.id = c.getString(IDX_ID);
g.title = c.getString(IDX_TITLE);
int users = c.getInt(c.getColumnIndex(ContactsContract.Groups.SUMMARY_WITH_PHONES));
if (users>0) {
// group with duplicate name?
GroupInfo g2 = m.get(g.title);
if (g2==null) {
m.put(g.title, g);
groups.add(g);
} else {
g2.id+=","+g.id;
}
}
Log.d("LongValue", g.id+g.title);
}
c.close();
}
}

Android: Refresh cursorloader from a second activity

Have a good day. I'm learning Android development so i'm creating a simple CRUD application, right now i have my main activity that has the listview (MarcaActivity) with the next code:
package com.example.crudapp.activity;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.crudapp.MarcaCursorAdapter;
import com.example.crudapp.R;
import com.example.crudapp.cp.MarcaCP;
public class MarcaActivity extends Activity implements
LoaderManager.LoaderCallbacks<Cursor> {
MarcaCursorAdapter crsAdap;
ListView lstMarcas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marca);
lstMarcas = (ListView)findViewById(R.id.lstMarcas);
lstMarcas.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(MarcaActivity.this, MarcaDetailActivity.class);
Uri todoUri = Uri.parse(MarcaCP.CONTENT_URI + "/" + arg3);
i.putExtra("DET", todoUri);
i.putExtra("ACTION", "EXISTING");
startActivity(i);
}
});
getLoaderManager().initLoader(0, null, this);
fillData();
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
getLoaderManager().restartLoader(0, null, this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.insertMnu:
Intent i = new Intent(this, MarcaDetailActivity.class);
i.putExtra("ACTION", "NEW");
startActivityForResult(i, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
/*switch (item.) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Uri uri = Uri.parse(MarcaCP.CONTENT_URI + "/"
+ info.id);
getContentResolver().delete(uri, null, null);
fillData();
return true;
}*/
return super.onContextItemSelected(item);
}
private void fillData() {
crsAdap = new MarcaCursorAdapter(this, R.layout.template_marcas, null ,
new String[]{MarcaCP.Marca.NOMBRE, MarcaCP.Marca.RANKING}, new int[]{R.id.nomMarca, R.id.rankMarca});
lstMarcas.setAdapter(crsAdap);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.marca, menu);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(this, MarcaCP.CONTENT_URI,
new String[]{MarcaCP.Marca.ID, MarcaCP.Marca.NOMBRE, MarcaCP.Marca.CODIGO, MarcaCP.Marca.RANKING}, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
crsAdap.swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
crsAdap.swapCursor(null);
} }
Then, i have the activity that manages the detail view where i can update or add items, called MarcaDetailActivity:
package com.example.crudapp.activity;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.crudapp.MarcaCursorAdapter;
import com.example.crudapp.R;
import com.example.crudapp.cp.MarcaCP;
public class MarcaDetailActivity extends Activity {
MarcaCursorAdapter crsAdap;
private Integer idReg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalle_marca);
Bundle extras = getIntent().getExtras();
if(extras != null && extras.get("ACTION").equals("EXISTING")) //Invocamos fillData
fillData((Uri)extras.get("DET"));
else
cleanForm();
}
public void cleanForm() {
((Button)findViewById(R.id.todo_edit_button)).setVisibility(View.INVISIBLE);
((Button)findViewById(R.id.todo_insert_button)).setVisibility(View.VISIBLE);
}
public void fillData(Uri uri) {
String[] projection = { MarcaCP.Marca.CODIGO,
MarcaCP.Marca.CLASIFICACION, MarcaCP.Marca.NOMBRE, MarcaCP.Marca.RANKING};
//builder.
Cursor cur = getContentResolver().query(uri, projection, null, null, null);
if(cur != null) {
cur.moveToFirst();
((EditText)findViewById(R.id.detNombre)).setText(cur.getString(cur.getColumnIndex(MarcaCP.Marca.NOMBRE)));
((EditText)findViewById(R.id.detCodigo)).setText(cur.getString(cur.getColumnIndex(MarcaCP.Marca.CODIGO)));
setIdReg(cur.getInt(cur.getColumnIndex(MarcaCP.Marca.ID)));
((EditText)findViewById(R.id.todo_edit_button)).setVisibility(View.VISIBLE);
((EditText)findViewById(R.id.todo_insert_button)).setVisibility(View.INVISIBLE);
String clasif = cur.getString(cur.getColumnIndex(MarcaCP.Marca.CLASIFICACION));
int rank = cur.getInt(cur.getColumnIndex(MarcaCP.Marca.RANKING));
Spinner spRnk = ((Spinner)findViewById(R.id.detRanking));
Spinner spClasf = ((Spinner)findViewById(R.id.detClasificacion));
//Buscamos setear los spinners en sus valores
for(short ps = 0; ps < spRnk.getCount(); ps++) {
String tmpRnk = (String)spRnk.getItemAtPosition(ps);
if(tmpRnk.equalsIgnoreCase("" + rank))
spRnk.setSelection(ps);
}
//Buscamos setear los spinners en sus valores
for(short ps = 0; ps < spClasf.getCount(); ps++) {
String tmpClas = (String)spClasf.getItemAtPosition(ps);
if(tmpClas.equalsIgnoreCase(clasif))
spClasf.setSelection(ps);
}
cur.close();
}
}
private boolean validate() {
boolean res = true;
return res;
}
public void guardar(View view) {
if(validate()) {
ContentValues cv = new ContentValues();
cv.put(MarcaCP.Marca.CLASIFICACION, (String)((Spinner)findViewById(R.id.detClasificacion)).getSelectedItem() );
cv.put(MarcaCP.Marca.CODIGO, ((TextView)findViewById(R.id.detCodigo)).getText().toString() );
cv.put(MarcaCP.Marca.NOMBRE, ((TextView)findViewById(R.id.detNombre)).getText().toString() );
cv.put(MarcaCP.Marca.RANKING, Integer.parseInt("" + ((Spinner)findViewById(R.id.detRanking)).getSelectedItem() ));
getContentResolver().insert(MarcaCP.CONTENT_URI, cv);
}
Toast.makeText(MarcaDetailActivity.this, "Registro registrado",
Toast.LENGTH_SHORT).show();
//Refrescamos el grid y cerramos la actividad
//((MarcaActivity)this.getCallingActivity()).refrescarLista()
//getLoaderManager().restartLoader(0, null, MarcaActivity.class);
this.finish();
}
public void regresar() {
Intent i = new Intent(MarcaDetailActivity.this, MarcaActivity.class);
i.putExtra("REFRESH", true);
startActivity(i);
}
public void actualizar(View view) {
if(validate()) {
ContentValues cv = new ContentValues();
cv.put(MarcaCP.Marca.CLASIFICACION, (String)((Spinner)findViewById(R.id.detClasificacion)).getSelectedItem() );
cv.put(MarcaCP.Marca.CODIGO, (String)((TextView)findViewById(R.id.detCodigo)).getText() );
cv.put(MarcaCP.Marca.NOMBRE, (String)((TextView)findViewById(R.id.detNombre)).getText() );
cv.put(MarcaCP.Marca.ID, getIdReg() );
cv.put(MarcaCP.Marca.RANKING, Integer.parseInt("" + ((Spinner)findViewById(R.id.detRanking)).getSelectedItem() ));
getContentResolver().update(MarcaCP.CONTENT_URI, cv, null, null);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.marca, menu);
return true;
}
public Integer getIdReg() {
return idReg;
}
public void setIdReg(Integer idReg) {
this.idReg = idReg;
} }
As you can see in the method guardar of MarcaDetailActivity, first i insert the item using my custom content provider, then i use Toast to show a confirm message, and finally finishing the activity, but when i do that, the listview isn't refreshed via the cursorloader. I read here (stackoverflow) and in other pages that i have to call
getLoaderManager().restartLoader(LIST_ID, null, this);
But in all examples that i found all the stuff (inserting data in the database and refreshing the list) is in the same activity, but in this case i have an activity with the list and the second activity that inserts the item, so i think that i have to call restartLoader from my detail activity, but i don't know how to do that or if that's the right way to do this. I was thinking about saving a reference to the list activity in extras when i create the intent to call the detail activity and have a public method that calls restartLoader but i don't know if that is the best approach. What's the best way to refresh the cursor loader from my detail activity?
And there's my content provider, MarcaCP:
package com.example.crudapp.cp;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import com.example.crudapp.util.ConnHandler;
public class MarcaCP extends ContentProvider {
private static final int TODOS = 10;
private static final int TODO_ID = 20;
public static final Uri CONTENT_URI = Uri.parse("content://provider.marcacp/marcas");
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI("provider.marcacp", "marcas", TODOS);
sURIMatcher.addURI("provider.marcacp", "marcas" + "/#", TODO_ID);
}
public static class Marca {
public static final String TABLA = "MARCA";
public static final String ID = "_id";
public static final String CODIGO = "codigo";
public static final String NOMBRE = "nombre";
public static final String CLASIFICACION = "clasificacion";
public static final String RANKING = "ranking";
}
private ConnHandler conn;
SQLiteDatabase dbObj;
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
int rowsDeleted = 0;
switch (uriType) {
case TODOS:
rowsDeleted = dbObj.delete(Marca.TABLA, selection, selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = dbObj.delete(Marca.TABLA,
Marca.ID + " = " + id,
null);
} else {
rowsDeleted = dbObj.delete(Marca.TABLA,
Marca.ID + " =" + id
+ " and " + selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
long id = 0;
switch (uriType) {
case TODOS:
id = dbObj.insert(Marca.TABLA, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse("marca/" + id);
}
#Override
public boolean onCreate() {
conn = new ConnHandler(getContext());
dbObj = conn.getDb();
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// Uisng SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
checkColumns(projection);
queryBuilder.setTables(Marca.TABLA);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case TODOS:
break;
case TODO_ID:
// Digamos para ver el detalle de un registro
queryBuilder.appendWhere(Marca.ID + " = "
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URIx: " + uri);
}
Cursor cur = queryBuilder.query(dbObj, projection, selection,
selectionArgs, null, null, sortOrder);
return cur;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
int rowsUpdated = 0;
switch (uriType) {
case TODOS:
rowsUpdated = dbObj.update(Marca.TABLA,
values,
selection,
selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = dbObj.update(Marca.TABLA,
values,
Marca.ID + " =" + id,
null);
} else {
rowsUpdated = dbObj.update(Marca.TABLA,
values,
Marca.ID + " =" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
private void checkColumns(String[] projection) {
/*String[] available = { TodoTable.COLUMN_CATEGORY,
TodoTable.COLUMN_SUMMARY, TodoTable.COLUMN_DESCRIPTION,
TodoTable.COLUMN_ID };
if (projection != null) {
HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
// Check if all columns which are requested are available
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}*/
} }
It's already registered in the AndroidManifest.xml:
<provider android:name=".cp.MarcaCP" android:authorities="provider.marcacp" />
Regards.
Try getContentResolver().notifyChange(MarcaCP.CONTENT_URI, null, false) from the second activity before finishing it.
It's a bit late to answer this.
since in your ContentProvider, you have
getContext().getContentResolver().notifyChange
which is great and correct!
so there is no need to called
getContentResolver().notifyChange(MarcaCP.CONTENT_URI, null, false) from the second activity before finishing it.
the problem is that instead of using getLoaderManager().initLoader
which is deprecated and not life-cycled aware.
try use
LoaderManager.getInstance(this).initLoader
this: is a class that maintains its own android.arch.lifecycle.Lifecycle and android.arch.lifecycle.ViewModelStore. For instance, androidx.fragment.app.FragmentActivity or androidx.fragment.app.Fragment.
so that when you pop back to the first activity and OnResume() called, there is no need to restart the loader again.
P.s. also a great reminder. Do not close any cursor related to the onLoadFinished(#NonNull Loader<Cursor> loader, Cursor cursor)
if doing so will also cause the loader won't update itself after data changed in DB.

Error in displaying data in custom listView while scrolling

My salute to the scholars. I am little embarrassed with custom listview. While scrolling, the values i am displaying in listview, gets changed. And on clicking on any listitem, it shows the data of the first record that is currently visible. Please help me out with it. I dont know how to handle getView() method to correct this bug.
My java code:
package com.addictioncounterapp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class StartActivity extends Activity
{
ListView listview1;
static SQLiteDatabase database;
private Addiction[] addictions;
private ArrayAdapter<Addiction> listAdapter ;
ArrayList<Addiction> addictionList;
ImageView iv_settings;
static int limit;
static String attribute;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
createDB();
loadDB();
iv_settings = (ImageView) findViewById(R.id.imageViewStart);
iv_settings.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(StartActivity.this, Settings.class);
startActivity(intent);
}
}
);
manageList();
listview1 = (ListView) findViewById(R.id.listViewStart);
if(addictionList.isEmpty())
{
Toast.makeText(getBaseContext(), "No records of Addiction found...Go to 'Settings > Manage Addictions > Add' to create new addiction.", Toast.LENGTH_LONG).show();
}
else
{
listview1.setAdapter(listAdapter);
}
listview1.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
View parentView = (View) arg1.getParent();
String textview1 = ((TextView) parentView.findViewById(R.id.textViewStartAddictionName)).getText().toString();
Intent intent = new Intent(StartActivity.this, AddictionDetails.class);
intent.putExtra("cat_name", textview1);
startActivity(intent);
}
}
);
}
private void createDB()
{
database = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
database.setLocale(Locale.getDefault());
database.setVersion(1);
try
{
String create_table_1 = "create table if not exists category (cat_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" cat_server_id INTEGER," +
" cat_name TEXT UNIQUE," +
" parent_cat_id INTEGER," +
" is_delete INTEGER," +
" is_sync INTEGER," +
" creation_date TEXT," +
" update_date TEXT)";
database.execSQL(create_table_1);
String create_table_2 = "create table if not exists category_attribute (cat_attribute_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" cat_attribute_server_id INTEGER," +
" cat_server_id INTEGER," +
" cat_id INTEGER," +
" cat_attribute_name TEXT," +
" cat_attribute_unit INTEGER," +
" cat_limit INTEGER," +
" is_delete INTEGER," +
" is_sync INTEGER," +
" creation_date TEXT," +
" update_date TEXT)";
database.execSQL(create_table_2);
String create_table_3 = "create table if not exists category_limit (limit_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" limit_server_id INTEGER," +
" cat_id INTEGER," +
" limit_count INTEGER," +
" is_delete INTEGER," +
" is_sync INTEGER," +
" creation_date TEXT," +
" update_date TEXT)";
database.execSQL(create_table_3);
String create_table_4 = "create table if not exists counter (counter_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" counter_server_id INTEGER," +
" cat_id INTEGER," +
" cat_attribute_id INTEGER," +
" cat_attribute_unit INTEGER," +
" counter_entry_date TEXT," +
" counter_entry_date_time TEXT," +
" is_delete INTEGER," +
" is_sync INTEGER)";
database.execSQL(create_table_4);
}
catch(SQLException e)
{
Log.e("SQLException","The SQL string is invalid. ");
Toast.makeText(getBaseContext(), "SQLException: The SQL string is invalid.", Toast.LENGTH_SHORT).show();
}
database.close();
}
private void loadDB()
{
database = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.OPEN_READWRITE, null);
}
private void manageList()
{
String addictionName="", todaysCount="", dailyLimit="", unit="";
addictionList = new ArrayList<Addiction>();
AddictionsData objAddictionsData = new AddictionsData();
Cursor cursor = database.query("category", new String[]{"cat_id"}, null, null, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
int tmp_cat_id = cursor.getInt(0);
addictionName = objAddictionsData.getAddictionName(tmp_cat_id);
todaysCount = objAddictionsData.getTodaysCount(tmp_cat_id);
dailyLimit = objAddictionsData.getDailyLimit(tmp_cat_id);
unit = objAddictionsData.getUnit(tmp_cat_id);
addictions = new Addiction[]{new Addiction(tmp_cat_id, addictionName, todaysCount, dailyLimit, unit)};
addictionList.addAll( Arrays.asList(addictions) );
}
cursor.close();
}
listAdapter = new AddictionArrayAdapter(this, addictionList);
database.close();//---------------------------
}
public int insertIntoCounter(int id)
{
loadDB();//------------------------------------
//---------------------insert the record-------------------
ContentValues values = new ContentValues();
int cat_attribute_id = 0;
int cat_attribute_unit = 0;
Cursor cursor1 = database.query("category_attribute", new String[]{"cat_attribute_id", "cat_attribute_unit"}, "cat_id=?", new String[]{id+""}, null, null, null);
if(cursor1.getCount() > 0)
{
while(cursor1.moveToNext())
{
cat_attribute_id = cursor1.getInt(0);
cat_attribute_unit = cursor1.getInt(1);
}
cursor1.close();
}
Calendar c = Calendar.getInstance();
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String currentTimeAndDate = dtf.format(c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String currentDate = df.format(c.getTime());
values.put("counter_server_id", 0);
values.put("cat_id", id);
values.put("cat_attribute_id", cat_attribute_id);
values.put("cat_attribute_unit", cat_attribute_unit);
values.put("counter_entry_date", currentDate);
values.put("counter_entry_date_time", currentTimeAndDate);
values.put("is_delete", 0);
values.put("is_sync", 0);
try
{
database.insert("counter", null, values);
}
catch(Exception e)
{
Log.e("Exception", e+"");
}
//------------------------LIMIT FUNCTIONSLITY---------------------
//------------------------fetching attribute name
cursor1 = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{id+""}, null, null, null);
if(cursor1.getCount() > 0)
{
while(cursor1.moveToNext())
attribute = cursor1.getString(0);
cursor1.close();
}
//------------------------fetching limit
cursor1 = database.query("category_limit", new String[]{"limit_count"}, "cat_id=?", new String[]{id+""}, null, null, null);
if(cursor1.getCount() > 0)
{
while(cursor1.moveToNext())
limit = cursor1.getInt(0);
cursor1.close();
}
//--------------------------fetching todays count
int todays_count = 0;
Calendar cal1 = Calendar.getInstance();
SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
String todays_date = dateFormat1.format(cal1.getTime());
cursor1 = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+id+" AND counter_entry_date = '"+todays_date+"';", null);
while(cursor1.moveToNext())
todays_count = cursor1.getInt(0);
//---------------------sending acknowledgement
int ack;
if(todays_count < limit)
ack = 0;
else if(todays_count == limit)
ack = 1;
else
ack = 2;
return ack;
}
public static class Addiction
{
private String cat_name = "", cat_todays_count="", cat_daily_limit="", cat_attribute_unit="";
private int cat_id = 0;
public Addiction(int id, String catName, String catTodaysCount, String catDailyLimit, String catAttributeUnit)
{
cat_id = id;
cat_name = catName ;
cat_todays_count = catTodaysCount;
cat_daily_limit = catDailyLimit;
cat_attribute_unit = catAttributeUnit;
}
public int getId()
{
return cat_id;
}
public String getCatName()
{
return cat_name;
}
public String getCatTodaysCount()
{
return cat_todays_count;
}
public String getCatDailyLimit()
{
return cat_daily_limit;
}
public String getCatAttributeUnit()
{
return cat_attribute_unit;
}
}
private static class AddictionViewHolder
{
private ImageView imageViewAddictionLog ;
private TextView textViewAddictionName, textViewTodaysCount, textViewDailyLimit, textViewAttributeUnit ;
public AddictionViewHolder( ImageView iv_log, TextView tv_addiction_name, TextView tv_todays_count, TextView tv_daily_limit, TextView tv_attribute_count)
{
imageViewAddictionLog = iv_log;
textViewAddictionName = tv_addiction_name;
textViewTodaysCount = tv_todays_count;
textViewDailyLimit = tv_daily_limit;
textViewAttributeUnit = tv_attribute_count;
}
public ImageView getImageViewAddLog()
{
return imageViewAddictionLog;
}
public TextView getTextViewAddictionName()
{
return textViewAddictionName;
}
public TextView getTextViewTodaysCount()
{
return textViewTodaysCount;
}
public TextView getTextViewDailyLimit()
{
return textViewDailyLimit;
}
public TextView getTextViewAttributeUnit()
{
return textViewAttributeUnit;
}
}
private static class AddictionArrayAdapter extends ArrayAdapter<Addiction>
{
private LayoutInflater inflater;
StartActivity objStartActivity = new StartActivity();
public AddictionArrayAdapter( Context context, List<Addiction> addictionList )
{
super( context, R.layout.single_row_start, R.id.textViewStartAddictionName, addictionList );
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Addiction addiction = (Addiction) this.getItem( position );
ImageView imageViewAddLog ;
TextView textViewAN ;
final TextView textViewTC;
final TextView textViewDL;
final TextView textViewU;
if(convertView == null)
{
convertView = inflater.inflate(R.layout.single_row_start, null);
imageViewAddLog = (ImageView) convertView.findViewById(R.id.imageViewStartAdd);
textViewAN = (TextView) convertView.findViewById(R.id.textViewStartAddictionName);
textViewTC = (TextView) convertView.findViewById(R.id.textViewStartTodaysCountValue);
textViewDL = (TextView) convertView.findViewById(R.id.textViewStartDailyLimitCount);
textViewU = (TextView) convertView.findViewById(R.id.textViewStartAddictionUnit);
imageViewAddLog.setFocusable(false);
imageViewAddLog.setFocusableInTouchMode(false);
imageViewAddLog.setClickable(true);
convertView.setTag( new AddictionViewHolder(imageViewAddLog, textViewAN, textViewTC, textViewDL, textViewU) );
imageViewAddLog.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
ImageView ib = (ImageView) v ;
Addiction addiction = (Addiction) ib.getTag();
int tmp_cat_id = addiction.getId();
int ack = objStartActivity.insertIntoCounter(tmp_cat_id);
String cat_name = addiction.getCatName();
switch(ack)
{
case 0:
String message0 = "Record added Successfully.";
customShowDialog(message0, tmp_cat_id);
break;
case 1:
String message1 = "Please stop "+cat_name+". Today you have already added "+limit+" "+ attribute+". Your daily limit is "+limit+" "+attribute+".";
customShowDialog(message1, tmp_cat_id);
break;
case 2:
String message2 = "Please stop "+cat_name+". Today you have already added "+limit+" "+ attribute+". You have crossed your daily limit of "+limit+" "+attribute+".";
customShowDialog(message2, tmp_cat_id);
break;
}
}
private void customShowDialog(String message, final int cat_id)
{
AlertDialog.Builder adb = new Builder(getContext());
adb.setTitle("Success !!!");
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
adb.setPositiveButton("Ok",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
arg0.cancel();
AddictionsData ad = new AddictionsData();
textViewTC.setText( ad.getTodaysCount(cat_id));
textViewDL.setText( ad.getDailyLimit(cat_id));
textViewU.setText( ad.getUnit(cat_id));
}
}
);
AlertDialog ad = adb.create();
ad.show();
}
}
);
}
else
{
AddictionViewHolder viewHolder = (AddictionViewHolder) convertView.getTag();
imageViewAddLog = viewHolder.getImageViewAddLog();
textViewAN = viewHolder.getTextViewAddictionName();
textViewTC = viewHolder.getTextViewTodaysCount();
textViewDL = viewHolder.getTextViewDailyLimit();
textViewU = viewHolder.getTextViewAttributeUnit();
}
imageViewAddLog.setTag( addiction );
textViewAN.setText( addiction.getCatName());
textViewTC.setText( addiction.getCatTodaysCount());
textViewDL.setText( addiction.getCatDailyLimit());
textViewU.setText( addiction.getCatAttributeUnit());
return convertView;
}
}
public static class AddictionsData
{
Cursor cursor;
String getAddictionName(int cat_id)
{
String tmp_name = null;
cursor = database.query("category", new String[]{"cat_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
tmp_name = cursor.getString(0);
}
cursor.close();
}
return tmp_name;
}
String getTodaysCount(int cat_id)
{
String todaysCount = null;
int todays_count = 0;
Calendar cal1 = Calendar.getInstance();
SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
String todays_date = dateFormat1.format(cal1.getTime());
cursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date = '"+todays_date+"';", null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
todays_count = cursor.getInt(0);
}
cursor.close();
}
String attribute = null;
cursor = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
attribute = cursor.getString(0);
}
cursor.close();
}
todaysCount = todays_count+" "+attribute;
return todaysCount;
}
String getDailyLimit(int cat_id)
{
String dailyLimit;
int daily_limit = 0;
cursor = database.query("category_limit", new String[]{"limit_count"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
daily_limit = cursor.getInt(0);
cursor.close();
}
String attribute = null;
cursor = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
attribute = cursor.getString(0);
}
cursor.close();
}
dailyLimit = daily_limit+ " "+attribute;
return dailyLimit;
}
String getUnit(int cat_id)
{
String unit;
int _unit = 0;
cursor = database.query("category_attribute", new String[]{"cat_attribute_unit"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
_unit = cursor.getInt(0);
cursor.close();
}
String attribute = null;
cursor = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
attribute = cursor.getString(0);
}
cursor.close();
}
unit = _unit+ " "+attribute;
return unit;
}
}
}
My main layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/main_bg_edited" >
<ImageView
android:id="#+id/imageViewStart"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/setting_icon"
android:layout_marginRight="7dp" />
<ListView
android:id="#+id/listViewStart"
android:layout_width="290dp"
android:layout_height="wrap_content"
android:layout_below="#+id/imageViewStart"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:divider="#android:color/transparent"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageViewStart"
android:layout_centerHorizontal="true"
android:text="Addictions"
style="#style/header_style" />
</RelativeLayout>
The layout from which i am inflating the view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/box_midbg" >
<TextView
android:id="#+id/textViewStartTodaysCountValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewStartAddictionName"
android:layout_toRightOf="#+id/textViewTodaysCount"
android:text=" TextView"
android:textSize="10sp"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textViewStartDailyLimitCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textViewStartTodaysCountValue"
android:layout_alignTop="#+id/textViewDailyLimit"
android:text="TextView"
android:textSize="10sp"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textViewStartAddictionUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textViewStartTodaysCountValue"
android:layout_marginRight="15dp"
android:text="TextView"
android:textColor="#ffffff"
android:textSize="10sp" />
<TextView
android:id="#+id/textViewStartAddictionName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageViewStartAdd"
android:layout_alignParentLeft="true"
android:layout_marginLeft="15dp"
android:text="TextView"
android:textColor="#ffffff"
android:textSize="20sp" />
<TextView
android:id="#+id/textViewTodaysCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textViewStartAddictionUnit"
android:layout_alignLeft="#+id/textViewStartAddictionName"
android:text="Today&apos;s Counts : "
android:textColor="#ffffff"
android:textSize="10sp" />
<TextView
android:id="#+id/textViewDailyLimit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textViewTodaysCount"
android:layout_below="#+id/textViewTodaysCount"
android:text="Daily Limit :"
android:textColor="#ffffff"
android:textSize="10sp" />
<ImageView
android:id="#+id/imageViewStartAdd"
android:layout_width="25sp"
android:layout_height="25sp"
android:layout_alignRight="#+id/textViewStartAddictionUnit"
android:layout_centerVertical="true"
android:clickable="true"
android:src="#drawable/add_btn" />
</RelativeLayout>
You should not store your data in the views as views are recycled and what will happen will almost certainly be what you didn't expect. The following
Addiction addiction = (Addiction) ib.getTag();
....
imageViewAddLog.setTag( addiction );
is not advisable. A better way is to let the list view handle the clicks so that you can know which view has been clicked and the correct Addiction object that corresponds to the view's position.
myList.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Addiction addiction = (Addiction) myList.getItemAtPosition(position);
...rest of code...
}
}
);
Please put all your other code after
convertView.setTag( new AddictionViewHolder(imageViewAddLog, textViewAN, textViewTC, textViewDL, textViewU) );
outside if and try to remove else from code.
rest of code of else will be same after if. Remember that when convertview is null, create a new holder and set in Tag. Then retrieve that object from Tag when convertview is not null. And write all other code like setting values to views etc after
AddictionViewHolder viewHolder = (AddictionViewHolder) convertView.getTag();

listview items disappearing

So.. my listview items are disappearing after they're scrolled off the screen. They're there, you scoll down, back up, and they're gone. After rotation they reappear, but I have no idea why this is happening.
package com.teslaprime.prirt;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.content.ContentValues;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ListView;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
public class TaskList extends Activity {
List<Task> tasks = new ArrayList<Task>();
TaskAdapter adapter = null;
SQLiteDatabase db = null;
public void populateList(){
adapter = new TaskAdapter();
adapter.clear();
Cursor cur = db.query("tasks",null,null,null,null,null,"timestamp");
cur.moveToFirst();
int anchor = 0;
while (cur.isAfterLast() == false) {
if (cur.getInt(cur.getColumnIndex("completed")) == 1) {
Task task = new Task(cur.getString(cur.getColumnIndex("name")),cur.getString(cur.getColumnIndex("type")));
task.id = cur.getInt(cur.getColumnIndex("id"));
task.completed = 1;
adapter.add(task);
anchor = anchor+1;
}
cur.moveToNext();
}
cur.moveToFirst();
while (cur.isAfterLast() == false) {
if (cur.getInt(cur.getColumnIndex("completed")) == 0) {
Task task = new Task(cur.getString(cur.getColumnIndex("name")),cur.getString(cur.getColumnIndex("type")));
task.id = cur.getInt(cur.getColumnIndex("id"));
adapter.add(task);
}
cur.moveToNext();
}
cur.close();
for (int i = tasks.size(); i <= 8; i++) {
adapter.add(new Task());
}
ListView list = (ListView) findViewById(R.id.tasks);
list.setAdapter(adapter);
list.setSelection(anchor);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent setupProcess = new Intent (TaskList.this, SetupWelcome.class);
boolean first = checkDatabase() ? true : false;
db = openOrCreateDatabase("priRT.db",
SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.setVersion(1);
db.setLockingEnabled(true);
db.execSQL("create table if not exists tasks ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "time integer,"
+ "completed integer,"
+ "timestamp integer,"
+ "spacer integer,"
+ "type text);");
db.execSQL("create table if not exists schedule ("
+ "id integer primary key autoincrement,"
+ "hours_free integer);");
if (first) { startActivityForResult(setupProcess,0); }
populateList();
Button add = (Button) findViewById(R.id.addTask);
add.setOnClickListener(onAdd);
}
public View.OnClickListener closeTaskListener = new View.OnClickListener(){
public void onClick(View v){
int pos = (Integer) (v.getTag());
Task task = adapter.getItem(pos);
ContentValues values = new ContentValues();
if (task.completed == 1){
values.put("completed", 0);
task.completed = 0;
} else {
values.put("completed", 1);
task.completed = 1;
}
Long time = new Date().getTime();
values.put("timestamp", time);
db.update("tasks", values, "id='"+task.id+"'", null);
populateList();
}
};
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(
"/data/data/com.teslaprime.prirt/databases/priRT.db", null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {}
return checkDB == null ? true : false;
}
private View.OnClickListener onAdd = new View.OnClickListener() {
public void onClick(View view) {
Intent addTask = new Intent (view.getContext(), TaskEntry.class);
startActivityForResult(addTask, 2);
}
};
protected void onActivityResult(int req, int res, Intent data) {
if (req == 0 && res == RESULT_OK) {
Intent setup = new Intent (TaskList.this, SetupWizard.class);
startActivityForResult(setup, 1);
}
if (req == 2 && res == RESULT_OK) {
Task task = new Task(data.getStringExtra("name"),data.getStringExtra("type"));
adapter.add(task);
ContentValues values = new ContentValues();
values.put("name", data.getStringExtra("name"));
values.put("type", data.getStringExtra("type"));
values.put("completed", 0);
values.put("spacer", 0);
db.insert("tasks", null, values);
Cursor cur = db.query("tasks", null, null, null, null, null, null);
cur.moveToLast();
task.id = cur.getInt(cur.getColumnIndex("id"));
cur.close();
populateList();
}
}
class TaskAdapter extends ArrayAdapter<Task> {
TaskAdapter() {super(TaskList.this,R.layout.task,tasks);}
private List<Task> taskList;
private Context context;
public View getView(int pos, View convertView, ViewGroup parent) {
View task = convertView;
if (convertView == null) {
LayoutInflater inflater = getLayoutInflater();
task = inflater.inflate(R.layout.task,null);
}
if (tasks.get(pos).spacer == 0) {
TextView taskName = (TextView) task.findViewById(R.id.name);
TextView taskType = (TextView) task.findViewById(R.id.type);
taskName.setText(tasks.get(pos).name);
taskType.setText(tasks.get(pos).type);
Task taskList = adapter.getItem(pos);
CheckBox closeTask = (CheckBox) task.findViewById(R.id.closeTask);
if (taskList.completed == 0) {
closeTask.setChecked(false);
} else {
closeTask.setChecked(true);
}
closeTask.setTag(pos);
closeTask.setOnClickListener(closeTaskListener);
} else {
CheckBox closeTask = (CheckBox) task.findViewById(R.id.closeTask);
task.setVisibility(View.GONE);
task.setFocusable(false);
task.setClickable(false);
}
return task;
}
}
}
It may be happening because of the background color of surface in which list appears. Try setting the background color to white in linerlayout and text view coolr black then scroll the through the list view again.

Categories

Resources