In my custom listview, when i try to scroll down to view a new list item (either bottom or top) the scroll is becoming laggy. Im kinda new in android developement and database so i dunno what is the cause of this.
This is my MainActivity
public class MainActivity extends AppCompatActivity implements CustomAdapter.passing{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_loading);
db = new DBHandler(this,null,null,1);
namaDoctor = this.getResources().getStringArray(R.array.namaDokter);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
setContentView(R.layout.activity_main);
searchSpesIcon = (ImageView) findViewById(R.id.buttonSearchSpesial);
searchRsIcon = (ImageView) findViewById(R.id.buttonSearchRs);
searchField = (EditText) findViewById(R.id.searchField);
searchDocIcon = (ImageView) findViewById(R.id.buttonSearchDoctor);
help = (LinearLayout) findViewById(R.id.help_view);
searchDocIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor WHERE nama LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian nama dokter " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
searchSpesIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor WHERE spesialisasi LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian dokter spesialisasi " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
searchRsIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor " +
"WHERE lokasia LIKE '%"+keyword+"%' OR lokasib LIKE '%"+keyword+"%' OR lokasic LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian dokter di rumah sakit " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
}
},milis);
}
void change(){
if(help.getVisibility()==View.VISIBLE){help.setVisibility(View.GONE);}
cAdapter = new CustomAdapter(this,namaDoctor,id);
//use callback
cAdapter.setPass(this);
list = (ListView) findViewById(R.id.listContatiner);
list.setAdapter(cAdapter);
cAdapter.notifyDataSetChanged();
}
#Override
public void getTag1(int t){
p1=t;
}
#Override
public void getTag2(int t2) {
p2=t2;
setNewAct(p1,p2);
}
public void setNewAct(int x, int y){
//some method
}
My CustomAdapter class
public class CustomAdapter extends ArrayAdapter {
Context c1;
String s1[];
Integer id[];
String spesialisasi[] ;
String daerahPraktek[];
int arrayImageDoctor[] = {R.drawable.doctor_1...};
public CustomAdapter(Context c, String s[], Integer i[]) {
super(c,R.layout.item_doctor,s);
this.c1=c;
this.s1=s;
this.id=i;
}
private passing pass;
#Override
public View getView(final int position, View v, ViewGroup parent) {
final LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
spesialisasi= c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
final TextView nama = (TextView) v.findViewById(R.id.namaDoctor);
TextView spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
TextView daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
ImageView ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
Button lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
nama.setText(s1[position]);
spesial.setText("Dokter " + spesialisasi[id[position]]);
daerah.setText(daerahPraktek[id[position]]);
ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
lokasi.setTag(R.id.tag1,id[position]);
lokasi.setTag(R.id.tag2,position);
lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return v;
}
public void setPass(passing pass){
this.pass=pass;
}
public interface passing{
void getTag1(int t1);
void getTag2(int t2);
}
My DBHandler class
public class DBHandler extends SQLiteOpenHelper {
public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
c=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_DOCTOR + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAMA + " TEXT, " +
COLUMN_DAERAH + " TEXT, " +
COLUMN_SPESIALISASI + " TEXT, " +
COLUMN_LOKASI_A + " TEXT, " +
COLUMN_LOKASI_B + " TEXT, " +
COLUMN_LOKASI_C + " TEXT, " +
COLUMN_ALAMAT_A + " TEXT, " +
COLUMN_ALAMAT_B + " TEXT, " +
COLUMN_ALAMAT_C + " TEXT " +");";
db.execSQL(query);
arrayNama = c.getResources().getStringArray(R.array.namaDokter);
arrayDaerah = c.getResources().getStringArray(R.array.daerahDokter);
arraySpesialisasi = c.getResources().getStringArray(R.array.spesialiasiDokter);
arrayLokasiA = c.getResources().getStringArray(R.array.lokasiA);
arrayLokasiB = c.getResources().getStringArray(R.array.lokasiB);
arrayLokasiC = c.getResources().getStringArray(R.array.lokasiC);
arrayAlamatA = c.getResources().getStringArray(R.array.alamatA);
arrayAlamatB = c.getResources().getStringArray(R.array.alamatB);
arrayAlamatC = c.getResources().getStringArray(R.array.alamatC);
ContentValues cv = new ContentValues();
for (int i = 0; i < arrayNama.length; i++) {
cv.put(COLUMN_NAMA, arrayNama[i]);
cv.put(COLUMN_DAERAH, arrayDaerah[i]);
cv.put(COLUMN_SPESIALISASI, arraySpesialisasi[i]);
cv.put(COLUMN_LOKASI_A, arrayLokasiA[i]);
cv.put(COLUMN_LOKASI_B, arrayLokasiB[i]);
cv.put(COLUMN_LOKASI_C, arrayLokasiC[i]);
cv.put(COLUMN_ALAMAT_A, arrayAlamatA[i]);
cv.put(COLUMN_ALAMAT_B, arrayAlamatB[i]);
cv.put(COLUMN_ALAMAT_C, arrayAlamatC[i]);
db.insert(TABLE_DOCTOR, null, cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DOCTOR);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PATIENT);
onCreate(db);
}
public String[] searchDoctor(String qdoc){
SQLiteDatabase db = getWritableDatabase();
Cursor c= db.rawQuery(qdoc,null);
String selectedDoc[] = new String[c.getCount()];
Integer selectedId[] = new Integer[c.getCount()];
String selectedLokasiA[] = new String[c.getCount()];
String selectedLokasiB[] = new String[c.getCount()];
String selectedLokasiC[] = new String[c.getCount()];
String selectedAlamatA[] = new String[c.getCount()];
String selectedAlamatB[] = new String[c.getCount()];
String selectedAlamatC[] = new String[c.getCount()];
int i = 0;
while(c.moveToNext()){
String doc = c.getString(c.getColumnIndex(COLUMN_NAMA));
Integer id = c.getInt(c.getColumnIndex(COLUMN_ID));
String lokasia = c.getString(c.getColumnIndex(COLUMN_LOKASI_A));
String lokasib = c.getString(c.getColumnIndex(COLUMN_LOKASI_B));
String lokasic = c.getString(c.getColumnIndex(COLUMN_LOKASI_C));
String alamata = c.getString(c.getColumnIndex(COLUMN_ALAMAT_A));
String alamatb = c.getString(c.getColumnIndex(COLUMN_ALAMAT_B));
String alamatc = c.getString(c.getColumnIndex(COLUMN_ALAMAT_C));
selectedDoc[i]= doc;
selectedId[i] = id-1;
selectedLokasiA[i]= lokasia;
selectedLokasiB[i] = lokasib;
selectedLokasiC[i] = lokasic;
selectedAlamatA[i]= alamata;
selectedAlamatB[i]=alamatb;
selectedAlamatC[i]= alamatc;
i++;
}
this.doctorId=selectedId;
this.doctorLokasiA=selectedLokasiA;
this.doctorLokasiB=selectedLokasiB;
this.doctorLokasiC=selectedLokasiC;
this.doctorAlamatA=selectedAlamatA;
this.doctorAlamatB=selectedAlamatB;
this.doctorAlamatC=selectedAlamatC;
return selectedDoc;
}
public Integer[] getDoctorId(){
return doctorId;
}
public static String[] getDoctorLokasiA() {
return doctorLokasiA;
}
public static String[] getDoctorLokasiB() {
return doctorLokasiB;
}
public static String[] getDoctorLokasiC() {
return doctorLokasiC;
}
public static String[] getDoctorAlamatA() {
return doctorAlamatA;
}
public static String[] getDoctorAlamatB() {
return doctorAlamatB;
}
public static String[] getDoctorAlamatC() {
return doctorAlamatC;
}
And my Item_doctor.xml
<RelativeLayout
android:id="#+id/itemCLick"
android:background="#0E9EA1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/doctor_1"
android:id="#+id/imageListDoctor"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageListDoctor"
android:layout_toEndOf="#+id/imageListDoctor"
android:id="#+id/linearLayout">
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama"
android:id="#+id/namaDoctor"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spesialis"
android:id="#+id/spesialisasiDoctor"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Daerah"
android:id="#+id/daerahPraktekDoctor"/>
</LinearLayout>
<Button
android:layout_width="115dp"
android:layout_height="wrap_content"
android:text="Lihat lokasi praktek"
android:layout_alignBottom="#+id/linearLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/lokasiPraktek"
android:onClick="LokasiPraktek"/>
Can someone tell me :
1.Does cursor inserting to array and Sqlite Query can cause big performance issue if not done correctly ?
2.Does the amount of view in the item of an list can affect the performance ?
3.What other things that affect listview performance ?
It will be good if someone tell me in which part of my code that i must change to increase the scroll speed.
Performance of list view can be increased if you use custom ViewHolder and implement in adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
spesialisasi = c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.item_doctor, parent, false);
viewHolder = new ViewHolder();
viewHolder.nama = (TextView) v.findViewById(R.id.namaDoctor);
viewHolder.spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
viewHolder.daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
viewHolder.ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
viewHolder.lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.nama.setText(s1[position]);
viewHolder.spesial.setText("Dokter " + spesialisasi[id[position]]);
viewHolder.daerah.setText(daerahPraktek[id[position]]);
viewHolder.ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
viewHolder.lokasi.setTag(R.id.tag1, id[position]);
viewHolder.lokasi.setTag(R.id.tag2, position);
viewHolder.lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return convertView;
}
private class ViewHolder {
private ImageView ImageDoc;
private Button lokasi;
private TextView nama;
private TextView spesial;
private TextView daerah;
}
Your adapter class's getView method is not properly implemented.
Change it to
#Override
public View getView(final int position, View v, ViewGroup parent) {
View row;
if (v == null) {
final LayoutInflater li = (LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.item_doctor, null);
} else {
row = v;
}
spesialisasi = c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
final TextView nama = (TextView) row.findViewById(R.id.namaDoctor);
TextView spesial = (TextView) row.findViewById(R.id.spesialisasiDoctor);
TextView daerah = (TextView) row.findViewById(R.id.daerahPraktekDoctor);
ImageView ImageDoc = (ImageView) row.findViewById(R.id.imageListDoctor);
Button lokasi = (Button) row.findViewById(R.id.lokasiPraktek);
nama.setText(s1[position]);
spesial.setText("Dokter " + spesialisasi[id[position]]);
daerah.setText(daerahPraktek[id[position]]);
ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
lokasi.setTag(R.id.tag1, id[position]);
lokasi.setTag(R.id.tag2, position);
lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return row;
}
getView function in adapter will called when you scrolled to make a item visible. As you write:
final LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
View v will be relayout while you scroll so that it make bad performace. You need check to reuse this view by:
if(v==null) {
final LayoutInflater li = (LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v= li.inflate(R.layout.item_doctor, null);
}
I recommend you use ViewHolder class with Adapter.
try the below adapter,and set the Tag for you each View of Listview.
public class CustomAdapter extends ArrayAdapter {
Context c1;
String s1[];
Integer id[];
String spesialisasi[] ;
String daerahPraktek[];
int arrayImageDoctor[] = {R.drawable.doctor_1...};
public CustomAdapter(Context c, String s[], Integer i[]) {
super(c,R.layout.item_doctor,s);
this.c1=c;
this.s1=s;
this.id=i;
}
private passing pass;
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder viewHolder = null;
if(v==null){
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
viewHolder = new ViewHolder();
viewHolder.nama = (TextView) v.findViewById(R.id.namaDoctor);
viewHolder.spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
viewHolder.daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
viewHolder.ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
viewHolder.lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
convertView.setTag(viewHolder);
}else{
iewHolder = (ViewHolder) convertView.getTag();
}
spesialisasi= c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
viewHolder.nama.setText(s1[position]);
viewHolder.spesial.setText("Dokter " + spesialisasi[id[position]]);
viewHolder.daerah.setText(daerahPraktek[id[position]]);
viewHolder.ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
viewHolder.lokasi.setTag(R.id.tag1,id[position]);
viewHolder.lokasi.setTag(R.id.tag2,position);
viewHolder.lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return v;
}
class ViewHolder {
TextView nama,spesial,daerah;
Button lokasi;
ImageView ImageDoc;
}
public void setPass(passing pass){
this.pass=pass;
}
public interface passing{
void getTag1(int t1);
void getTag2(int t2);
}
Related
I'm developing an application in Android Studio using this library: com.daimajia.swipelayout:library:1.2.0#aar. My app user a SQLite database with the following classes:
BDSQLiteHelper.java
public class BDSQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ExtraOficial";
private static final String TABELA_VAZAMENTOS = "VazamentosToSQL";
private static final String vazID = "VazID";
private static final String nomeServico = "nomeServico";
private static final String[] VAZ_COLUNAS = {vazID, nomeServico};
public BDSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_VAZAMENTOTABLE = "CREATE TABLE VazamentosToSQL ("+
"vazID INTEGER PRIMARY KEY AUTOINCREMENT,"+
"nomeServico)";
db.execSQL(CREATE_VAZAMENTOTABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS VazamentosToSQL");
this.onCreate(db);
}
public void addVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(nomeServico, VazamentosToSQL.getNomeServico());
db.insert(TABELA_VAZAMENTOS, null, values);
db.close();
}
public VazamentosToSQL getVazamentos (int vazID) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABELA_VAZAMENTOS,
VAZ_COLUNAS,
" vazID = ?",
new String[] {String.valueOf(vazID)},
null,
null,
null,
null);
if (cursor == null) {
return null;
} else {
cursor.moveToFirst();
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
return VazamentosToSQL;
}
}
private VazamentosToSQL cursorTovazamentos(Cursor cursor) {
VazamentosToSQL VazamentosToSQL = new VazamentosToSQL();
VazamentosToSQL.setVazID(Integer.parseInt(cursor.getString(0)));
VazamentosToSQL.setNomeServico(cursor.getString(1));
return VazamentosToSQL;
}
public ArrayList<VazamentosToSQL> getAllVazamentos() {
ArrayList<VazamentosToSQL> listaVazamentos = new ArrayList<VazamentosToSQL>();
String query = "SELECT * FROM " + TABELA_VAZAMENTOS + " ORDER BY "+ vazID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
listaVazamentos.add(VazamentosToSQL);
} while (cursor.moveToNext());
}
return listaVazamentos;
}
[...]
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS,
vazID+" =?",
new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
VazamentosToSQL.java
public class VazamentosToSQL {
private int vazID;
private String nomeServico;
public int getVazID() { return vazID; }
public void setVazID(int vazID) {
this.vazID = vazID;
}
public String getNomeServico() { return nomeServico; }
public void setNomeServico(String nomeServico) { this.nomeServico = nomeServico; }
}
ListViewActivity.java:
[...]
//variables
private BDSQLiteHelper bd;
ArrayList<VazamentosToSQL> listaVazamentos;
SwipeLayout swipeLayout;
private final static String TAG = ListViewActivity.class.getSimpleName();
vazamentosAdapter adapter;
ListView lista;
[...]
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
[...]
bd = new BDSQLiteHelper(this);
lista = (ListView) findViewById(R.id.lvdenuncias);
listaVazamentos = bd.getAllVazamentos();
setListViewHeader();
setListViewAdapter();
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { //aqui é o vazamentosAdapter
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ExibeVazamentosActivity.this, DetalhesVazamentosActivity.class);
intent.putExtra("vazID", listaVazamentos.get(position).getVazID());
startActivity(intent);
}
});
#Override
protected void onStart() {
super.onStart();
updateAdapter(); //Refresh ListView items
}
private void setListViewHeader() {
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview, lista, false);
totalClassmates = (TextView) header.findViewById(R.id.total);
swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
setSwipeViewFeatures();
//UNNECESSARY for me: lista.addHeaderView(header);
}
private void setSwipeViewFeatures() {
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
//add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));
swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
Log.i(TAG, "onClose");
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
Log.i(TAG, "on swiping");
}
#Override
public void onStartOpen(SwipeLayout layout) {
Log.i(TAG, "on start open");
}
#Override
public void onOpen(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally show");
}
#Override
public void onStartClose(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally close");
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
}
private void setListViewAdapter() {
adapter = new vazamentosAdapter(this, listaVazamentos);
lista.setAdapter(adapter);
}
public void updateAdapter() {
listaVazamentos.clear();
listaVazamentos.addAll(bd.getAllVazamentos());
adapter.notifyDataSetChanged(); //update adapter
lista.invalidateViews();
lista.refreshDrawableState();
}
}
vazamentosAdapter.java:
public class vazamentosAdapter extends ArrayAdapter<VazamentosToSQL> {
private final Context context;
private final ArrayList<VazamentosToSQL> elementos;
File imgFile;
private Bitmap bitmap;
private ExifInterface exifObject;
private ExibeVazamentosActivity activity;
int vazID;
private SQLiteDatabase bd;
public vazamentosAdapter(Context context, ArrayList<VazamentosToSQL> elementos) {
super(context, R.layout.linha, elementos);
this.context = context;
this.elementos = elementos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.linha, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
}else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
[...]
editText.setText(elementos.get(position).getVaznomeServico());
holder.btnEdit.setOnClickListener(onEditListener(position, holder));
holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));
return convertView;
}
private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
/**--------------Tried it, not working =( ---------------*/
elementos.get(position).getVazID();
//listaVazamentos.remove(position);
//activity.listaVazamentos.remove(position);
//bd = context.openOrCreateDatabase("DesoExtraOficial", Activity.MODE_PRIVATE, null);
//bd.execSQL("DELETE from VazamentosToSQL where vazID = '" + elementos.get(position).getVazID() + "'");
//bd.close();
//elementos.remove(position);
Toast.makeText(context, "ID: "+elementos.get(position).getVazID(),Toast.LENGTH_LONG).show();
bd.deleteVazamentos(VazamentosToSQL);
holder.swipeLayout.close();
// activity.updateAdapter(); //Executa o método "updateAdapter()" na Activity "ExibeVazamentos"
/**--------------Tried it, not working =( ---------------*/
}
};
}
private class ViewHolder {
private TextView name;
private View btnDelete;
private View btnEdit;
private SwipeLayout swipeLayout;
private ListView listv;
public ViewHolder(View v) {
swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
btnDelete = v.findViewById(R.id.delete);
btnEdit = v.findViewById(R.id.edit_query);
listv = (ListView) v.findViewById(R.id.lvdenuncias);
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
}
}
The mentioned library is working great. But i'm trying to delete database row when user click in a button according to the listview selected line. With this code: elementos.get(position).getVazID() I get the database index. But I can't delete from database. Someone can help me with the code to delete row from database and line from listview?
Try changing this:
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS, vazID+" =?", new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
To this:
public void deleteVazamentos(int vazID) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABELA_VAZAMENTOS, "vazID=" + vazID, null);
}
Then if you want to delete a row, you can call:
(Inside onDeleteListener)
bd.deleteVazamentos(elementos.get(position).getVazID());
I do not understand how to perform this operation that you mention.
When I press the button I want to change the amount of food orders
I just want to update the button on the selected topic or, if it does not, activate the entire list
public class AdapterFood extends ArrayAdapter<Charola.Producto> {
ImageView imgFood;
private String nameService = "AgregarItemCharola";
private String usuarioId = "UsuarioId";
private String productoId = "ProductoId";
private String cantidad = "Cantidad";
private String especificaciones = "Especificaciones";
private String urlComplete = Constantes.URLMAIN + nameService + "?";
private Fragment fragment;
private List<Charola.Producto> productoList;
public AdapterFood(Context context, List<Charola.Producto> productoList, Fragment fragment) {
super(context, 0, productoList);
this.fragment = fragment;
this.productoList = productoList;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listViewInflate = convertView;
if (convertView == null) {
listViewInflate = inflater.inflate(R.layout.item_menu, viewGroup, false);
}
imgFood = (ImageView) listViewInflate.findViewById(R.id.imageFood);
TextView tituloFood = (TextView) listViewInflate.findViewById(R.id.tittleFood);
TextView descricionFood = (TextView) listViewInflate.findViewById(R.id.descriptionFood);
TextView precio = (TextView) listViewInflate.findViewById(R.id.priceFood);
final Button btnAnadir = (Button) listViewInflate.findViewById(R.id.buttonAnadir);
final Charola.Producto producto = getItem(position);
tituloFood.setText(producto.getNombre().toString());
descricionFood.setText(producto.getDescripcion());
precio.setText("$" + producto.getPrecio() + ".00");
if (producto.getCantidad() != 0) {
btnAnadir.setText("+ Añadir (" + producto.getCantidad() + ")");
btnAnadir.setBackgroundResource(R.drawable.btns_dialogs);
} else {
btnAnadir.setText("+ Añadir");
btnAnadir.setBackgroundResource(R.drawable.btn_anadir);
}
btnAnadir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new consumeServiceAgregarProductoACharola().execute(urlComplete + "#" + producto.getIdProducto());
}
});
Glide.with(getContext()).
load(producto.getUrlFoto()).placeholder(R.drawable.place_holder)
.into(imgFood);
return listViewInflate;
}
//recuperar id usuario
public int recuperarIdUsario() {
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MIS_PREFRENCIAS", Context.MODE_PRIVATE);
int valor = sharedPreferences.getInt("id", 1);
return valor;
}
//Asynta
}
I have two buttons: + and -. I want that when I click on the button +, the value of the textview present in the fragment class (outside the listview) is changed. How can I do this ?
This is my Adapter class:
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
public CartBaseAdapter(Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
// viewHolder.mImgDelete.setTag(pojoCart.getmCategoryId());
/* try {
URL url = new URL(pojoCart.getmItemImage());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
viewHolder.mImgItem.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
// Log.e("exception", "" + e.getMessage());
}*/
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
mValue++;
viewHolder.mTvNumber.setText("" + mValue);
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
// viewHolder.Dish_rate.setVisibility(View.GONE);
Log.e("value1", value1);
Log.e("value2", value2);
z = x * y;
pojoCart.setmItemPrice(String.valueOf(z));
Log.e("z", "" + z);
if (x > 2) {
int n = x - 1;
int k = z / n;
Log.e("k", "" + k);
pojoCart.setmItemPrice(String.valueOf(k));
} else {
pojoCart.setmItemPrice(String.valueOf(z));
}
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
int total = dbh.getTotalOfAmount();
pojoCart.setmTotalPrice(total);
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
if (mValue > 0) {
mValue--;
viewHolder.mTvNumber.setText("" + mValue);
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
if (x >= 1) {
Log.e("value11", value1);
Log.e("value22", value2);
int n = x + 1;
Log.e("n", "" + n);
int k = y / n;
Log.e("k", "" + k);
z = k * x;
Log.e("z", "" + z);
pojoCart.setmItemPrice(String.valueOf(z));
} else {
pojoCart.setmItemPrice(pojoCart.getmItemPrice());
}
}
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
viewHolder.mImgDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
int categoryId = pojoCart.getmCategoryId();
// int id = (Integer) view.getTag();
// id++;
Log.e("removeIdFromTheTable", "" + categoryId);
dbh.delete_byID(categoryId);
mList.remove(position);
notifyDataSetChanged();
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
This is my Fragment Class:
public class Cart extends Fragment implements View.OnClickListener {
private ArrayList<PojoCart> mCartList;
private ListView mListView;
private CartBaseAdapter mCartBaseAdapter;
private DataBaseHandler dbh;
private List<PojoCartDataBase> pojoCartDataBase;
private TextView mTvProcesscheck, mTvTotalPrice;
private String ItemName, ItemPrice;
private String ItemImage;
private ArrayList<String> mTotalPrice;
private Toolbar toolbar;
private int ItemQuantity;
int id = 1;
private String categoryId;
private int sumOfPrice;
private PojoCart pojoCart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
// addData();
displayTotalAmount();
try {
getDataFromDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initialize() {
mTotalPrice = new ArrayList<String>();
mCartList = new ArrayList<PojoCart>();
mListView = (ListView) getActivity().findViewById(R.id.listview_cart);
mCartBaseAdapter = new CartBaseAdapter(getContext(), mCartList);
Parcelable state = mListView.onSaveInstanceState();
mListView.setAdapter(mCartBaseAdapter);
mListView.onRestoreInstanceState(state);
mTvProcesscheck = (TextView) getActivity().findViewById(R.id.tv_checkout);
mTvTotalPrice = (TextView) getActivity().findViewById(R.id.tv_total_price);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
dbh = new DataBaseHandler(getContext());
mTvProcesscheck.setOnClickListener(this);
toolbar.setTitle("Cart");
mCartBaseAdapter.notifyDataSetChanged();
final RippleView rippleView = (RippleView) getActivity().findViewById(R.id.ripple_view_cart);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
Log.d("Sample", "Ripple completed");
Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
toolbar.setTitle("Restaurant List");
}
});
}
/* private void addData() {
for (int i = 0; i < mItemName.length; i++) {
PojoCart pojoCart = new PojoCart();
pojoCart.setmItemName(mItemName[i]);
pojoCart.setmItemPrice(mItemPrice[i]);
pojoCart.setmItemImage(mItemImage[i]);
mCartList.add(pojoCart);
}
// mCartList.add(pojoCartDataBase);
}
*/
private void getDataFromDatabase() throws IOException {
Cursor c = dbh.getAllRows();
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
// int id = c.getInt(0);
int id = c.getInt(1);
Log.e("id.....", "" + id);
ItemName = c.getString(2);
ItemPrice = c.getString(3);
Log.e("itemname", ItemName);
Log.e("itemprice", ItemPrice);
ItemQuantity = c.getInt(4);
Log.e("itemquantity", "" + ItemQuantity);
ItemImage = c.getString(5);
Log.e("itemimage.........", ItemImage);
pojoCart = new PojoCart();
pojoCart.setmItemName(ItemName);
pojoCart.setmItemPrice(ItemPrice);
pojoCart.setmItemImage(ItemImage);
pojoCart.setmQuantity(ItemQuantity);
pojoCart.setmCategoryId(id);
mCartList.add(pojoCart);
mCartBaseAdapter.notifyDataSetChanged();
c.moveToNext();
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_checkout:
/* Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();*/
// toolbar.setTitle("Checkout");
}
}
public void displayTotalAmount() {
int total = dbh.getTotalOfAmount();
mTvTotalPrice.setText(String.valueOf(total));
}
}
I want to change the value of the mTvTotalPric (Textview) on click of the button + and -, which is present at the listview. And the textview which the value I want to change is outside the listview.
In your Adapter class create one interface
Adapter.class
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
private SendDataToFragment sendDataToFragment;
public CartBaseAdapter(FragmentCart fragmentCart, Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
sendDataToFragment = (SendDataToFragment) fragmentCart;
}
//Interface to send data from adapter to fragment
public interface SendDataToFragment {
void sendData(String Data);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
Inside your fragment implement that interface so as soon as your button is clicked in your adapter you will get the data inside your fragment.
Fragment.class
public class FragmentCart extends Fragment implements
View.OnClickListener, CartBaseAdapter.SendDataToFragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, null);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CartBaseAdapter adapter = new CartBaseAdapter(FragmentCart.this, getActivity(), yourList);
}
#Override
public void onClick(View v) {
}
#Override
public void sendData(String Data) {
//set this data to your textView
}
}
Create a interface :
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, int value);
}
In your listview adapter use interface like below on click of button + or - like :
MyListener ml;
ml = (MyListener) context;
ml.callback(this, "success");
In activity implements MyListener than callback method override there and than you get performed action from fragment to activity.
I made an app and so far i stored captured images in database. Then I split them in categories and showed them in different GridViews for each category. I managed to show them in differents ImageViews after i choose an image from each gridView. Now i was trying to take those choosen images and save them in database and then show them in ListView. The problem is that in the list there is nothing. I suppose that my mistake is in the part of the code that i am taking the images to save them.
Any help?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
handler2 = new DatabaseHandler(getApplicationContext());
Intent i = getIntent();
ImageView im1 = (ImageView) findViewById(R.id.im1);
im1.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image1")));
ImageView im2 = (ImageView) findViewById(R.id.im2);
im2.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image2")));
ImageView im3 = (ImageView) findViewById(R.id.im3);
im3.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image3")));
ImageView im4 = (ImageView) findViewById(R.id.im4);
im4.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image4")));
ImageView im5 = (ImageView) findViewById(R.id.im5);
im5.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image5")));
ImageView im6 = (ImageView) findViewById(R.id.im6);
im6.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image6")));
ImageButton btn_save_outfit = (ImageButton)findViewById(R.id.btn_combine);
btn_save_outfit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Outfits outfits = new Outfits();
outfits.setImage1(i1);
outfits.setImage2(i2);
outfits.setImage3(i3);
outfits.setImage4(i4);
outfits.setImage5(i5);
outfits.setImage6(i6);
Boolean added = handler2.addOutfit(outfits);
if(added){
Toast.makeText(getApplicationContext() , "Outfit added." , Toast.LENGTH_LONG).show();
String log = "Id: "+ outfits.getID()+" ,Image1: " + outfits.getImage1() + " ,Image2: " + outfits.getImage2()
+ ",Image3:" + outfits.getImage3() + ",Image4:" + outfits.getImage5() + ",Image6:" +outfits.getImage6();
Log.d("Image1: ", log);
}else{
Toast.makeText(getApplicationContext(), "Outfit not added. Please try again", Toast.LENGTH_LONG).show();
}
}});
}
}
Outfits.class
public class Outfits {
private int _id;
private String _image1;
private String _image2;
private String _image3;
private String _image4;
private String _image5;
private String _image6;
public Outfits(){
}
public Outfits(String image1, String image2, String image3, String image4, String image5 ,String image6){
this._image1 = image1;
this._image2 = image2;
this._image3 = image3;
this._image4 = image4;
this._image5 = image5;
this._image6 = image6;
}
// Id
public int getID(){
return _id;
}
public void setID(int id){
this._id = id;
}
// Image1
public String getImage1(){
return this._image1;
}
public void setImage1(String image1){
this._image1 = image1;
}
// Image2
public String getImage2(){
return this._image2;
}
public void setImage2(String image2){
this._image2 = image2;
}
// Image3
public String getImage3(){
return this._image3;
}
public void setImage3(String image3){this._image3 = image3;}
// Image4
public String getImage4(){
return this._image4;
}
public void setImage4(String image4){this._image4 = image4;
}
// Image5
public String getImage5(){
return this._image5;
}
public void setImage5(String image5){
this._image5 = image5;
}
// Image6
public String getImage6(){
return this._image6;
}
public void setImage6(String image6){this._image6 = image6;
}
}
Adapter.class
public class OutfitsAdapter extends BaseAdapter {
private List<Outfits> items;
private Context context;
private LayoutInflater inflater;
public OutfitsAdapter(Context _context, List<Outfits> _items){
inflater = LayoutInflater.from(_context);
this.items = _items;
this.context = _context;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Outfits outfits = items.get(position);
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.outfit_item, null);
ImageView i1 = (ImageView) view.findViewById(R.id.image1);
ImageView i2 = (ImageView) view.findViewById(R.id.image2);
ImageView i3 = (ImageView) view.findViewById(R.id.image3);
ImageView i4 = (ImageView) view.findViewById(R.id.image4);
ImageView i5 = (ImageView) view.findViewById(R.id.image5);
ImageView i6 = (ImageView) view.findViewById(R.id.image6);
i1.setImageBitmap(BitmapFactory.decodeFile(outfits.getImage1()));
i2.setImageBitmap(BitmapFactory.decodeFile(outfits.getImage2()));
i3.setImageBitmap(BitmapFactory.decodeFile(outfits.getImage3()));
i4.setImageBitmap(BitmapFactory.decodeFile(outfits.getImage4()));
i5.setImageBitmap(BitmapFactory.decodeFile(outfits.getImage5()));
i6.setImageBitmap(BitmapFactory.decodeFile(outfits.getImage6()));
}
return view;
}
}
Database.class
public List<Outfits> readAllOutfits(){
SQLiteDatabase db = this.getWritableDatabase();
List<Outfits> outfits = new ArrayList<Outfits>();
Cursor cursor = db.query(SQLITE_TABLE_2, columns_2, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Outfits out = new Outfits();
out.setID(Integer.parseInt(cursor.getString(0)));
out.setImage1(cursor.getString(1));
out.setImage2(cursor.getString(2));
out.setImage3(cursor.getString(3));
out.setImage4(cursor.getString(4));
out.setImage5(cursor.getString(5));
out.setImage6(cursor.getString(6));
cursor.moveToNext();
}
cursor.close();
return outfits;
}
And the class with the list
public class CurrentOutfits extends Activity {
private List<Outfits> outfits;
private DatabaseHandler handler2;
ListView lv_outfits;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_outfits);
handler2 = new DatabaseHandler(getApplicationContext());
lv_outfits = (ListView) findViewById(R.id.outfits_list);
loadOutfits();
}
private void loadOutfits() {
outfits = handler2.readAllOutfits();
OutfitsAdapter adapter = new OutfitsAdapter(this, outfits);
lv_outfits.setAdapter(adapter);
for (Outfits o : outfits) {
String record = "ID=" + o.getID() + " | Category=" + o.getImage1() + " | " + o.getImage2();
Log.d("Record", record);
}
}
}
The issue is in Database.class you are missing a line check this out
public List<Outfits> readAllOutfits(){
SQLiteDatabase db = this.getWritableDatabase();
List<Outfits> outfits = new ArrayList<Outfits>();
Cursor cursor = db.query(SQLITE_TABLE_2, columns_2, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Outfits out = new Outfits();
out.setID(Integer.parseInt(cursor.getString(0)));
out.setImage1(cursor.getString(1));
out.setImage2(cursor.getString(2));
out.setImage3(cursor.getString(3));
out.setImage4(cursor.getString(4));
out.setImage5(cursor.getString(5));
out.setImage6(cursor.getString(6));
outfits.add(out);//this is the line you missed
cursor.moveToNext();
}
cursor.close();
return outfits;
}
hope it works
I've written an activity which loads all contacts of the phone and displays it at once in a ListView. The thing is, it takes time to load 400+ contacts and this is not very user friendly. Can anyone point me how can i make this activity run in the background\run faster, I've tried to use AsyncTask but apparently it uses a class rather and not an activity. Any advice is greatly appreciated.
Im adding the code so it will be easier to understand how things work for now:
This is the Contacts class:
public class CustomContact
{
private String contactName;
private String contactPhoneNumber;
private boolean selected = false;
public CustomContact()
{
}
public CustomContact(String contactName, String contactPhoneNumber, boolean selected)
{
super();
this.contactName = contactName;
this.contactPhoneNumber = contactPhoneNumber;
this.selected = selected;
}
public String getContactName()
{
return contactName;
}
public void setContactName(String contactName)
{
this.contactName = contactName;
}
public String getContactPhoneNumber()
{
return contactPhoneNumber;
}
public void setContactPhoneNumber(String contactPhoneNumber)
{
this.contactPhoneNumber = contactPhoneNumber;
}
public boolean isSelected()
{
return selected;
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
#Override
public String toString()
{
return contactPhoneNumber + " " + "\u200e" + contactName;
}
}
Now the code of the activity which uses the CustomContacts class:
public class ContactSelectActivity extends Activity
{
MyCustomAdapter dataAdapter = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_select);
//Generate list View from ArrayList
displayListView();
checkButtonClick();
}
private void displayListView()
{
//Array list of countries
ArrayList<CustomContact> contactsList = new ArrayList<CustomContact>();
String[] projection = new String[] {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.LOOKUP_KEY
};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME ;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, projection,
ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"+ ("1") + "'",
null, sortOrder
);
if (cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
while (phones.moveToNext())
{
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
CustomContact customContact = new CustomContact(name, phoneNumber, false);
contactsList.add(customContact);
}
phones.close();
}
}
}
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,R.layout.custom_contact_info, contactsList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
CustomContact contact = (CustomContact) parent.getItemAtPosition(position);
}
});
}
private class MyCustomAdapter extends ArrayAdapter<CustomContact>
{
private ArrayList<CustomContact> contactList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<CustomContact> stateList)
{
super(context, textViewResourceId, stateList);
this.contactList = new ArrayList<CustomContact>();
this.contactList.addAll(stateList);
}
private class ViewHolder
{
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.custom_contact_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
CustomContact _contact = (CustomContact) cb.getTag();
_contact.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
CustomContact contact = contactList.get(position);
holder.code.setText(" (" + contact.getContactName() + ")");
holder.name.setText(contact.getContactPhoneNumber());
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
private void checkButtonClick()
{
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<CustomContact> contactList = dataAdapter.contactList;
for(int i=0;i<contactList.size();i++)
{
CustomContact contact = contactList.get(i);
if(contact.isSelected())
{
responseText.append("\n" + contact.getContactPhoneNumber());
}
}
}
});
}
}