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
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());
CODE:
private static final String CREATE_DETAILEDMEALS = "CREATE TABLE "
+ TABLE_DetailedMeals + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
+ mealsName + " TEXT unique," + categoryId + " INTEGER,"
+ desc + " TEXT," + size + " TEXT,"
+ price + " TEXT" + ")";
public void addDetailedMeals(String name, int catId, String d, String s, String p){
ContentValues values = new ContentValues(1);
values.put(mealsName, name);
values.put(categoryId, catId);
values.put(desc, d);
values.put(size, s);
values.put(price, p);
getWritableDatabase().insert(TABLE_DetailedMeals, null, values);
}
public Cursor getMeals2(int id)
{
Cursor cursor = getReadableDatabase().rawQuery("SELECT Name, Description, Size, Price FROM " + TABLE_DetailedMeals + " WHERE " + categoryId + "=" + String.valueOf(id), null);
return cursor;
}
// ID1 = MEALS
public ArrayList<DetailedMeals> GetDetailedMeals(int ID1)
{
ArrayList<DetailedMeals> list = new ArrayList<DetailedMeals>();
Cursor cursor = getMeals2(ID1);
int i = 0; // Iterator for 'do-while'. While it gets Categories names, it shall catch all the url's from array as well.
if (cursor.moveToFirst())
{
do
{
DetailedMeals cat = new DetailedMeals();
cat.setName(cursor.getString(cursor.getColumnIndex(mealsName))); //mealsName
cat.setDescription(cursor.getString(cursor.getColumnIndex(mealsName)));
cat.setSize(cursor.getString(cursor.getColumnIndex(mealsName)));
cat.setPrice(cursor.getString(cursor.getColumnIndex(mealsName)));
switch (ID1) {
case 1: cat.setImage(PIZZA_image_urls[i]);
break;
case 2: cat.setImage(BEER_image_urls[i]);
break;
default:
break;
}
list.add(cat);
i++;
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
return list;
}
Adapter:
public class DifferentRowAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
FragmentActivity c;
ArrayList<DetailedMeals> MealsList;
private final int MEAL = 0, DETAIL = 1;
public DifferentRowAdapter(FragmentActivity c, ArrayList<DetailedMeals> MealsList) {
this.c = c;
this.MealsList = MealsList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case MEAL:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rec_item, parent, false);
return new mViewHolder(view);
case DETAIL:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.details_item, parent, false);
return new dViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
DetailedMeals object = MealsList.get(position);
if (object != null) {
switch (object.getmType()) {
case MEAL:
((mViewHolder) holder).mNameTextView.setText(object.getName());
Glide.with(c)
.load(MealsList.get(position).getImage())
.diskCacheStrategy(DiskCacheStrategy.ALL) // Saves the media item after all transformations to cache and
// Saves just the original data to cache.
.placeholder(R.mipmap.ic_launcher)
.into(((mViewHolder) holder).img);
break;
case DETAIL:
((dViewHolder) holder).descTextView.setText(object.getDescription());
((dViewHolder) holder).sizeTextView.setText(object.getSize());
((dViewHolder) holder).priceTextView.setText(object.getPrice());
break;
}
}
}
#Override
public int getItemCount() {
if (MealsList == null)
return 0;
return MealsList.size();
}
#Override
public int getItemViewType(int position) {
if (MealsList != null) {
DetailedMeals object = MealsList.get(position);
if (object != null) {
return object.getmType();
}
}
return 0;
}
public class dViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView descTextView;
TextView sizeTextView;
TextView priceTextView;
detailsItemClickListener icl;
public dViewHolder(View itemView) {
super(itemView);
// Get references to desc, size, price
descTextView = (TextView) itemView.findViewById(R.id.desc);
sizeTextView = (TextView) itemView.findViewById(R.id.size);
priceTextView = (TextView) itemView.findViewById(R.id.price);
itemView.setOnClickListener(this);
}
public void setItemClickListener(detailsItemClickListener icl)
{
this.icl = icl;
}
#Override
public void onClick(View v){
this.icl.onItemClick(v, getPosition());
}
}
public class mViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView mNameTextView;
ImageView img;
mealsItemClickListener icl;
public mViewHolder(View itemView) {
super(itemView);
// Get references to image and name.
mNameTextView = (TextView) itemView.findViewById(R.id.name);
img = (ImageView) itemView.findViewById(R.id.category_image);
itemView.setOnClickListener(this);
}
public void setItemClickListener(mealsItemClickListener icl)
{
this.icl = icl;
}
#Override
public void onClick(View v){
this.icl.onItemClick(v, getPosition());
}
}
}
DetailedMeals.class
public class DetailedMeals {
private String name;
private String image;
private String description;
private String size;
private String price;
private int id;
private int mType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public int getmType() {
return mType;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Right now, GetDetailedMeals(..) returns only details name (not name/desc/price/size) ect. and also, it tries to return it before I get recyclerview with only Meal names.
My goal here is: https://img.exs.lv/l/a/lat-deels/fragm_1.png
Change your DifferentRowAdapter extends to RecyclerView.Adapter because the viewholder you are using is within the DifferentRowAdapter.
list.add(cat); in your code you are putting a DetailedMeals in a DiffRowAdapter list
So change the
public ArrayList<DifferentRowAdapter> GetDetailedMeals(int ID1)
to
public ArrayList<DetailedMeals> GetDetailedMeals(int ID1)
to have a same list and adapter.
then put result hear to know what happens.
Update:
after changing them you have just showing the name in your view so add more items like price or desc in mViewHolder:
public mViewHolder(View itemView) {
super(itemView);
// Get references to image and name.
mNameTextView = (TextView) itemView.findViewById(R.id.name);
// Add them hear
mPriceTextView = (TextView) itemView.findViewById(R.id.price);
mDescTextView = (TextView) itemView.findViewById(R.id.desc);
img = (ImageView) itemView.findViewById(R.id.category_image);
itemView.setOnClickListener(this);
}
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);
}
First of all the viewpage preload the next page and previous page. So if I currently view the PageB , it actually store the Page A and Page C view as well.
And it caused the problem. When I am in pageB, I press a onClickListener on it, it get the position of pageC, also, I would like to change one of the imageview at pageB, but after I press on the button , it turn out change the image view in pageC.
Here is the code snippet, I extended the PagerAdapter
public class CustomPagerAdapter extends PagerAdapter {
private ArrayList<Item> items;
private LinearLayout rootView;
private NetworkImageView album;
private ImageView left;
private ImageView right;
private int imagePos;
private String[] img;
private WebView mWebView;
private ImageView i;
private ImageView i2;
private WebView fbLikeBtn;
private WebView sinaLikeBtn;
private String type;
private TextView report;
private TextView id;
private TextView name;
private TextView age_brand;
private TextView gender_model;
private TextView feature;
private TextView remarks;
private TextView location;
private TextView date;
private TextView reward;
private ImageView find;
private ImageView email;
private ImageView call;
private ImageView share;
private ImageView gps;
private ImageView play_record;
private Item item;
private String isComplete;
private LinearLayout reward_layout;
private DownloadManager mgr;
private boolean isStartPlay;
private MediaPlayer myPlayer;
private BroadcastReceiver onComplete;
private String intent_type_string;
private String intent_type;
private String intent_msg;
public CustomPagerAdapter(ArrayList<Item> items) {
this.items = items;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
rootView = (LinearLayout) LayoutInflater.from(ctx).inflate(R.layout.item_detail, null);
item = (Item) items.get(position);
album = (NetworkImageView) rootView.findViewById(R.id.img);
left = (ImageView) rootView.findViewById(R.id.left);
right = (ImageView) rootView.findViewById(R.id.right);
share = (ImageView) rootView.findViewById(R.id.share);
find = (ImageView) rootView.findViewById(R.id.find);
email = (ImageView) rootView.findViewById(R.id.email);
call = (ImageView) rootView.findViewById(R.id.call);
gps = (ImageView) rootView.findViewById(R.id.gps);
report = (TextView) rootView.findViewById(R.id.report);
id = (TextView) rootView.findViewById(R.id.id);
name = (TextView) rootView.findViewById(R.id.name);
age_brand = (TextView) rootView.findViewById(R.id.age_brand);
gender_model = (TextView) rootView.findViewById(R.id.gender_model);
feature = (TextView) rootView.findViewById(R.id.feature);
remarks = (TextView) rootView.findViewById(R.id.remarks);
location = (TextView) rootView.findViewById(R.id.location);
date = (TextView) rootView.findViewById(R.id.date);
reward = (TextView) rootView.findViewById(R.id.reward);
play_record = (ImageView) rootView.findViewById(R.id.play_record);
reward_layout = (LinearLayout) rootView.findViewById(R.id.reward_layout);
name.setText(getResources().getString(R.string.name) + item.name);
imagePos = 0;
if (item.image_url != null) {
img = new String[item.image_url.length];
for (int i = 0; i < item.image_url.length; i++) {
img[i] = item.image_url[i];
}
if (img.length == 1) {
album.setImageUrl(Constant.request_imageFolder + item.user_id + "/" + item.image_url[0], mImageLoader);
left.setVisibility(View.GONE);
right.setVisibility(View.GONE);
} else {
album.setImageUrl(Constant.request_imageFolder
+ item.user_id + "/" + item.image_url[0],
mImageLoader);
left.setVisibility(View.GONE);
left.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (imagePos != 0) {
imagePos--;
right.setVisibility(View.VISIBLE);
album.setImageUrl(Constant.request_imageFolder
+ item.user_id + "/"
+ item.image_url[imagePos],
mImageLoader);
if (imagePos == 0)
left.setVisibility(View.GONE);
}
}
});
right.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (imagePos != item.image_url.length - 1) {
imagePos++;
left.setVisibility(View.VISIBLE);
album.setImageUrl(Constant.request_imageFolder
+ item.user_id + "/"
+ item.image_url[imagePos],
mImageLoader);
if (imagePos == item.image_url.length - 1)
right.setVisibility(View.GONE);
}
}
});
}
album.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
item = (Item) items.get(position);
Intent intent = new Intent(ctx, Zoom.class);
intent.putExtra("photo_list", item.image_url);
intent.putExtra("pos", imagePos);
intent.putExtra("user_id", item.user_id);
startActivity(intent);
}
});
} else {
album.setDefaultImageResId(R.drawable.image_null);
album.setImageResource(R.drawable.image_null);
left.setVisibility(View.GONE);
right.setVisibility(View.GONE);
}
gps.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
item = (Item) items.get(position);
Intent intent = new Intent(ctx, MapSingle.class);
intent.putExtra("msg", "ID:" + item.id + " " + intent_type_string + " - " + item.name);
intent.putExtra("lat", item.lat);
intent.putExtra("lng", item.lng);
intent.putExtra("type", intent_type_string);
startActivity(intent);
}
});
container.addView(rootView);
return rootView;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return items.size();
}
}
In the code variable album is the target to change image at, while variable left and right is the switch button. Thanks a lot
Your issue is that a ViewPager will create multiple pages at a time (by default, one before the currently viewed page, and one after). So your references would point to the last page created.
Ideally, you should have a custom view for each page, which will have its own references.
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());
}
}
}
});
}
}