android array adapter changing data - android

Here is my main class and Adapter together
public class MainActivity extends Activity {
public MyAdapter adapter;
private View view;
Context context;
public ListView list;
public int t[];
public SharedPreferences prefs;
public SharedPreferences.Editor edit;
public SharedPreferences preferences;
public SharedPreferences.Editor editor;
int [] btnNums={66,150,94,72,206,489,1481,731,131,91,145,137,662,770};
int [] tuesdaynum={351,14,308,19,134,514,305,68,104,129,62,47,409,630};
int [] wednesdaynum={744,131,184,846,37,336,812,88,1020,1286,1106,551,202,156};
int [] thursdaynum={206,662,731,1281,801,351,117,770,302,526,212,1100,1060,1100};
int [] fridaynum={232,998,209,80,73,270,312,55,110,78,209,114,161,1001};
int [] saturdaynum={20,48,573,319,108,66,116,500,46,68,286,201,256,113};
int [] sundaynum={137,148,56,124,68,490,18,156,14,48,20,86,514,298};
int [] btnNumsrefs={66,150,94,72,206,489,1481,731,131,91,145,137,662,770};
int yesterday;
public void storeYesterday(Calendar a){
yesterday=a.get(Calendar.DAY_OF_MONTH);
preferences=getSharedPreferences("yesterday",0);
editor=preferences.edit();
editor.putInt("yesterday",yesterday);
editor.commit();
}
public Integer getFromYesterday(){
preferences=getSharedPreferences("yesterday",0);
int get =preferences.getInt("yesterday", 0);
return get;
}
int[] images = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9,
R.drawable.a10, R.drawable.a11, R.drawable.a12, R.drawable.a13, R.drawable.a14};
int[] tuesday = {R.drawable.elkahhar, R.drawable.elvehhab, R.drawable.errezzak, R.drawable.elvahid, R.drawable.essamed, R.drawable.elkabid, R.drawable.elkadir, R.drawable.elhakem, R.drawable.eladl,
R.drawable.ellatif, R.drawable.elbatin, R.drawable.elvali, R.drawable.ettevvab, R.drawable.elmuntekim};
int[] wednesday = {R.drawable.elmuktedir, R.drawable.esselam, R.drawable.elmukaddim, R.drawable.elmuaahir, R.drawable.elevvel, R.drawable.elmusavvir, R.drawable.elhabir, R.drawable.elhalim, R.drawable.elazim,
R.drawable.elgafur, R.drawable.ezzahir, R.drawable.elmuteali, R.drawable.elberr, R.drawable.elafuv };
int[] thursday = {R.drawable.elcebbar, R.drawable.elmutekebbir2, R.drawable.elhaliik, R.drawable.elgafffar, R.drawable.ellahir, R.drawable.errafi, R.drawable.elmuiz, R.drawable.elmuzil, R.drawable.elbasir,
R.drawable.essekur, R.drawable.malikulmulk, R.drawable.zulcelalilikram, R.drawable.elganiy, R.drawable.elmugni };
int[] friday = {R.drawable.elkebir, R.drawable.elhafiz, R.drawable.elmukit, R.drawable.elhasib, R.drawable.elcelil, R.drawable.elkerim, R.drawable.elrakib, R.drawable.elmucib, R.drawable.elaliy,
R.drawable.elhakim, R.drawable.elmuksit, R.drawable.elcami, R.drawable.elmani, R.drawable.eddar};
int[] saturday = {R.drawable.elvedud, R.drawable.elmecid, R.drawable.elbais, R.drawable.essehid, R.drawable.elhak, R.drawable.elvekil, R.drawable.elkaviy, R.drawable.elmetin, R.drawable.elveliy,
R.drawable.elhamid, R.drawable.errauf, R.drawable.ennafi, R.drawable.ennur, R.drawable.elbaki};
int[] sunday = {R.drawable.elvasi, R.drawable.elmuhsi, R.drawable.elmubdi, R.drawable.elmuid, R.drawable.elmuhyi, R.drawable.elmumit, R.drawable.elhay, R.drawable.elkayyum, R.drawable.elvacid,
R.drawable.elmacid, R.drawable.elhadi, R.drawable.elbedi, R.drawable.erresid, R.drawable.essabur };
String[] exp;
String[] exp2;
String[] exp3;
String[] exp4;
String[] exp5;
String[] exp6;
String[] exp7;
String[] mean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit= this.getSharedPreferences("NAME", Context.MODE_APPEND).edit();
prefs = getSharedPreferences("NAME", Context.MODE_APPEND);
view=getWindow().getDecorView().getRootView();
Admob.createLoadBanner(getApplicationContext(), view);
Admob.createLoadInterstitial(getApplicationContext(), null);
Resources res=getResources();
exp= res.getStringArray(R.array.names);
exp2= res.getStringArray(R.array.faz2);
exp3= res.getStringArray(R.array.faz3);
exp4= res.getStringArray(R.array.faz4);
exp5= res.getStringArray(R.array.faz5);
exp6= res.getStringArray(R.array.faz6);
exp7= res.getStringArray(R.array.faz7);
mean=res.getStringArray(R.array.anlam);
list= (ListView) findViewById(R.id.listView);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
Calendar cal2=Calendar.getInstance();
cal2.setTime(new Date());
int today = cal.get(Calendar.DAY_OF_MONTH);
if(today==Calendar.Monday){
adapter.setData(this,exp3,thursday,mean,thursdaynum);
}else if(today==Calendar.TUESDAY){
adapter.clear();
adapter=new MyAdapter(this,exp2,tuesday,mean,tuesdaynum);
}//goes on
if(getFromYesterday()==null){
storeYesterday(cal);
}else {
if(today!=getFromYesterday()) {
storeYesterday(cal);
adapter = new MyAdapter(this, exp, images, mean, t);
storeYesterday(cal);
edit.putInt("Count", btnNumsrefs.length);
int count = 0;
for (int i : btnNums) {
edit.putInt("IntValue_" + count++, i);
}
}
edit.commit();
}
int[] ret;
Integer count1 = prefs.getInt("Count", 0);
if(count1!=null) {
ret = new int[count1];
for (int i = 0; i < count1; i++) {
ret[i] = prefs.getInt("IntValue_" + i, i);
t=ret;
}
}
if(t!=null)
{
adapter = new MyAdapter(this, exp, images, mean, t);
}else
{
adapter = new MyAdapter(this, exp, images, mean, btnNums);
}
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
context=getApplicationContext();
}
}
class MyAdapter extends ArrayAdapter<String>{
int [] images;
String [] titleArray;
String [] descriptionArray;
int [] btnNums;
MainActivity ma;
public MyAdapter(MainActivity m, String[] titles, int imgs[], String[] descp, int[] btnNum ){
super(m, R.layout.single_row, R.id.textView,titles);
this.images=imgs;
this.titleArray=titles;
this.descriptionArray=descp;
btnNums=btnNum;
this.ma=m;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
LayoutInflater inflater= (LayoutInflater) ma.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row=inflater.inflate(R.layout.single_row, parent, false);
final TextView myTitle=(TextView)row.findViewById(R.id.textView);
myTitle.findViewById(R.id.textView);
final TextView descp=(TextView)row.findViewById(R.id.textView2);
final ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
final Button button = (Button) row.findViewById(R.id.angry_btn);
final Vibrator a = (Vibrator) ma.getSystemService(Context.VIBRATOR_SERVICE);
if(ma.t!=null)
{
for(int i=0; i<14;i++){
if (btnNums[position] <= 0) {
button.setText("OK");
/* Integer index=(Integer) convertView.getTag();
ma.list.removeViewAt(index);
ma.adapter.notifyDataSetChanged();
*/
}else {
button.setText("" + ma.t[position]);
}
// button.setText("" + ma.t[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}else
{
for(int i=0; i<14;i++){
if (btnNums[position] <= 0) {
button.setText("OK");
/* Integer index=(Integer) convertView.getTag();
ma.list.removeViewAt(index);
ma.adapter.notifyDataSetChanged();
*/
}else {
button.setText("" + btnNums[position]);
}
// button.setText("" + btnNums[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNums[position]--;
storeIntArray(btnNums);
a.vibrate(30);
int temp[]=getFromPrefs();
ma.t=temp;
for (int i = 0; i <14; i++) {
if (btnNums[position] <= 0) {
button.setText("OK");
/* Integer index=(Integer) convertView.getTag();
ma.list.removeViewAt(index);
ma.adapter.notifyDataSetChanged();
*/
}else {
button.setText("" + temp[position]);
}
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
});
return row;
}
In my app, I use custom list view with different datas. these datas come from arrays , I want to send new arrays via constructor to my adapter by checking date but it doesn't work .
after these codes I used these lines
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
Please help I am stucked.

Why don't you create a setData() method in your adapter where you're clearing the current data and setting the new one and then call the notifyDataSetChanged method.
This way you will not create and set the same adapter multiple times when you want to change the data.

Related

Can a Shared Preference be applied to custom ListView?

I have a shared preference in my Custom list view. I am using it to keep numbers on the button but I have a condition where the row disappears when the button becomes 0 but when I scroll down it returns to its old form and becomes visible to it's user again. Is it possible to apply the same logic for view in SharedPreference like to keep last situation?
My code is the following:
import static android.view.View.INVISIBLE;
public class MainActivity extends Activity {
public MyAdapter adapter;
Context context;
public ListView list;
public int t[];
public SharedPreferences prefs;
public SharedPreferences.Editor edit;
int [] btnNums={100,150,94,72,206,489,1481,731,131,91,145,137,662,770,196,351,258,131,180,1281};
int[] images = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9,
R.drawable.a10, R.drawable.a11, R.drawable.a12, R.drawable.a13, R.drawable.a14, R.drawable.a15, R.drawable.a16, R.drawable.a17, R.drawable.a18, R.drawable.a19, R.drawable.a20, R.drawable.a21};
String[] exp;
String[] mean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit= this.getSharedPreferences("NAME", Context.MODE_APPEND).edit();
prefs = getSharedPreferences("NAME", Context.MODE_APPEND);
Resources res=getResources();
exp= res.getStringArray(R.array.names);
mean=res.getStringArray(R.array.anlam);
list= (ListView) findViewById(R.id.listView);
//
// edit.putInt("Count", btnNums.length);
// int count = 0;
// for (int i: btnNums){
// edit.putInt("IntValue_" + count++, i);
// }
// edit.commit();
//
int[] ret;
int count1 = prefs.getInt("Count", 0);
ret = new int[count1];
for (int i = 0; i < count1; i++){
ret[i] =prefs.getInt("IntValue_"+ i, i);
}
t=ret;
if(t!=null)
{
adapter=new MyAdapter(this,exp,images,mean,t);
}else
{
adapter=new MyAdapter(this,exp,images,mean,btnNums);
}
list.setAdapter(adapter);
context=getApplicationContext();
}
}
class MyAdapter extends ArrayAdapter<String>{
int [] images;
String [] titleArray;
String [] descriptionArray;
int [] btnNums;
MainActivity ma;
public MyAdapter(MainActivity m, String[] titles, int imgs[], String[] descp, int[] btnNum ){
super(m, R.layout.single_row, R.id.textView,titles);
this.images=imgs;
this.titleArray=titles;
this.descriptionArray=descp;
btnNums=btnNum;
this.ma=m;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater= (LayoutInflater) ma.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row=inflater.inflate(R.layout.single_row, parent, false);
final TextView myTitle=(TextView)row.findViewById(R.id.textView);
myTitle.findViewById(R.id.textView);
final TextView descp=(TextView)row.findViewById(R.id.textView2);
final ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
final Button button = (Button) row.findViewById(R.id.angry_btn);
final Vibrator a = (Vibrator) ma.getSystemService(Context.VIBRATOR_SERVICE);
if(ma.t!=null)
{
for(int i=0; i<21;i++){
button.setText("" + ma.t[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}else
{
for(int i=0; i<21;i++){
button.setText("" + btnNums[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNums[position]--;
storeIntArray(btnNums);
a.vibrate(30);
if (btnNums[position] == 0) {
button.setEnabled(false);
button.setVisibility(INVISIBLE);
row.setVisibility(INVISIBLE);
}
int temp[]=getFromPrefs();
ma.t=temp;
for (int i = 0; i < 21; i++) {
button.setText("" + temp[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
});
return row;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public void storeIntArray(int[] array){
ma.edit.putInt("Count", array.length);
int count = 0;
for (int i: array){
ma.edit.putInt("IntValue_" + count++, i);
}
ma.edit.commit();
}
public int[] getFromPrefs(){
int[] ret;
int count = ma.prefs.getInt("Count", 0);
ret = new int[count];
for (int i = 0; i < count; i++){
ret[i] =ma.prefs.getInt("IntValue_"+ i, i);
}
return ret;
}
}
First, please format your code, so its more readable.
Question: Can a Shared Preference be applied to custom ListView?
Answer: Yes it possible to use/access shared preferences in a Listview.
Upon reading your code, I believe the problem lies in your implementation of Listview and its adapter. The reason why it gets back to original state when scrolled down. Please note, that GetView is always called when scrolling.
You can refer to this topic: ListView & ViewHolder Pattern.

Android setting Condition in onCheckedChanged

I am displaying images from the gallery to my custom grid view with checkbox.
I have to select 6 images only.
I have the following code
public class MultiPhotoSelectActivity extends BaseActivity {
private ArrayList<String> imageUrls;
private DisplayImageOptions options;
private ImageAdapter imageAdapter;
CheckBox mCheckBox;
int pos;
ArrayList<String> selectedItems;
ArrayList<String> selectedimgs = new ArrayList<String>();
RelativeLayout rl_gallery_row,rl_gallery_async;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_grid);
//Bundle bundle = getIntent().getExtras();
//imageUrls = bundle.getStringArray(Extra.IMAGES);
rl_gallery_async = (RelativeLayout) findViewById(R.id.RelativeLayout_galleryas);
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
System.out.println("=====> Array path => "+imageUrls.get(i));
}
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory()
.cacheOnDisc()
.build();
imageAdapter = new ImageAdapter(this, imageUrls);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(imageAdapter);
/*gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImageGalleryActivity(position);
}
});*/
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
public void btnChoosePhotosClick(View v){
selectedItems = imageAdapter.getCheckedItems();
Toast.makeText(MultiPhotoSelectActivity.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show();
Log.d(MultiPhotoSelectActivity.class.getSimpleName(), "Selected Items: " + selectedItems.toString());
}
public class ImageAdapter extends BaseAdapter {
ArrayList<String> mList;
LayoutInflater mInflater;
Context mContext;
SparseBooleanArray mSparseBooleanArray;
public ImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
mSparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<String>();
this.mList = imageList;
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for(int i=0;i<mList.size();i++) {
if(mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pos = position;
if(convertView == null) {
convertView = mInflater.inflate(R.layout.row_multiphoto_item, null);
}
mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
rl_gallery_row = (RelativeLayout) findViewById(R.id.Relativelayout_gallery_row);
imageLoader.displayImage("file://"+imageUrls.get(position), imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(Bitmap loadedImage) {
Animation anim = AnimationUtils.loadAnimation(MultiPhotoSelectActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
});
mCheckBox.setTag(position);
//mCheckBox.setId(position);
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
//mCheckBox.setId(position);
//holder.imageview.setId(position);
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
selectedItems = imageAdapter.getCheckedItems();
if(selectedItems.size() > 5 )
{
mCheckBox.setEnabled(false); // disable checkbox
}
}
};
}
}
Now i am not able to uncheck the checkbox automatically when the limit is crossed..
Please help..
I think your condition is not satisfied for unchecking the check box, try to put a toast inside your condition

How to make Android ListView get refresh automatically?

In my app i have a ListView. Data is populated in ListView using SimpleCursorAdapter. I want ListView to be refreshed automatically whenever there is change in database or when i click button. I have tried adapter.notifyDataSetChanged() but its not effective.i couldn,t findout a good solution. I want ListView to be refreshed whenever user enters value in EditText and then press Send Button and save entered data in SQLite database. Here is my Code :
public class chatCursor extends Activity {
static MyListAdapter adapter;
ArrayList<String> item_id;
ArrayList<String> item_phone_num;
ArrayList<String> item_msg_body;
ArrayList<String> item_time;
ArrayList<String> item_flag;
ArrayList<String> items;
private Button btn_send;
DbManager manager;
Cursor Cursor;
//ViewHolder holder12;
String contact_for_chat;
String contact_no;
String message_body = "";
Calendar c;
SimpleDateFormat sdf;
String time;
EditText et_chat;
String flag;
String msg = "";
ListView lv_chat;
String[] from = new String[]{"Message_body","Time"};
int[] toIDs = new int[]{R.id.msg_body,R.id.time};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Bundle bundle = getIntent().getExtras();
contact_for_chat = bundle.getString("contact_name");
contact_for_chat = contact_for_chat.replace(" ", "");
contact_no = Util.getContactNumber(contact_for_chat, chatCursor.this);
Toast.makeText(getApplicationContext(), contact_no, Toast.LENGTH_LONG).show();
manager = new DbManager(this);
Cursor = manager.Return_SMS(contact_for_chat);
c = Calendar.getInstance();
sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
time = sdf.format(c.getTime());
item_id = new ArrayList<String>(Cursor.getCount());
item_phone_num = new ArrayList<String>(Cursor.getCount());
item_msg_body = new ArrayList<String>(Cursor.getCount());
item_time = new ArrayList<String>(Cursor.getCount());
item_flag = new ArrayList<String>(Cursor.getCount());
findViews();
showList();
//setActionBar();
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SendSMS();
showList();
}
});
lv_chat.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
int itemId = Integer.valueOf(String.valueOf(position));
}});
}
private void showList() {
showEvents(Cursor);
adapter = new MyListAdapter(this,R.layout.activity_chat,
Cursor,
from,
toIDs);
lv_chat.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void findViews() {
et_chat = (EditText)findViewById(R.id.et_chat);
btn_send = (Button)findViewById(R.id.button1);
lv_chat = (ListView)findViewById(R.id.list);
lv_chat.setDivider(this.getResources().getDrawable(android.R.color.transparent));
}
protected void SendSMS() {
SmsManager sms_manager = SmsManager.getDefault();
message_body = et_chat.getText().toString();
ArrayList<String> parts = sms_manager.divideMessage(message_body);
sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
flag = "1";
manager.Insert_sms_data(time, contact_for_chat, message_body,flag);
if(message_body.length()>0)
{
et_chat.setText("");
}
showList();
Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_LONG).show();
private void showEvents(Cursor cursor) {
int i=0;
while (cursor.moveToNext()) {
item_id.add(i+"");
item_time.add(cursor.getString(1));
item_msg_body.add(cursor.getString(3));
item_phone_num.add(cursor.getString(2));
item_flag.add(cursor.getString(4));
i++;
}
}
public class MyListAdapter extends SimpleCursorAdapter {
Cursor myCursor;
Context myContext;
public MyListAdapter(Context context, int layout,
Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
myCursor = c;
myContext = context;
}
public int getCount() {
return item_msg_body.size();
}
public Object getItem(int position) {
return item_msg_body.get(position);
}
public long getItemId(int position) {
return item_msg_body.get(position).hashCode();
}
public View getView(final int position, View arg1, ViewGroup arg2) {
View v = arg1;
ViewHolder holder = null;
if (v == null) {
LayoutInflater layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_chat, null);
holder = new ViewHolder();
// holder.tv_contact = (TextView) v.findViewById(R.id.phone_num);
holder.tv_sms_body = (TextView) v.findViewById(R.id.msg_body);
holder.tv_time = (TextView) v.findViewById(R.id.time);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
if(item_flag.get(position).equals("1"))
{
RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
RelativeLayout.LayoutParams dateparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dateparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
dateparams.addRule(RelativeLayout.BELOW, R.id.msg_body);
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);
holder.tv_sms_body.setLayoutParams(params);
holder.tv_time.setLayoutParams(dateparams);
}
else if(item_flag.get(position).equals("0"))
{
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_yellow);
}
//holder.tv_contact.setText("" + item_phone_num.get(position));
holder.tv_sms_body.setText(item_msg_body.get(position));
holder.tv_time.setText(item_time.get(position));
return v;
}
}
public class ViewHolder {
private TextView tv_contact;
private TextView tv_sms_body;
private TextView tv_time;
}
}
Any help will will be appreciated .Thanks in advance
call adapter.notifydatasetchanged() method to refresh listview

AlertDialog selectedItem is null

I have code for ListwithImage list. But when i try to onclickItem shows with Dialog, but Dialog shows null. I implement onclickItemListener . I tried this code without image, Dialog shows selected list. But when i try with image, it won't work.
MyCode:
public class MainActivity extends Activity {
EditText edittext;
ListView listview;
String[] text = { "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten" };
int[] image = { R.drawable.one, R.drawable.two, R.drawable.three,
R.drawable.four, R.drawable.five, R.drawable.six, R.drawable.seven,
R.drawable.eight, R.drawable.nine, R.drawable.ten };
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setAdapter(new MyCustomAdapter(text, image));
edittext.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after)
{
}
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
for (int i = 0; i < text.length; i++)
{
if (textlength <= text[i].length())
{
if (edittext.getText().toString().
equalsIgnoreCase((String) text[i].subSequence(0, textlength)))
{
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}
listview.setAdapter(new MyCustomAdapter
(text_sort, image_sort));
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
// TODO Auto-generated method stub
listview.getItemAtPosition(position);
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setTitle("List");
adb.setMessage(" selected Item is="
+ listview.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
});
}
});
}
class MyCustomAdapter extends BaseAdapter
{
String[] data_text;
int[] data_image;
MyCustomAdapter()
{
}
MyCustomAdapter(String[] text, int[] image)
{
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Integer> image)
{
data_text = new String[text.size()];
data_image = new int[image.size()];
for(int i=0;i<text.size();i++)
{
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}
}
public int getCount()
{
return data_text.length;
}
public String getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview, parent, false);
TextView textview = (TextView) row.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) row
.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
}
your getting wrong values in Your Alert
wrong
+listview.getItemAtPosition(position));
right
adb.setMessage(" selected Item is="+text_sort.get(position).toString());
Try changing this:
adb.setMessage(" selected Item is= " + listview.getItemAtPosition(position));
To this:
adb.setMessage(" selected Item is= " + text_sort.get(position));

how to pass total value in textview using base adapter class in android

At first time choosing price,qty values.i added all prices and show in totalamount as textview.up to now working fine. if i changed the qty values i can change automatically price value at that time i want change the total value in textview
i try this code
public class SelectedItem extends Activity {
private ListView lv;
private CustomAdapter adapter;
int tableid;
String id;
ArrayList<String> arr=new ArrayList<String>();
ArrayList<String> price=new ArrayList<String>();
ArrayList<Bitmap> image=new ArrayList<Bitmap>();
Double amountvalue;
TextView totalamount;
Button order;
String dtotalamount;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
arr=getIntent().getStringArrayListExtra("itemname");
price=getIntent().getStringArrayListExtra("itemprice");
image=getIntent().getExtras().getParcelableArrayList("itemimage");
setContentView(R.layout.selecteditem);
lv = (ListView) findViewById(R.id.selecteditemlist);
adapter = new CustomAdapter(this, arr,price,image);
lv.setAdapter(adapter);
amountvalue=CustomAdapter.x;
System.out.println(amountvalue);
totalamount=(TextView)findViewById(R.id.amount);
totalamount.setText(String.valueOf(amountvalue));(here only i can display the total value...now i want change qty means total also will change)
order=(Button)findViewById(R.id.order);
order.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try
{
tableid=Login.tableid;
id=Integer.toString(tableid);
System.out.println(id);
String x=amountvalue.toString();
public class SelectedItem extends Activity {
private ListView lv;
private CustomAdapter adapter;
int tableid;
String id;
ArrayList<String> arr=new ArrayList<String>();
ArrayList<String> price=new ArrayList<String>();
ArrayList<Bitmap> image=new ArrayList<Bitmap>();
Double amountvalue;
TextView totalamount;
Button order;
String dtotalamount;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
arr=getIntent().getStringArrayListExtra("itemname");
price=getIntent().getStringArrayListExtra("itemprice");
image=getIntent().getExtras().getParcelableArrayList("itemimage");
setContentView(R.layout.selecteditem);
lv = (ListView) findViewById(R.id.selecteditemlist);
adapter = new CustomAdapter(this, arr,price,image);
lv.setAdapter(adapter);
amountvalue=CustomAdapter.x;
System.out.println(amountvalue);
totalamount=(TextView)findViewById(R.id.amount);
totalamount.setText(String.valueOf(amountvalue));
order=(Button)findViewById(R.id.order);
order.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tableid=Login.tableid;
id=Integer.toString(tableid);
System.out.println(id);
String x=amountvalue.toString();
}
});
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
public static Double x = 0.0;
public static Double z;
ArrayList<Integer> selectprice = new ArrayList<Integer>();
public static ArrayList<String> arr1 = new ArrayList<String>();
public static ArrayList<String> itemprice = new ArrayList<String>();
public static ArrayList<Bitmap> itemimage = new ArrayList<Bitmap>();
ArrayList<Integer> total = new ArrayList<Integer>();
public Context Context;
private LayoutInflater inflater;
HashMap<String, String> map = new HashMap<String, String>();
public CustomAdapter(Context context, ArrayList<String> arr,
ArrayList<String> price, ArrayList<Bitmap> image) {
Context = context;
inflater = LayoutInflater.from(context);
arr1 = arr;
itemprice = price;
itemimage = image;
System.out.println(itemprice);
System.out.println("arr: " + arr.size());
for (int i = 0; i < price.size(); i++) {
x = x + Double.parseDouble(price.get(i));
}
}
public int getCount() {
// TODO Auto-generated method stub
return arr1.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return arr1.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void clear() {
arr1.clear();
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.selecteditemlistview, null);
holder = new ViewHolder();
holder.textViewSelectedText = (TextView) convertView
.findViewById(R.id.selectedtext);
holder.price = (TextView) convertView
.findViewById(R.id.selectitemprice);
holder.image = (ImageView) convertView
.findViewById(R.id.selectitemimage);
holder.qty = (EditText) convertView.findViewById(R.id.selectqty);
holder.total = (TextView) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
#SuppressWarnings("unused")
String amount = holder.qty.getText().toString();
final Double price1 = Double.parseDouble(itemprice.get(position));
int qut = Integer.parseInt(holder.qty.getText().toString());
final double total = (price1 * qut);
holder.textViewSelectedText.setText(arr1.get(position));
holder.price.setText(itemprice.get(position));
holder.image.setImageBitmap(itemimage.get(position));
holder.total.setText(String.valueOf(total));
holder.qty.setOnFocusChangeListener(new OnFocusChangeListener() {
#SuppressWarnings("static-access")
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (!hasFocus) {
int position = v.getId();
final EditText Caption = (EditText) v;
Caption.setFocusable(true);
holder.qty.setFocusable(true);
int q = Integer.parseInt(holder.qty.getText().toString());
Double result = (price1 * q);
Double y = x - total;
double z = y + result;
}
}
});
return convertView;
}
class ViewHolder {
TextView textViewSelectedText = null;
TextView price = null;
ImageView image = null;
EditText qty = null;
TextView total = null;
}
}
at first time x(customadapter) values can show in total. after changing the qty i will get z(customadapter) value. this z value i want pass total.. please any one can help me
OKay. Inside the getView() of your Adapter do this,
You have to use a TextWatcher for your EditText. It is simple.
holder.qty.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
int q = Integer.parseInt(holder.qty.getText().toString());
Double result = (price1 * q);
Double y = x - total;
double z = y + result;
totalamount.setText(String.valueOf(z));
}
});
EDIT 1
In your SelectedItem.Java,
change this line
adapter = new CustomAdapter(this, arr,price,image);
as,
adapter = new CustomAdapter(this, arr,price,image,totalamount);
And now in your CustomAdapter class add a TextView globally,
TextView totalamount=null;
And now change the constructor,
public CustomAdapter(Context context, ArrayList<String> arr,
ArrayList<String> price, ArrayList<Bitmap> image,TextView text) {
Context = context;
inflater = LayoutInflater.from(context);
arr1 = arr;
itemprice = price;
totalamount=text;
itemimage = image;
System.out.println(itemprice);
System.out.println("arr: " + arr.size());
for (int i = 0; i < price.size(); i++) {
x = x + Double.parseDouble(price.get(i));
}
}

Categories

Resources