Android VeiwFlow load images from SdCard - android

I'm using an implementation of ViewFlow example for my application where I have to swipe images from SdCard. With the code I'm using I can swipe images, but it's showing only one and i'm trying to set the whole images from my SdCard specific folder in the ViewFlow, but that's the problem that I have. I'm getting the path to the image by an ID which I get from sqlite database and depending on that I want to add these images to the view. So this is the code which I'm using for now :
My Cards.class :
package com.stampii.stampii.cards;
import java.util.ArrayList;
import java.util.HashMap;
import com.stampii.stampii.R;
import com.stampii.stampii.comm.rpc.UserDatabaseHelper;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class Cards extends Activity {
public Cursor cursor;
int position;
int indexxx;
Bitmap b;
int objectId;
int cardsId;
ArrayList<HashMap<Integer, String>> imgpaths;
ArrayList<Integer> ids;
String path;
int mediaType=5001;
private ViewFlow viewFlow;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.circle_layout);
UserDatabaseHelper userDbHelper = new UserDatabaseHelper(this, null, 1);
userDbHelper.initialize(this);
imgpaths = new ArrayList<HashMap<Integer, String>>();
HashMap<Integer, String> hm = new HashMap<Integer, String>();
ids = new ArrayList<Integer>();
final int cardId = getIntent().getIntExtra("card_id",0);
Log.i("Card Id ","Card Id : "+cardId);
final int collId = getIntent().getIntExtra("collection_id",0);
Log.i("Collection Id ","Collection Id : "+collId);
position = getIntent().getIntExtra("position",0);
Log.i("position","position : "+position);
String cardSQL = "SELECT cm.cardId, cm.objectId "+
"FROM cardmedias AS cm "+
"INNER JOIN cards AS cd "+
"ON (cm.cardId = cd.objectId) "+
"WHERE cd.collectionId="+collId +" AND cm.mediaType="+mediaType;
Cursor cards = userDbHelper.executeSQLQuery(cardSQL);
if (cards.getCount() == 0) {
Log.i("", "No Image file");
cards.close();
} else if (cards.getCount() > 0) {
for (cards.move(0); cards.moveToNext(); cards.isAfterLast()) {
cardsId = Integer.parseInt(cards.getString(cards
.getColumnIndex("objectId")));
//Log.i("", "cards objectId : " + cardsId);
String path = Environment.getExternalStorageDirectory()
+ "/.Stampii/MediaCard/" + cardsId + ".png";
//Log.i("", "path : " + path);
ids.add(cardsId);
hm.put(cardsId, path);
}
}
String sql = "SELECT objectId FROM cardmedias WHERE cardId=" + cardId
+ " LIMIT 1";
Cursor cursor = userDbHelper.executeSQLQuery(sql);
if (cursor.getCount() == 0) {
Log.i("", "No Image file");
cursor.close();
} else if (cursor.getCount() > 0) {
cursor.moveToFirst();
objectId = Integer.parseInt(cursor.getString(cursor
.getColumnIndex("objectId")));
Log.i("", "objectId : " + objectId);
path = hm.get(objectId);
Log.i("","path : "+hm.get(objectId));
Log.i("","hm size : "+hm.size());
}
Button info = (Button) findViewById(R.id.info_button);
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Cards.this, SingleCardInfo.class);
intent.putExtra("card_id", cardId);
intent.putExtra("collection_id", collId);
startActivity(intent);
}
});
Button back = (Button) findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
final ArrayList<Bitmap> images = new ArrayList<Bitmap>();
for(int i=0;i<=2;i++){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
Bitmap b = BitmapFactory.decodeFile(hm.get(objectId), options);
Log.i("","path : "+hm.get(objectId));
images.add(b);
}
viewFlow = (ViewFlow) findViewById(R.id.viewflow);
viewFlow.setAdapter(new ImageAdapter(this, images),position);
ImageButton prevBtn = (ImageButton) findViewById(R.id.previous_button);
prevBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
indexxx = viewFlow.getSelectedItemPosition()-1;
if (indexxx>=0) {
viewFlow.setAdapter(new ImageAdapter(Cards.this, images),indexxx);
viewFlow.setSelectedItemPosition(indexxx);
Log.i("indexxx", "indexxx : " + indexxx);
}
}
});
ImageButton nextBtn = (ImageButton) findViewById(R.id.next_button);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
indexxx = viewFlow.getSelectedItemPosition()+1;
if (indexxx<images.size()) {
viewFlow.setAdapter(new ImageAdapter(Cards.this, images),indexxx);
viewFlow.setSelectedItemPosition(indexxx);
Log.i("indexxx", "indexxx : " + indexxx);
}
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
viewFlow.onConfigurationChanged(newConfig);
}
}
And my ImageAdapter class :
package com.stampii.stampii.cards;
import java.util.ArrayList;
import com.stampii.stampii.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<Bitmap> ids = new ArrayList<Bitmap>();
//private Bitmap bitmap;
public ImageAdapter(Context context, ArrayList<Bitmap> images) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ids = images;
}
#Override
public int getCount() {
return ids.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) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.image_item, null);
}
((ImageView) convertView.findViewById(R.id.imgView)).setImageBitmap(ids.get(position));
return convertView;
}
}
So my question is how can I add all images from my SdCard folder to this ViewFlow example when I had the path to these images. I've tried to load all of them, but in some cases the images are too much and it's throwing me an outofmemoryException, that's why I think it's better just to set the paths to them. So any help or suggestions are welcomed!
Thanks in advance!
Here is code of ViewFlow.class : ViewFlow

You can try something like this :
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> ids = new ArrayList<String>();
//private Bitmap bitmap;
public ImageAdapter(Context context, ArrayList<String> images) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ids = images;
}
#Override
public int getCount() {
return ids.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) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.image_item, null);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[8*1024];
Bitmap ops = BitmapFactory.decodeFile(ids.get(position), options);
((ImageView) convertView.findViewById(R.id.imgView)).setImageBitmap(ops);
return convertView;
}
}
And :
public class Cards extends Activity {
public Cursor cursor;
int position;
int indexxx;
Bitmap b;
int objectId;
int cardsId;
ArrayList<Integer> ids;
String path;
int mediaType=5001;
ArrayList<String> images;
int card;
private ViewFlow viewFlow;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.circle_layout);
UserDatabaseHelper userDbHelper = new UserDatabaseHelper(this, null, 1);
userDbHelper.initialize(this);
//imgpaths = new ArrayList<HashMap<Integer, String>>();
HashMap<Integer, String> hm = new HashMap<Integer, String>();
ids = new ArrayList<Integer>();
images = new ArrayList<String>();
final int cardId = getIntent().getIntExtra("card_id",0);
Log.i("Card Id ","Card Id : "+cardId);
final int collId = getIntent().getIntExtra("collection_id",0);
Log.i("Collection Id ","Collection Id : "+collId);
position = getIntent().getIntExtra("position",0);
Log.i("position","position : "+position);
String cardSQL = "SELECT cm.cardId, cm.objectId "+
"FROM cardmedias AS cm "+
"INNER JOIN cards AS cd "+
"ON (cm.cardId = cd.objectId) "+
"WHERE cd.collectionId="+collId +" AND cm.mediaType="+mediaType;
Cursor cards = userDbHelper.executeSQLQuery(cardSQL);
if (cards.getCount() == 0) {
Log.i("", "No Image file");
cards.close();
} else if (cards.getCount() > 0) {
for (cards.move(0); cards.moveToNext(); cards.isAfterLast()) {
cardsId = Integer.parseInt(cards.getString(cards
.getColumnIndex("objectId")));
card = Integer.parseInt(cards.getString(cards
.getColumnIndex("cardId")));
String path = Environment.getExternalStorageDirectory()
+ "/.Stampii/MediaCard/" + cardsId + ".png";
ids.add(card);
hm.put(cardsId, path);
path = hm.get(cardsId);
Log.i("","path : "+hm.get(cardsId));
Log.i("","hm size : "+hm.size());
images.add(path);
}
}
Button back = (Button) findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
viewFlow = (ViewFlow) findViewById(R.id.viewflow);
viewFlow.setAdapter(new ImageAdapter(this, images),position);
ImageButton prevBtn = (ImageButton) findViewById(R.id.previous_button);
prevBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
indexxx = viewFlow.getSelectedItemPosition()-1;
if (indexxx>=0) {
viewFlow.setAdapter(new ImageAdapter(Cards.this, images),indexxx);
viewFlow.setSelectedItemPosition(indexxx);
Log.i("indexxx", "indexxx : " + indexxx);
}
}
});
ImageButton nextBtn = (ImageButton) findViewById(R.id.next_button);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
indexxx = viewFlow.getSelectedItemPosition()+1;
if (indexxx<images.size()) {
viewFlow.setAdapter(new ImageAdapter(Cards.this, images),indexxx);
viewFlow.setSelectedItemPosition(indexxx);
Log.i("indexxx", "indexxx : " + indexxx);
}
}
});
Button info = (Button) findViewById(R.id.info_button);
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Cards.this, SingleCardInfo.class);
intent.putExtra("card_id", ids.get(position));
intent.putExtra("collection_id", collId);
startActivity(intent);
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
viewFlow.onConfigurationChanged(newConfig);
}
}
That should do the trick!

Related

listview effecting multiple rows 4th,7th,10th

i have a custom listview and custom adapter. each row has multiple items inside it, when i click on like button it change the color of imageview but it also effect the 4th,7th and 10th row.
after searching on internet i learned that i have to use getTag and setTag but i dont know how to use it.
please help me in understanding the concept of getTag and setTag and solving this error.
here is my code:-
package rj.osmthemes;
import java.util.ArrayList;
import android.content.Context;
import android.os.Build;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import static android.R.attr.data;
import static rj.osmthemes.R.id.downlink;
import static rj.osmthemes.R.id.likebtn;
import static rj.osmthemes.R.id.likecount;
public class ListAdapter extends ArrayAdapter<DataModel> {
customButtonListener customListner;
private ArrayList<DataModel> dataSet;
public String temp1;
public interface customButtonListener {
public void onButtonClickListner(int position,String value);
public void onImageClickListner(int position,String value);
public void onlikeImageClickListner(int position,String value);
public void ondislikeImageClickListner(int position,String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
//private ArrayList<String> data = new ArrayList<String>();
public ListAdapter(ArrayList<DataModel> data, Context context) {
super(context, R.layout.list_layout, data);
this.dataSet = data;
this.context = context;
}
private int lastPosition = -1;
// public ListAdapter(Context context, ArrayList<String> dataItem) {
// super(context, R.layout.list_layout, dataItem);
// this.data = dataItem;
// this.context = context;
// }
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final DataModel dataModel = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_layout, null);
viewHolder = new ViewHolder();
viewHolder.themename = (TextView) convertView.findViewById(R.id.themename);
viewHolder.madeby = (TextView) convertView.findViewById(R.id.madeby);
viewHolder.downcount = (TextView) convertView.findViewById(R.id.downcount);
viewHolder.likecount = (TextView) convertView.findViewById(likecount);
viewHolder.dislikecount = (TextView) convertView.findViewById(R.id.dislikecount);
viewHolder.ss1 = (ImageView) convertView.findViewById(R.id.img1);
viewHolder.ss2 = (ImageView) convertView.findViewById(R.id.img2);
viewHolder.ss3 = (ImageView) convertView.findViewById(R.id.img3);
viewHolder.likebtn = (ImageView) convertView.findViewById(likebtn);
viewHolder.dislikebtn = (ImageView) convertView.findViewById(R.id.dislikebtn);
viewHolder.btndownload = (Button) convertView.findViewById(downlink);
convertView.setTag(viewHolder);
final String temp = getItem(position).toString();
viewHolder.likebtn.setTag(temp);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
lastPosition = position;
//final String temp = getItem(position).toString();
// viewHolder.tempid = Integer.parseInt(dataModel.getId());
final String ss1link,ss2link,ss3link,downlink;
viewHolder.themename.setText(dataModel.getTheme_name());
viewHolder.madeby.setText(dataModel.getMade_by());
viewHolder.downcount.setText(dataModel.getDown_count());
viewHolder.likecount.setText(dataModel.getLike_count());
viewHolder.dislikecount.setText(dataModel.getDislike_count());
ss1link = dataModel.getSs1();
ss2link = dataModel.getSs2();
ss3link = dataModel.getSs3();
downlink = dataModel.getDown_link();
// viewHolder.text.setText(temp);
viewHolder.btndownload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
int downcounttmp = Integer.parseInt(dataModel.getDown_count());
downcounttmp++;
viewHolder.downcount.setText(""+downcounttmp);
String name = downlink + "#" + dataModel.getTheme_name() + "#" + dataModel.getId() + "#" + downcounttmp;
customListner.onButtonClickListner(position,name);
}
}
});
viewHolder.ss1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss1link);
}
}
});
viewHolder.ss2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss2link);
}
}
});
viewHolder.ss3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss3link);
}
}
});
viewHolder.likebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
// Toast.makeText(context, dataModel.getId() + " { " ,Toast.LENGTH_LONG).show();
if(viewHolder.check == 0){
int likecount = Integer.parseInt(dataModel.getLike_count());
likecount++;
viewHolder.likecount.setText(""+likecount);
String name = likecount + "#" + dataModel.getId();
// Toast.makeText(context,position + " " + temp,Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.likebtn.setImageResource(R.drawable.ic_thumb_up_red_24dp);
//viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp));
viewHolder.check = 1;
}
customListner.onlikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
viewHolder.dislikebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
if(viewHolder.check == 0) {
int dislikecount = Integer.parseInt(dataModel.getDislike_count());
dislikecount++;
viewHolder.dislikecount.setText(""+dislikecount);
String name = dislikecount + "#" + dataModel.getId();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp));
viewHolder.check = 1;
}
customListner.ondislikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
Glide
.with(context)
.load(ss1link)
.into(viewHolder.ss1);
Glide
.with(context)
.load(ss2link)
.into(viewHolder.ss2);
Glide
.with(context)
.load(ss3link)
.into(viewHolder.ss3);
return convertView;
}
public class ViewHolder {
TextView themename,madeby,downcount,likecount,dislikecount;
Button btndownload;
ImageView ss1,ss2,ss3,likebtn,dislikebtn;
int check = 0, tempid = 0;
}
}
This is because of object reuse in your list view.
You can manage separate ArrayList or HashMap to maintain your likes.
And based on that you should update in your getView like this,
if([already selected]) {
viewHolder.likebtn.setBackground([your selected drawable]);
} else {
viewHolder.likebtn.setBackground([your non selected drawable]);
}

First time SharedPreferences use with GridView

This is my Apps Screenshoot :
There is two button in that GridView : +/-.
So what im gonna try is when i press "+" button or "-" button, the quantity is store in SharedPreferences.
But really im confused about this.
This is my code so far :
package com.android.customer_blanjapasar.Utility;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.customer_blanjapasar.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Leon on 5/3/2016.
*/
public class CustomGridView2 extends BaseAdapter {
private ArrayList<ListItem> listData;
private LayoutInflater layoutInflater;
private Context context;
private String[] imageUrls;
private int count = 0;
int arrayCount[];
SharedPreferences prefs ;
SharedPreference sharedPreference;
public CustomGridView2(Context context, ArrayList<ListItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
this.context = context;
sharedPreference = new SharedPreference();
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.afterlogin_product_gridview, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.nama_produk);
holder.teaserView = (TextView) convertView.findViewById(R.id.harga);
holder.imageView = (ImageView) convertView.findViewById(R.id.img_produk);
holder.cmdMinus = (Button) convertView.findViewById(R.id.btn_min);
holder.cmdPlus = (Button) convertView.findViewById(R.id.btn_plus);
holder.qty = (TextView) convertView.findViewById(R.id.lbl_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListItem newsItem = listData.get(position);
String satuan = newsItem.getSatuan().toString();
String harga = newsItem.getReporterName().toString();
harga = "Rp. " + harga + " / " + satuan;
holder.headlineView.setText(newsItem.getHeadline().toUpperCase());
holder.teaserView.setText(harga);
String a = newsItem.getUrl();
holder.cmdPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = Integer.parseInt( holder.qty.getText().toString());
count++;
holder.qty.setText(""+count);
}
});
holder.cmdMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = Integer.parseInt( holder.qty.getText().toString());
if(count == 0) {
holder.qty.setText("0");
}
else {
count--;
holder.qty.setText("" + count);
}
}
});
if (holder.imageView != null) {
//new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
Picasso
.with(context)
.load(a)
.fit()
.into(holder.imageView);
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView teaserView;
ImageView imageView;
TextView satuan,qty;
Button cmdPlus,cmdMinus;
}
}
I already see this tutorial. But im still getting confused. Please guide me step by step.
EDIT
This is ListItem.class :
public class ListItem {
private String headline;
private String reporterName;
private String kode;
private String url;
private String satuan;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
public String getReporterName() {
return reporterName;
}
public void setReporterName(String reporterName) {
this.reporterName = reporterName;
}
public String getKode() {
return kode;
}
public void setKode(String kode) {
this.kode = kode;
}
public String getSatuan() {
return satuan;
}
public void setSatuan(String satuan) {
this.satuan = satuan;
}
#Override
public String toString() {
return "[ headline=" + headline + ", reporter Name=" + reporterName + " , date=" + kode + "]";
}
}
And this is the code inside MainActivity.class :
public class AfterLogin_Produk extends Activity {
Activity activity;
ImageButton btn_resep,btn_product;
static int jArray;
GridView product_gridview;
static String[] nama_prdct;
static String[] img_prdct;
static String[] harga_prdct;
static String[] satuan_prdct;
static String kode_ktgr;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.after_login_produk_main);
product_gridview = (GridView) findViewById(R.id.product_gridview);
new GetLength().execute();
}
public ArrayList<ListItem> getListData() {
ArrayList<ListItem> listMockData = new ArrayList<ListItem>();
for (int i = 0; i < jArray; i++) {
ListItem newsData = new ListItem();
newsData.setUrl(img_prdct[i]);
newsData.setHeadline(nama_prdct[i]);
newsData.setReporterName(harga_prdct[i]);
newsData.setSatuan(satuan_prdct[i]);
listMockData.add(newsData);
}
return listMockData;
}
class GetLength extends AsyncTask<String, String, String> {
String nama_product,img_product,harga_product,satuan_product;
JSONParser2 jParser = new JSONParser2();
ArrayList<String> list_nama_produk = new ArrayList<String>();
ArrayList<String> list_img_produk = new ArrayList<String>();
ArrayList<String> list_harga_produk = new ArrayList<String>();
ArrayList<String> list_satuan_produk = new ArrayList<String>();
protected String doInBackground(String... params) {
try {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("kode_kategori", kode_ktgr));
JSONObject json = jParser.makeHttpRequest("http:xxx.php", "POST", param);
JSONArray array = json.getJSONArray("categories");
jArray = array.length();
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
nama_product = row.getString("nama_produk");
img_product = row.getString("img_produk");
harga_product = row.getString("harga_satuan");
satuan_product = row.getString("nama_satuan");
list_nama_produk.add(nama_product);
list_img_produk.add(img_product);
list_harga_produk.add(harga_product);
list_satuan_produk.add(satuan_product);
}
} catch (Exception e) {
System.out.println("Exception : " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Toast.makeText(getBaseContext(),"Value : " + list_nama_kategori,Toast.LENGTH_SHORT).show();
nama_prdct = new String[list_nama_produk.size()];
img_prdct = new String[list_img_produk.size()];
harga_prdct = new String[list_harga_produk.size()];
satuan_prdct = new String[list_satuan_produk.size()];
nama_prdct = list_nama_produk.toArray(nama_prdct);
img_prdct = list_img_produk.toArray(img_prdct);
harga_prdct = list_harga_produk.toArray(harga_prdct);
satuan_prdct = list_satuan_produk.toArray(satuan_prdct);
ArrayList<ListItem> listData = getListData();
product_gridview.setAdapter(new CustomGridView2(AfterLogin_Produk.this, listData));
}
}
you are using custom array list of object than set propertie to it and on back press of application you can jsonify your object to string and store it in shared preference and at activity on create you can regenerate your object getting from shared preference. in activity onCreate()
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
(Dashboard.this);
String data = mSettings.getString("data", "");
/* Should Activity Check for Updates Now? */
if ((data.equals(""))) {
//do nothing data is not in shared preference
}
else {
//data is there convert To object
data=mSettings.getString("data", "");
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
ArrayList<ListRowItem> listRowItems = new Gson().fromJson(data, listType);
//setAdapter coming for arrayList as usual.
}
and in backPressed you can read data from adapter and jsonify it using json and put it in sharedPreference
i hope you understand the login . clear preference after data set.
Your issue is here:
holder.qty.setText(store);
It is clearly pointed out in your error log:
android.content.res.Resources$NotFoundException: String resource ID
0x1 at android.content.res.Resources.getText(Resources.java:1409) at android.widget.TextView.setText(TextView.java:4943)
store is an integer and setText is trying to look for a resource with this id. Use this instead.
holder.qty.setText(store.toString());
Also, to reduce the complexity of shared preferences specific code you can use this library

Odd behavior in adding items to listview

I have a custom photo gallery and I need to get the selected images and display their filenames in a listview
This is my custom gallery:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class CustomPhotoGallery extends Activity {
private GridView grdImages;
private Button btnSelect;
private ImageAdapter imageAdapter;
private String[] arrPath;
private boolean[] thumbnailsselection;
private int ids[];
private int count;
String filename;
/**
* Overrides methods
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_gallery);
grdImages= (GridView) findViewById(R.id.grdImages);
btnSelect= (Button) findViewById(R.id.btnSelect);
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
#SuppressWarnings("deprecation")
Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.arrPath = new String[this.count];
ids = new int[count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
ids[i] = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
imageAdapter = new ImageAdapter();
grdImages.setAdapter(imageAdapter);
imagecursor.close();
btnSelect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
for (int i = 0; i < len; i++) {
if (thumbnailsselection[i]) {
cnt++;
selectImages = selectImages + arrPath[i] + "|";
}
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
} else {
Log.d("SelectedImages", selectImages);
Intent i = new Intent();
i.putExtra("data", selectImages);
setResult(Activity.RESULT_OK, i);
finish();
}
}
});
}
#Override
public void onBackPressed() {
setResult(Activity.RESULT_CANCELED);
super.onBackPressed();
}
/**
* Class method
*/
/**
* This method used to set bitmap.
* #param iv represented ImageView
* #param id represented id
*/
private void setBitmap(final ImageView iv, final int id) {
new AsyncTask<Void, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(Void... params) {
return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
iv.setImageBitmap(result);
}
}.execute();
}
/**
* List adapter
* #author tasol
*/
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.custom_gallery_item, null);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
holder.chkImage = (CheckBox) convertView.findViewById(R.id.chkImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.chkImage.setId(position);
holder.imgThumb.setId(position);
holder.chkImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id]) {
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.imgThumb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int id = holder.chkImage.getId();
if (thumbnailsselection[id]) {
holder.chkImage.setChecked(false);
thumbnailsselection[id] = false;
} else {
holder.chkImage.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
try {
setBitmap(holder.imgThumb, ids[position]);
} catch (Throwable e) {
}
holder.chkImage.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
/**
* Inner class
* #author tasol
*/
class ViewHolder {
ImageView imgThumb;
CheckBox chkImage;
int id;
}
}
Now the result based on selection goes to main activity where I need to display all the selected images in a listview.
This is what I'm trying to do
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_MULTIPLE){
imagesPathList = new ArrayList<String>();
String[] imagesPath = data.getStringExtra("data").split("\\|");
try{
lnrImages.removeAllViews();
}catch (Throwable e){
e.printStackTrace();
}
for (int i=0;i<imagesPath.length;i++){
//Toast.makeText(MainActivity.this,String.valueOf(imagesPath.length),Toast.LENGTH_LONG).show();
imagesPathList.add(imagesPath[i]);
//Toast.makeText(MainActivity.this,imagesPathList.toString(),Toast.LENGTH_LONG).show();
yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourbitmap);
imageView.setAdjustViewBounds(true);
//lnrImages.addView(imageView);
Uri uri = (Uri.fromFile(new File(imagesPath[i])));
filename = uri.getLastPathSegment();
//Toast.makeText(MainActivity.this,filename,Toast.LENGTH_LONG).show();
Uri selectedImage = data.getData();
encodedImage= bitmapToBase64(yourbitmap);
//Toast.makeText(MainActivity.this,encodedImage,Toast.LENGTH_LONG).show();
myStringList.add(filename);
myStringArray = myStringList.toArray();
lv.setAdapter(null);
Toast.makeText(MainActivity.this,(String)myStringArray[i],Toast.LENGTH_LONG).show();
arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
myStringList );
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
}
}
}
Now my problem is:
1) If I select one single image it's showing me the toast with the filename but not adding it to the listview
2)If I select two images its adding to the list view as normal
3) If I select more than two its appending to the old list(ie..adding the newly selected images to the previously selected images) though I have set the adapter to 'NULL'
4) Selecting large number of images takes time consumption to adding it to the listview crashing the app due to memory.
So can anyone suggest me the best way of handling this ?
Thanks in Advance!
There are multiple problems in your code. As in Java everything is reference, so instead of creating the adapter again and again, you should only set the new list to the adapter and then should call notifyDataSetChanged. For example, your ImageAdapter should be like this
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> imagesList = new ArrayList<>();
public void updateImagesList(ArrayList<Strinf> newImages) {
if(newImages != null && newImages.size() > 0) {
this.imagesList.clear();
this.imagesList.addAll(newImages);
}
}
}
and then you should create global Adapter variable which we will be using for future list updates
and in your onActivityResult, you should populate the strings list in a loop and then after the loop you should update the adapter list as
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_MULTIPLE) {
for (int i = 0; i < imagesPath.length; i++) {
//Toast.makeText(MainActivity.this,String.valueOf(imagesPath.length),Toast.LENGTH_LONG).show();
imagesPathList.add(imagesPath[i]);
//Toast.makeText(MainActivity.this,imagesPathList.toString(),Toast.LENGTH_LONG).show();
yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourbitmap);
imageView.setAdjustViewBounds(true);
//lnrImages.addView(imageView);
Uri uri = (Uri.fromFile(new File(imagesPath[i])));
filename = uri.getLastPathSegment();
//Toast.makeText(MainActivity.this,filename,Toast.LENGTH_LONG).show();
Uri selectedImage = data.getData();
encodedImage = bitmapToBase64(yourbitmap);
//Toast.makeText(MainActivity.this,encodedImage,Toast.LENGTH_LONG).show();
myStringList.add(filename);
Toast.makeText(MainActivity.this, (String) myStringArray[i], Toast.LENGTH_LONG).show();
}
arrayAdapter.updateImages(myStringList);
arrayAdapter.notifyDataSetChanged();
}
}
}
Apart the above two changes, there is great performance impact because you are all doing I/O operations on Ui Thread as you are decoding Bitmap files on Main thread which is not the good approach as It will cause OutOfMemoryError as well as It will slow down your application. You should do bitmap operations or displaying using Universal Image Loader https://github.com/nostra13/Android-Universal-Image-Loader
Hope this helps.

getActivity() gives context equal to null

I have developed and launched an Android application. It works fine on my Android phone, but it crashes on several devices.
*BugSense gives me the following error:*
0 java.lang.NullPointerException
1 at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
2 at android.widget.ArrayAdapter.(ArrayAdapter.java:128)
3 **at com.challenger.app.ChallengeAdapter.(ChallengeAdapter.java:27)**
4 at com.challenger.app.AllChallenges.fitChallenges(AllChallenges.java:142)
5 at com.challenger.app.AllChallenges$1.onSuccess(AllChallenges.java:108)
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class AllChallenges extends Fragment {
Button loginButton;
ListView listView2, listView1;
TextView textView;
int category = 0;
View view;
List<Challenge> challenge_data;
public AllChallenges(int cat) {
category = cat;
}
public AllChallenges() {
// TODO Auto-generated constructor stub
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
if(getActivity()!=null){
load();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.allchallenges, container, false);
if(getActivity()!=null){
load();
}
return view;
}
public void load() {
loadOld();
if (!AppSettings.refreshed[category + 1]) {
update();
}
}
public void loadOld() {
Log.d("Challenge", "Updating " + category);
JSONArray a = AppSettings.loadChallenges(category, getActivity());
if (a != null) {
fitChallenges(makeArray(a));
}
}
public void update() {
Log.d("Challenge", "getChallenges/" + category);
RequestParams a = new RequestParams();
if (AppSettings.logged) {
a.put("fb_id", AppSettings.facebookId);
a.put("fb_authkey", AppSettings.facebookAuthToken);
}
NetworkClient.receiveJSON("getChallenges/" + category, a,
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray chalList) {
Log.d("Challenge", "Downloaded " + category);
AppSettings.saveChallenges(category, chalList,
getActivity());
fitChallenges(makeArray(chalList));
AppSettings.refreshed[category + 1] = true;
}
});
}
public Challenge[] makeArray(JSONArray list) {
challenge_data = new ArrayList<Challenge>();
try {
for (int i = 0; i < list.length(); i++) {
JSONObject chal = (JSONObject) list.get(i);
String[] arr = {};
if (chal.has("friends"))
arr = JSONArrToArr(chal.getJSONArray("friends"));
Log.e("Boolean", chal.getString("active"));
challenge_data.add(new Challenge(chal.getInt("id"), chal
.getString("title"), chal.getInt("category"), chal
.getInt("taken_by"), arr, chal.getBoolean("active"),
chal.getString("text"), chal.getInt("streak"), chal
.getInt("percentage")));
}
return challenge_data.toArray(new Challenge[challenge_data.size()]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void fitChallenges(Challenge[] chalArray) {
**ChallengeAdapter adapter = new ChallengeAdapter(getActivity(),
R.layout.list_row, chalArray);** //
listView1 = (ListView) view.findViewById(R.id.listView1);
listView1.setAdapter(adapter);
OnItemClickListener listener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("listener", "am ID" + id + "position " + position);
int n = (int) id;
String title = challenge_data.get(n).toStringArray()[1];
Log.i("listener", "am ID" + id + "position " + position
+ " title " + title);
int people = challenge_data.get(n).peopleInt;
String category = challenge_data.get(n).toStringArray()[0];
String description = challenge_data.get(n).toStringArray()[5];
int streak = challenge_data.get(n).streak;
int percentage = challenge_data.get(n).percentage;
int chal_id = challenge_data.get(n).id;
boolean active = challenge_data.get(n).active;
((AllChallengesPager) getActivity()).showDetailed(chal_id,
title, "" + people, category, active, description, ""
+ streak, "" + percentage);
}
};
listView1.setOnItemClickListener(listener);
}
public String[] JSONArrToArr(JSONArray arr) {
String[] newArr = {};
try {
List<String> list = new ArrayList<String>();
for (int i = 0; i < arr.length(); i++) {
list.add(arr.getString(i));
}
newArr = list.toArray(new String[list.size()]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newArr;
}}
public class ChallengeAdapter extends ArrayAdapter<Challenge> {
Context context;
int layoutResourceId;
Challenge data[] = null;
Typeface a;
public ChallengeAdapter(Context context, int layoutResourceId,
Challenge[] data) {
**super(context, layoutResourceId, data);** //in this line code crashes
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
a = Typeface.createFromAsset(context.getAssets(),
"fonts/roboto_condensed.ttf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChallengeHolder holder = null;
Challenge challenge = data[position];
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChallengeHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.list_image);
holder.txtTitle = (TextView) row.findViewById(R.id.challenge);
holder.txtPeople = (TextView) row.findViewById(R.id.peopleNumber);
holder.friendThumbs = (LinearLayout) row
.findViewById(R.id.friendThumbs);
row.setTag(holder);
} else {
holder = (ChallengeHolder) row.getTag();
}
holder.friendThumbs.removeAllViews();
for (int i = 0; i < challenge.friendIds.length; i++) {
holder.friendThumbs.addView(createIcon(challenge.friendIds[i],
context));
}
holder.txtTitle.setText(challenge.title);
holder.txtTitle.setTypeface(a);
holder.imgIcon.setImageResource(challenge.icon);
holder.txtPeople.setText(challenge.peopleString);
return row;
}
static class ChallengeHolder {
public LinearLayout friendThumbs;
ImageView imgIcon;
TextView txtTitle;
TextView txtPeople;
}
public ImageView createIcon(String friendID, Context cont) {
ImageView icon = new ImageView(context);
LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
(int) cont.getResources().getDimension(R.dimen.fbIconSize),
(int) cont.getResources().getDimension(R.dimen.fbIconSize));
par.setMargins(0, 0, 15, 0);
icon.setLayoutParams(par);
Log.e("ID " + friendID, "log");
final String myurl = AppSettings.profilePictureUrl(friendID);
icon.setImageResource(R.drawable.default_fb_icon_small);
((MyApplication) ((Activity) context).getApplication())
.loadImageSimple(myurl, icon);
return icon;
}
}
I guess that the cause of this problem is context equal to null got from the method getActivity, but don't know how to deal with this problem. Could anyone explain how to solve the problem?
I think onActivityCreated method override and implement for this code, and its working fine may be...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(getActivity()!=null){
load();
}
}
And Fragment lifecyle must read for this doc Documentation
Most likely your Fragment is detached from your activity at this stage as this is called in an external thread JsonHttpResponseHandler.
You have a good explanation here:
https://stackoverflow.com/a/11536337/891479
You should not call
if(getActivity()!=null){
load();
}
in onCreateView.
onViewCreated is called after onCreateView and as per the docs
The fragment's view hierarchy is not however attached to its parent
at this point.
I think if I remember correctly its better to use getActivity().getApplicationContext()

Click Event Listeners in a ListActivity [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: How to fire onListItemClick in Listactivity with buttons in list?
i have develop one app in which i have make ListActivity in which custome listview are going to display custom item list.all things are going to well but here i am confuse with itemOnClickListner. how can i add onclick listner in listActivity ? because there are not any listview that initialize and i can set listner trough that listview control... i have find out from here but its also not working for me
:Here is Code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update3
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends Activity implements OnClickListener, OnItemClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
lstFavrowlistv = (ListView)findViewById(R.id.lstFavrowlistv);
lstFavrowlistv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
});
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
lstFavrowlistv.setAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) lstFavrowlistv.getAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
use getListview() in list Activity to get List..........
in Oncreate
ListView lv = getListView();
http://www.mkyong.com/android/android-listview-example/
this link has both ways
1- overriding onListItemClick(
2- Setting you listener..
Try this way..
ListView lv = getListView();
lv. storelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
}
this are help you.
Thanks
Override the function onlistitemclick() for this. Here the integer position represents the postion of item that you had pressed
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
.......
}
Try this one
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
}
});

Categories

Resources