i have create an app in which,i want to show the checkbox prechecked with the help of xml,and after that user can checked or uncheked the checkbox,but xaml is not showing it checked on start of the app in device,what is the problem.please advise.
MainActivity
public class File_Selecter extends Activity implements OnItemClickListener {
EditText edDelimiter, edqualifier, edcolumn, edrow;
ListView list;
StringBuilder addition = new StringBuilder();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
ArrayList<String> list3 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
private Button btnsave;
String str;
int t;
int count = 0;
String[] BreakData, roz;
TextView textnum;
static String fileinfo;
static StringBuilder conct = new StringBuilder();
static int ResultCode = 12;
String name = "", number = "";
MyAdapter ma;
String fin = "";
String[] cellArray;
String[] art = null;;
String pathname = Environment.getExternalStorageDirectory()
.getAbsolutePath();
static String contacts = "";
static String mixer;
static String delimiter, qulifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_file);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#00aef0"));
actionBar.setBackgroundDrawable(colorDrawable);
Intent itadd = new Intent();
// edittext name
// final String name=itadd.getStringExtra("name").toString();
textnum = (TextView) findViewById(R.id.textnum1);
list = (ListView) findViewById(R.id.listview);
ma = new MyAdapter();
list.setAdapter(ma);
// list.setOnItemClickListener(this);
// list.setItemsCanFocus(false);
// list.setTextFilterEnabled(true);
edDelimiter = (EditText) findViewById(R.id.edDelimiter);
edcolumn = (EditText) findViewById(R.id.edcoloumns);
edrow = (EditText) findViewById(R.id.edrow);
edqualifier = (EditText) findViewById(R.id.edqualifier);
// edittext number
// final String number=itadd.getStringExtra("number").toString();
edDelimiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edDelimiter.setError(null);
}
});
if(fileinfo!=null){
//Toast.makeText(getApplication(),
//fileinfo.toString(), Toast.LENGTH_LONG)
//.show();
if (delimiter != null){
edDelimiter.setText( SmsSend
.delim1.toString());
qulifier= SmsSend
.qulifier.toString(); }
ToRead(fileinfo);
// contacts from smssend
contacts = SmsSend.contacts1;
if (SmsSend.contacts1 != null) {
cellArray = contacts.split(";");
if(list2.size() != 0){
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list2.size(); j++) {
if (list2.get(j).contains(cellArray[i])) {
//ma.setChecked(j, true);
break;
}}}}
else{
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list1.size(); j++) {
if (list1.get(j).contains(cellArray[i])) {
//ma.setChecked(j, true);
break;
}
}
}
}
}
}
// button1
btnsave = (Button) findViewById(R.id.btnsave);
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(edDelimiter.getText().toString().length()== 0){
edDelimiter.setError("Delimiter ir required");
}
if(File_Explorer.fileSizeInMB <= 1){
ToRead(fileinfo);
//finish();
}else{
Toast.makeText(getApplication(), "file size is too large", Toast.LENGTH_LONG).show();
}
}
});
}
public void ToRead(String fileinfo) {
if (fileinfo != null) {
delimiter = edDelimiter.getText().toString();
// Toast.makeText(getApplication(), delimiter, Toast.LENGTH_LONG).show();
//delim=":";
qulifier = edqualifier.getText().toString();
//Toast.makeText(getApplication(), qulifier.toString(), Toast.LENGTH_LONG).show();
// qulifier="\\";
// finish();
mixer = qulifier + delimiter;
BreakData = fileinfo.split(mixer);
str = edrow.getText().toString().trim();
try {
t = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// Handle parse error.
}
if (BreakData != null) {
// String t2= (String.valueOf(t));
if (File_Explorer.fileExtension.equals("vcf")) {
if (!(String.valueOf(t)).equals("0")) {
if (t > BreakData.length) {
Toast.makeText(getApplication(),
"Data is less then entered rows",
Toast.LENGTH_LONG).show();
Arrays.fill(BreakData, null);
Toast.makeText(getApplication(),
"empty.................", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < BreakData.length; i++) {
if (BreakData[i].contains("FN")) {
art = BreakData[i + 1].split("\n");
name = art[0].toString();
} else if (BreakData[i].contains("TEL;CELL")) {
roz = BreakData[i + 1].split("\n");
number = roz[0].toString();
fin = name.toString() + "\n" + "\n"
+ number.toString();
list2.add(fin.toString());
}
}
for (int a = 0; a < list2.size() && a < t; a++) {
list1.add(list2.get(a).toString());
}
}
textnum.setText(Integer.toString(list1.size()));
}
else {
for (int i = 0; i < BreakData.length; i++) {
if (BreakData[i].contains("FN")) {
art = BreakData[i + 1].split("\n");
name = art[0].toString();
} else if (BreakData[i].contains("TEL;CELL")) {
roz = BreakData[i + 1].split("\n");
number = roz[0].toString();
fin = name.toString() + "\n" + "\n"
+ number.toString();
list1.add(fin.toString());
}
}
textnum.setText(Integer.toString(list1.size()));
}
} else {
if (!(String.valueOf(t)).equals("0")) {
if (t > BreakData.length) {
Toast.makeText(getApplication(),
"Data is less then entered rows",
Toast.LENGTH_LONG).show();
Arrays.fill(BreakData, null);
Toast.makeText(getApplication(),
"empty.................", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < BreakData.length && i < t; i++) {
list1.add(BreakData[i].toString());
}
textnum.setText(Integer.toString(t));
}
}
else {
for (int i = 0; i < BreakData.length; i++) {
list1.add(BreakData[i].toString());
//t = i;
}
textnum.setText(Integer.toString(BreakData.length));
}
}
}
}
list.setAdapter(ma);
// fileinfo= null;
//edDelimiter.setText(null);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < list1.size(); i++)
{
if (ma.mCheckStates.get(i) == false) {
// Toast.makeText(getApplication(), "hiii",
// Toast.LENGTH_LONG).show();
StringTokenizer st1 = new StringTokenizer(list1.get(i)
.toString(), "\n");
String first = st1.nextToken();
String second = st1.nextToken();
phno0.add(second.toString());
checkedcontacts.append(list1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ list1.get(i).toString());
}
}
//Toast.makeText(getApplication(), phno0.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("extermal_name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.add_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.attachments:
fileinfo = null;
Intent i = new Intent(File_Selecter.this, File_Explorer.class);
startActivityForResult(i, ResultCode);
break;
case android.R.id.home:
// app icon in action bar clicked; go home
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int j = 0; j < list1.size(); j++)
{
if (ma.mCheckStates.get(j) == true) {
StringTokenizer st1 = new StringTokenizer(list1.get(j)
.toString(), "\n");
String first = st1.nextToken();
String second = st1.nextToken();
phno0.add(second.toString());
checkedcontacts.append(list1.get(j).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ list1.get(j).toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("extermal_name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if (resultCode == RESULT_OK) {
fileinfo = data.getStringExtra("name");
}
// list.setAdapter(ma);
}
if (resultCode == RESULT_CANCELED) {
}
}
AdapterCLass
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(list1.size());
mInflater = (LayoutInflater) File_Selecter.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Save ListView state
#Override
public int getCount() {
// TODO Auto-generated method stub
return list1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
// tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(list1.get(position));
// tv1.setText(phno1.get(position));
cb.setTag(position);
//cb.setChecked(mCheckStates.get(position, true));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
row.layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:ems="20"
android:text="TextView"
android:textColor="#0082e6" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:checked="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="22dp"
android:layout_marginTop="5dp" />
</RelativeLayout>
Related
I'm trying to upload some of images after selecting it from my UploadActivity.
public static int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
private static final int PICK_FROM_CAMERA = 1;
ArrayList<String> IPath = new ArrayList<String>();
public static Uri uri;
TextView msgLoading;
//ProgressBar pBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
msgLoading = (TextView) findViewById(R.id.msgLoading);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
final Cursor imagecursor = getImageCursor();
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
msgLoading.setVisibility(View.GONE);
}
},100);
final Button uploadBtn = (Button) findViewById(R.id.uploadDONE);
uploadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
for (int i = 0; i < len; i++) {
if (thumbnailsselection[i]) {
cnt++;
selectImages = arrPath[i];
IPath.add(selectImages);
}
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"You've selected Total " + cnt + " image(s).",
Toast.LENGTH_LONG).show();
Log.i("SelectedImages", String.valueOf(selectImages.toCharArray()));
Intent intentMessage = new Intent(UploadActivity.this,
ImagesForAds.class);
intentMessage.putStringArrayListExtra("IMAGE", IPath);
startActivity(intentMessage);
}
}
});
}
#NonNull
private Cursor getImageCursor() {
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
final Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
final int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
return imagecursor;
}
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) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView
.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
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.imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]),
"image/*");
startActivity(intent);
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent i = new Intent(UploadActivity.this, ImagesForAds.class);
UploadActivity.this.finish();
startActivity(i);
super.onBackPressed();
}
and it's worked fine, I can back data to my main activity as below :
b = getIntent().getExtras();
if (b != null) {
ImgData = b.getStringArrayList("IMAGE");
for (int i = 0; i < ImgData.size(); i++) {
map.add(ImgData.get(i).toString());
}
}
now it's ok... I need to upload those Images that I selected, here is my asyncTask:
public class ImageUploadTask extends AsyncTask<String, Void, String> {
String sResponse = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(ImagesForAds.this, "Uploading",
"Please wait...", true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
String url = "myLink";
int i = Integer.parseInt(params[0]);
Bitmap bitmap = decodeFile(map.get(i));
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
entity = new MultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
//entity.addPart("user_id", new StringBody("199"));
//entity.addPart("club_id", new StringBody("10"));
entity.addPart("images", new ByteArrayBody(data,
"image/jpeg", params[1]));
Log.i(TAG, "array map: " + map.get(i));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
sResponse = EntityUtils.getContentCharSet(response.getEntity());
System.out.println("sResponse : " + sResponse);
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return sResponse;
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),
sResponse + " Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
count++;
if (count < map.size()) {
new ImageUploadTask().execute(count + "", "hm" + count
+ ".jpg");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
and here how I invoke it :
int count = 0;
new ImageUploadTask().execute(count + "", "pk" + count + ".jpg");
The issue with AsyncTask.. it's upload only 1 image, how I can upload all images I have selected ?
This is your flaw :
if (count < map.size()) {
new ImageUploadTask().execute(count + "", "hm" + count
+ ".jpg");
}
not a good idea to create a new ImageUploadTask inside ImageUploadTask.
move your for loop inside doInBackground() and for updating user use publishProgress() and catch that event inside onProgressUpdate.
Read more about AsyncTask : https://developer.android.com/reference/android/os/AsyncTask.html
In my Recycler View not displaying the item orderwise routinely changing the items for each and every time while running the program.
How to display Order wise the items in Recycler View.
Code:
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
Adapter:
public class CartlistAdapter extends RecyclerView.Adapter < CartlistAdapter.ViewHolder > {
private ArrayList < CartItemoriginal > cartlistadp;
private ArrayList < Cartitemoringinaltwo > cartlistadp2;
DisplayImageOptions options;
private Context context;
public static final String MyPREFERENCES = "MyPrefs";
public static final String MYCARTPREFERENCE = "CartPrefs";
public static final String MyCartQtyPreference = "Cartatyid";
SharedPreferences.Editor editor;
SharedPreferences shared,
wishshared;
SharedPreferences.Editor editors;
String pos,
qtyDelete;
String date;
String currentDateandTime;
private static final int VIEW_TYPE_ONE = 1;
private static final int VIEW_TYPE_TWO = 2;
private static final int TYPE_HEADER = 0;
private Double orderTotal = 0.00;
DecimalFormat df = new DecimalFormat("0");
Double extPrice;
View layout,
layouts;
SharedPreferences sharedPreferences;
SharedPreferences.Editor QutId;
boolean flag = false;
public CartlistAdapter() {
}
public CartlistAdapter(ArrayList < CartItemoriginal > cartlistadp, Context context) {
this.cartlistadp = cartlistadp;
this.cartlistadp2 = cartlistadp2;
this.context = context;
options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).showImageOnLoading(R.drawable.b2)
.showImageForEmptyUri(R.drawable.b2).build();
if (YelloPage.imageLoader.isInited()) {
YelloPage.imageLoader.destroy();
}
YelloPage.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
public int getItemViewType(int position) {
if (cartlistadp.size() == 0) {
Toast.makeText(context, String.valueOf(cartlistadp), Toast.LENGTH_LONG).show();
return VIEW_TYPE_TWO;
}
return VIEW_TYPE_ONE;
}
#Override
public CartlistAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
ViewHolder viewHolder = null;
switch (position) {
case VIEW_TYPE_TWO:
View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_cart, viewGroup, false);
viewHolder = new ViewHolder(view2, new MyTextWatcher(viewGroup, position));
// return view holder for your placeholder
break;
case VIEW_TYPE_ONE:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartitemrow, viewGroup, false);
viewHolder = new ViewHolder(view, new MyTextWatcher(view, position));
// return view holder for your normal list item
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(CartlistAdapter.ViewHolder viewHolder, int position) {
viewHolder.productnames.setText(cartlistadp.get(position).getProductname());
viewHolder.cartalisname.setText(cartlistadp.get(position).getAliasname());
viewHolder.cartprice.setText("Rs" + " " + cartlistadp.get(position).getPrice());
viewHolder.cartdelivery.setText(cartlistadp.get(position).getDelivery());
viewHolder.cartshippin.setText(cartlistadp.get(position).getShippincharge());
viewHolder.cartsellername.setText(cartlistadp.get(position).getSellername());
viewHolder.Error.setText(cartlistadp.get(position).getError());
viewHolder.qty.setTag(cartlistadp.get(position));
viewHolder.myTextWatcher.updatePosition(position);
if (cartlistadp.get(position).getQty() != 0) {
viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
viewHolder.itemView.setTag(viewHolder);
} else {
viewHolder.qty.setText("0");
}
YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
}
#Override
public int getItemCount() {
return cartlistadp.size();
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return cartlistadp.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView productnames, cartalisname, cartprice, cartdelivery, cartshippin, cartsellername, Error, total;
private ImageView cartitemimg;
private ImageButton wishbtn, removebtn;
private LinearLayout removecart, movewishlist;
private CardView cd;
private EditText qty;
private ImageView WishImg;
public MyTextWatcher myTextWatcher;
public ViewHolder(final View view, MyTextWatcher myTextWatcher) {
super(view);
productnames = (TextView) view.findViewById(R.id.cartitemname);
cartalisname = (TextView) view.findViewById(R.id.cartalias);
cartprice = (TextView) view.findViewById(R.id.CartAmt);
cartdelivery = (TextView) view.findViewById(R.id.cartdel);
cartshippin = (TextView) view.findViewById(R.id.shippingcrg);
cartsellername = (TextView) view.findViewById(R.id.cartSellerName);
cartitemimg = (ImageView) view.findViewById(R.id.cartimg);
Error = (TextView) view.findViewById(R.id.error);
this.myTextWatcher = myTextWatcher;
removecart = (LinearLayout) view.findViewById(R.id.removecart);
movewishlist = (LinearLayout) view.findViewById(R.id.movewishlist);
WishImg = (ImageView) view.findViewById(R.id.wishimg);
qty = (EditText) view.findViewById(R.id.quantity);
qty.addTextChangedListener(myTextWatcher);
String pid, qid;
sharedPreferences = view.getContext().getSharedPreferences(MYCARTPREFERENCE, Context.MODE_PRIVATE);
QutId = sharedPreferences.edit();
Log.d("Position checking1 ---", String.valueOf(getAdapterPosition()));
//MyTextWatcher textWatcher = new MyTextWatcher(view,qty);
// qty.addTextChangedListener(new MyTextWatcher(view,getAdapterPosition()));
//qty.addTextChangedListener(textWatcher);
qty.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
qty.setSelection(qty.getText().length());
return false;
}
});
wishshared = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE);
editors = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE).edit();
shared = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE);
editor = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE).edit();
cd = (CardView) view.findViewById(R.id.cv);
productnames.setSingleLine(false);
productnames.setEllipsize(TextUtils.TruncateAt.END);
productnames.setMaxLines(2);
//totalPrice();
view.setClickable(true);
// view.setFocusableInTouchMode(true);
removecart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cartlistadp.size() == 1) {
Intent list = new Intent(v.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
removeAt(getAdapterPosition());
Log.i(String.valueOf(getPosition()), "item");
Toast.makeText(context, "All items deleted from your WishList", Toast.LENGTH_LONG).show();
} else {
removeAt(getAdapterPosition());
}
}
});
MovewishList();
totalPrice();
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void removeAt(int positions) {
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray item = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
String channel = shared.getString(Constants.cartid, String.valueOf(test));
pos = cartlistadp.get(getAdapterPosition()).getProductid();
qtyDelete = String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
try {
JSONArray delteitems = new JSONArray(channel);
itemsQty = delteitems.getJSONArray(0);
item = delteitems.getJSONArray(1);
for (int x = 0; x < itemsQty.length(); x++) {
if (pos.equalsIgnoreCase(itemsQty.getString(x))) {
itemsQty.remove(x);
cartlistadp.remove(positions);
notifyItemRemoved(positions);
notifyItemRangeChanged(positions, cartlistadp.size());
notifyDataSetChanged();
}
}
for (int y = 0; y < item.length(); y++) {
if (qtyDelete.equalsIgnoreCase(item.getString(y)))
item.remove(y);
}
String s = String.valueOf(delteitems);
editor.putString(Constants.cartid, String.valueOf(delteitems));
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void MovewishList() {
movewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartlistadp.size() == 1) {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
JSONArray items3;
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems1", Toast.LENGTH_LONG).show();
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Toast.makeText(context, Constants.productid, Toast.LENGTH_LONG).show();
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
} else {
removeAt(getAdapterPosition());
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
}
} else {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
removeAt(getAdapterPosition());
}
}
}
});
}
}
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private EditText editText;
private int position;
//private int position;
private MyTextWatcher(View view, int position) {
this.view = view;
this.position = position;
// this.position = adapterPosition;
// cartlistadp.get(position).getQty() = Integer.parseInt((Caption.getText().toString()));
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// EditText qtyView = (EditText) view.findViewById(R.id.quantity);
Log.i("editextpostion", String.valueOf(position));
}
public void afterTextChanged(Editable s) {
DecimalFormat df = new DecimalFormat("0");
String qtyString = s.toString();
int quantity = qtyString.equals("") ? 0 : Integer.valueOf(qtyString);
String quty = String.valueOf(quantity);
EditText qtyView = (EditText) view.findViewById(R.id.quantity);
CartItemoriginal product = (CartItemoriginal) qtyView.getTag();
// int position = (int) view.qtyView.getTag();
Log.d("postion is qtytag", "Position is: " + product);
qtyView.setFilters(new InputFilter[] {
new InputFilterMinMax(product.getMinquantity(), product.getMaxquantity())
});
if (product.getQty() != quantity) {
Double currPrice = product.getExt();
Double price = Double.parseDouble(product.getPrice());
int maxaty = Integer.parseInt(product.getMaxquantity());
int minqty = Integer.parseInt(product.getMinquantity());
if (quantity < maxaty) {
extPrice = quantity * price;
} else {
Toast.makeText(context, "Sorry" + " " + " " + "we are shipping only" + " " + " " + maxaty + " " + " " + "unit of quantity", Toast.LENGTH_LONG).show();
}
Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));
product.setQty(quantity);
product.setExt(extPrice);
TextView ext = (TextView) view.findViewById(R.id.CartAmt);
if (product.getQty() != 0) {
ext.setText("Rs." + " " + df.format(product.getExt()));
} else {
ext.setText("0");
}
if (product.getQty() != 0) {
qtyView.setText(String.valueOf(product.getQty()));
} else {
qtyView.setText("");
}
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray items = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
JSONArray listitems = null;
//String Sharedqty= String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
String channel = (shared.getString(Constants.cartid, String.valueOf(test)));
try {
listitems = new JSONArray(channel);
itemsQty = listitems.getJSONArray(1);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (itemsQty != null) {
itemsQty.put(position + 1, qtyString);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (listitems != null) {
listitems.put(1, itemsQty);
}
} catch (JSONException e) {
e.printStackTrace();
}
QutId.putString(Constants.cartid, String.valueOf(listitems));
QutId.apply();
Toast.makeText(context, String.valueOf(listitems), Toast.LENGTH_SHORT).show();
totalPrice();
}
return;
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void updatePosition(int position) {
this.position = position;
}
}
}
Thanks in Advance.
For sorting you need to Collection.sort method of Java and also you need to implement comparable interface for define your comparison.
CartItemoriginal implements Comparable {
public int compareTo(Object obj) { } }
Updated
public class CartItemoriginal implements Comparable<CartItemoriginal > {
private Float val;
private String id;
public CartItemoriginal (Float val, String id){
this.val = val;
this.id = id;
}
#Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
#Override
public String toString(){
return this.id;
}
}
and use
Collections.sort(sortList);
I have created a Custom listview and set data by parsing a link and sorted them inside the list. Now when I am going to make a click and get the value of the individual object of a row I can't get the object of clicked row.
public class MainActivity extends Activity implements OnChildClickListener,
OnItemClickListener {
private ExpandableListView mExpandableListView;
private List<GroupEntity> mGroupCollection;
String URL;
ArrayList<EventParsingClass> EventObject_Collection = new ArrayList<EventParsingClass>();
ArrayList<Date> DateArray = new ArrayList<Date>();
ArrayList<ArrayList<EventParsingClass>> arrayOfEventDescription = new ArrayList<ArrayList<EventParsingClass>>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
prepareResource();
initPage();
URL = "http://..............";
ParsingWithURL(URL);
}
private void ParsingWithURL(String uRL2) {
// TODO Auto-generated method stub
new JSONPARSINGFOREVENTSTREAM().execute(URL);
}
private class JSONPARSINGFOREVENTSTREAM extends
AsyncTask<String, Void, String> {
private final String TAG_ID = "id";
private final String TAG_Title = "title";
private final String TAG_Description = "description";
private final String TAG_StartDate = "start_datetime";
private final String TAG_EndDate = "end_datetime";
private final String TAG_City = "place_city";
private final String TAG_Club = "place_club";
private final String TAG_AgeLimit = "event_agelimit";
private static final String TAG_Event_streamable = "data";
EventParsingClass EPC;
JSONArray streamable = null;
ProgressDialog pDialog;
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.d("************PARAMS", arg0[0]);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(arg0[0]);
try {
streamable = json.getJSONArray(TAG_Event_streamable);
for (int i = 0; i < streamable.length(); i++) {
EPC = new EventParsingClass();
JSONObject c = streamable.getJSONObject(i);
EPC.setId(c.getString(TAG_ID));
EPC.setPlace_city(c.getString(TAG_City));
EPC.setPlace_club(c.getString(TAG_Club));
EPC.setTitle(c.getString(TAG_Title));
EPC.setDescription(c.getString(TAG_Description));
EPC.setSratdate_time(c.getString(TAG_StartDate));
EPC.setEnddate_time(c.getString(TAG_EndDate));
EPC.setEvent_agelimit(c.getString(TAG_AgeLimit));
long difference = EPC.geEnddate_time_date().getTime()
- EPC.getSratdate_time_date().getTime();
int day_difference = (int) (difference / (1000 * 3600 * 24));
// Log.d("Difference", "" + day_difference);
if (day_difference == 0) {
AddDay(EPC.getSratdate_time_date());
} else {
if (DateArray.size() == 0) {
DateArray.add(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
DateArray.add(Constructed_value);
}
} else {
AddDay(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
AddDay(Constructed_value);
}
}
}
EventObject_Collection.add(EPC);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void AddDay(Date value) {
// TODO Auto-generated method stub
if (DateArray.size() == 0) {
DateArray.add(value);
} else {
boolean b = true;
for (Date s : DateArray) {
if (s.equals(value)) {
b = false;
break;
}
}
if (b) {
DateArray.add(value);
}
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("+++++++++++++++++++++++number of Items in List", ""
+ DateArray.size());
AddDetailedItemToListView();
AddHeaderItemsToListView();
pDialog.dismiss();
}
private void AddDetailedItemToListView() {
// TODO Auto-generated method stub
for (Date s : DateArray) {
ArrayList<EventParsingClass> constructed_arrayfor_items = new ArrayList<EventParsingClass>();
for (int g = 0; g < EventObject_Collection.size(); g++) {
EventParsingClass EVPC = EventObject_Collection.get(g);
long new_startdate = EVPC.getSratdate_time_date().getTime();
long new_endtdate = EVPC.geEnddate_time_date().getTime();
long date = s.getTime();
if (date >= new_startdate && date <= new_endtdate) {
Log.d("^^^^^^^^^^^ Value Of Date ", "" + s);
Log.d("^^^^^^^^^^^ Value Of StartDay ",
"" + EVPC.getSratdate_time_date());
Log.d("^^^^^^^^^^^ Value Of EndDay ",
"" + EVPC.geEnddate_time_date());
constructed_arrayfor_items.add(EVPC);
}
}
arrayOfEventDescription.add(constructed_arrayfor_items);
Log.d("^^^^^^^^^^^^^^^^^^^arrayOfEventDescription", ""
+ arrayOfEventDescription);
}
}
private void AddHeaderItemsToListView() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.list_evevnt);
LayoutInflater i = LayoutInflater.from(MainActivity.this);
List<Item> items = new ArrayList<Item>();
int length_of_datearray = DateArray.size();
Log.d("!!!!!!!!!!!!!!!", "" + DateArray.size());
Log.d("EEEEEEEEEEEEEEEEEEEE", "" + arrayOfEventDescription.size());
for (ArrayList<EventParsingClass> It : arrayOfEventDescription) {
Log.d("", "" + It.size());
for (EventParsingClass oETC : It) {
Log.d("*******" + oETC.getTitle(),
"" + oETC.getSratdate_time_date());
}
}
for (int m = 0; m < length_of_datearray; m++) {
String day_of_header = (String) android.text.format.DateFormat
.format("EEEE", DateArray.get(m));
String month_of_header = (String) android.text.format.DateFormat
.format("MMM", DateArray.get(m));
String date_of_header = (String) android.text.format.DateFormat
.format("dd", DateArray.get(m));
String total_header = day_of_header + " " + month_of_header
+ " " + date_of_header;
items.add(new Header(i, "" + total_header));
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(m);
for (int h = 0; h < Arraylist_for_loop.size(); h++) {
String description = Arraylist_for_loop.get(h).getId();
String title = Arraylist_for_loop.get(h).getTitle();
String place_city = Arraylist_for_loop.get(h)
.getPlace_city();
String age_limit = Arraylist_for_loop.get(h)
.getEvent_agelimit();
String dayOfTheWeek = (String) android.text.format.DateFormat
.format("EEEE", Arraylist_for_loop.get(h)
.getSratdate_time_date());
String DayofWeek = dayOfTheWeek;
if (!(dayOfTheWeek == day_of_header)) {
DayofWeek = day_of_header;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String Today = sdf.format(d);
String Value_of_today = "";
if (Today.contentEquals(DayofWeek)) {
Value_of_today = "Today";
}
items.add(new EventItem(i, Value_of_today, DayofWeek,
"12:00", title, description, place_city, "10",
age_limit));
}
}
MyListAdapter adapter = new MyListAdapter(MainActivity.this, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
}
private void prepareResource() {
mGroupCollection = new ArrayList<GroupEntity>();
for (int i = 1; i < 3; i++) {
GroupEntity ge = new GroupEntity();
ge.Name = "City " + i;
for (int j = 1; j < 4; j++) {
GroupItemEntity gi = ge.new GroupItemEntity();
gi.Name = "Venu" + j;
ge.GroupItemCollection.add(gi);
}
mGroupCollection.add(ge);
}
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), childPosition + "Clicked",
Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
EventParsingClass obj = (EventParsingClass) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), obj.getPlace_city() + "Clicked",Toast.LENGTH_LONG).show();
}
}
How can I proceed in these two scenarios?
EventParsingClass EPSP= ??? and
EPSP.getid= ??
fetch[0]="XXX"
fetch[1]="YYY"
fetch[2]="ZZZ"
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), fetch[position] + "Clicked",
Toast.LENGTH_LONG).show();
}
just declare fetch[position] to get the value of clicked item. hope this will give you some solution.
Use int position to find out values from your data list (array list or what ever you used).
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), EPSP.getid(position) + "Clicked",Toast.LENGTH_LONG).show();
}
EventItem item = (EventItem) parent.getItemAtPosition(position);
Now you have a hold of EventItem. So you can start using the get methods of your EventItem class in order to get whatever you want from it.
I got the solution:
EventParsingClass new_method(int value) {
int item_count = 0;
for (int i = 0; i < arrayOfEventDescription.size(); i++) {
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(i);
item_count++;
for (int j = 0; j < Arraylist_for_loop.size(); j++) {
if (value == item_count) {
return Arraylist_for_loop.get(j);
}
item_count++;
}
}
return null;
}
And call it from here:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
EventParsingClass newObject = new_method(arg2);
if (newObject == null) {
} else {
Log.d("Generated Value Id : ", "" + newObject.getId());
Toast.makeText(getApplicationContext(),
"Item Clicked" + arg2 + "-----" + newObject.getTitle(),
Toast.LENGTH_LONG).show();
}
}
Hi I am using custom listview and my list item contains checkbox. When updating the listview with the existing values the background is changed, so it is working fine.But when i clicks the check button, at that time the background will not changing after loading some where again then the background is changed . My question is at the time of check the item the background need to change immediately.
This is my adapter class.
public class GuestListAdapter extends BaseAdapter implements OnClickListener {
private String strExe;
AlertDialog.Builder builder;
Context context;
private ArrayList<String> arrayListFirstName;
private ArrayList<String> arrayListLastName;
private ArrayList<String> arrayListGuests;
private ArrayList<String> arrayCustomOne;
private ArrayList<String> arTempId;
private ArrayList<Boolean> chickinlist;
public static ArrayList<Integer> arrCheckedItems;
public static ArrayList<Integer> arrUnCheckedItems;
Button btnInfo;
private SQLiteAdapter mySqliteAdapter;
private GuestListScreen myGuestList;
private RelativeLayout views;
// private AlertDialog alertDialog = null;
private ArrayList<Boolean> checks = new ArrayList<Boolean>();
public GuestListAdapter(Context mcontext, ArrayList<String> arrListFN,
ArrayList<String> arrListLN, ArrayList<String> arrListGuest,
ArrayList<String> arrTiketID, ArrayList<String> arrCustOne,
ArrayList<Boolean> chicklist) {
clearAdapter();
arrayListFirstName = new ArrayList<String>();
arrayListLastName = new ArrayList<String>();
arrayListGuests = new ArrayList<String>();
arrayCustomOne = new ArrayList<String>();
arTempId = new ArrayList<String>();
chickinlist = new ArrayList<Boolean>();
arrCheckedItems = new ArrayList<Integer>();
arrUnCheckedItems = new ArrayList<Integer>();
arrayListFirstName = arrListFN;
arrayListLastName = arrListLN;
arrayListGuests = arrListGuest;
arrayCustomOne = arrCustOne;
arTempId = arrTiketID;
chickinlist = chicklist;
context = mcontext;
mySqliteAdapter = new SQLiteAdapter(context);
for (int i = 0; i < arrayListFirstName.size(); i++) {
checks.add(i, false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("", "getCount" + arrayListFirstName.size());
return arrayListFirstName.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
Log.d("", "getItem" + arrayListFirstName.size());
return arrayListFirstName.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
final int pos = position;
views = null;
LayoutInflater layoutInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
views = (RelativeLayout) layoutInflator.inflate(
R.layout.guest_list_item, null);
final CheckBox chk = (CheckBox) views.getChildAt(0);
// Log.d("", "CheckBox Pos "+position);
chk.setId(position);
TextView txtView = (TextView) views.getChildAt(1);
TextView txtView2 = (TextView) views.getChildAt(2);
TextView txtView3 = (TextView) views.getChildAt(3);
final TextView txtView4 = (TextView) views.getChildAt(4);
TextView txtView5 = (TextView) views.getChildAt(6);
txtView5.setId(position);
// Log.d("", "Button Pos "+position);
txtView4.setId(position);
txtView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, InfoScreen.class);
intent.putExtra("IDVALUE",arTempId.get(txtView4.getId()) );
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
// System.out.println(v + "##########" + " " + v.getId());
// System.out.println(v + "##########" + " " + arTempId.get(txtView4.getId()));
// System.out.println(v + "##########" + " " + chickinlist.get(txtView4.getId()));
}
});
Log.e("", "****************************************************** " );
// Log.v("", "Adapter arr pos " + pos);
// Log.v("", "Adapter arr position " + position);
Log.v("", "Adapter arr size " + arrayListFirstName.size());
Log.v("", "Passsing arr size " + chickinlist.size());
for (int dd = 0; dd < arrayListFirstName.size(); dd++) {
if (position == dd) {
// Log.d("", "Passsing arr size " + chickinlist.size());
Boolean result = chickinlist.get(position);
// Log.d("", "After " + result);
if (result == true) {
chk.setChecked(true);
arrCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_checked);
} else {
chk.setChecked(false);
arrUnCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_unchecked);
}
txtView.setText(arrayListFirstName.get(position));
txtView2.setText(arrayListLastName.get(position));
txtView3.setText("(" + arrayListGuests.get(position) + ")");
if(arrayCustomOne.get(position).equalsIgnoreCase("0")||arrayCustomOne.get(position).equalsIgnoreCase(null)||arrayCustomOne.get(position).equalsIgnoreCase(""))
{
txtView5.setText("");
}else
{
txtView5.setText(arrayCustomOne.get(position));
}
}
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
strExe = "update ticket_details set checkin_status=1 where tempid="+arTempId.get(chk.getId());
// Log.d("Adapter", "Checked Temp Id "+arTempId.get(chk.getId()));
Log.d("", "Position "+chk.getId()+"tempid "+arTempId.get(chk.getId()));
if (isChecked) {
// views.setBackgroundResource(R.drawable.list_item_checked);
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.create();
builder.setMessage(arrayListFirstName.get(chk.getId())
+ " " + arrayListLastName.get(chk.getId())
+ " has been checked in.");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// myGuestList = new GuestListScreen();
mySqliteAdapter.executeCheckQurey(strExe);
// myGuestList.ListUpdate();
dialog.dismiss();
}
}).show();
// Log.d("", "ID = " + buttonView.getId());
} else {
// views.setBackgroundResource(R.drawable.list_item_unchecked);
strExe = "update ticket_details set checkin_status=0 where tempid="+arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
// Toast.makeText(context, "check release", Toast.LENGTH_SHORT)
// .show();
}
}
});
return views;
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Integer index = (Integer) view.getTag();
boolean state = checks.get(index.intValue());
checks.set(index.intValue(), !state);
}
// private void showADialog(int posit) {
//
// AlertDialog.Builder builder = new AlertDialog.Builder(
// context);
// builder.create();
// builder.setMessage("The clicked row is "
// + arrayListFirstName.get(posit));
// builder.setPositiveButton("Ok?", new DialogInterface.OnClickListener() {
//
// #Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
//
// }).show();
// }
public void clearAdapter() {
if (arrayListFirstName != null) {
arrayListFirstName.clear();
arrayListFirstName = null;
arrayListLastName.clear();
arrayListLastName = null;
arrayListGuests.clear();
arrayListGuests = null;
arrayCustomOne.clear();
arrayCustomOne = null;
arTempId.clear();
arTempId = null;
chickinlist.clear();
chickinlist = null;
arrCheckedItems.clear();
arrCheckedItems = null;
arrUnCheckedItems.clear();
arrUnCheckedItems = null;
}
}
}
I just want to change the background of the checked item immediatly without updating the list again.
I think you need to tell the BaseAdapter to refresh the data when your OnCheckedChanged Listener is called.
GuestListAdapter.this.notifyDataSetChanged()
I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}
You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()