I am having some problems with an alertdialog box. I have a listview containing some strings and when i click the box, it shows an alert dialog box giving the option to book or cancel (its a taxi app). I am trying to get it so the name of the item chosen shows in the alert dialog box. But everytime i try it comes up showing random letters and numbers. Ill post my code as it might make it easier to understand:
Code below -
public class TaxiMain extends ListActivity {
/** Called when the activity is first created.
* #return */
class Taxi {
private String taxiName;
private String taxiAddress;
public String getName() {
return taxiName;
}
public void setName(String name) {
taxiName = name;
}
public String getAddress() {
return taxiAddress;
}
public void setAddress(String address) {
taxiAddress = address;
}
public Taxi(String name, String address) {
taxiName = name;
taxiAddress = address;
}
}
public class TaxiAdapter extends ArrayAdapter<Taxi> {
private ArrayList<Taxi> items;
private TaxiViewHolder taxiHolder;
private class TaxiViewHolder {
TextView name;
TextView address;
}
public TaxiAdapter(Context context, int tvResId, ArrayList<Taxi> items) {
super(context, tvResId, items);
this.items = items;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.taxi_list_item, null);
taxiHolder = new TaxiViewHolder();
taxiHolder.name = (TextView)v.findViewById(R.id.taxi_name);
taxiHolder.address = (TextView)v.findViewById(R.id.taxi_address);
v.setTag(taxiHolder);
} else taxiHolder = (TaxiViewHolder)v.getTag();
Taxi taxi = items.get(pos);
if (taxi != null) {
taxiHolder.name.setText(taxi.getName());
taxiHolder.address.setText(taxi.getAddress());
}
return v;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] taxiNames = getResources().getStringArray(R.array.taxi_name_array);
final String[] taxiAddresses = getResources().getStringArray(R.array.taxi_address_array);
ArrayList<Taxi> taxiList = new ArrayList<Taxi>();
for (int i = 0; i < taxiNames.length; i++) {
taxiList.add(new Taxi(taxiNames[i], taxiAddresses[i]));
}
setListAdapter(new TaxiAdapter(this, R.layout.taxi_list_item, taxiList));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(TaxiMain.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You Have Selected: "+taxiNames);
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(TaxiMain.this, Booking.class);
intent.putExtra("booking", taxiNames[selectedPosition]);
intent.putExtra("address", taxiAddresses[selectedPosition]);
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
You'll see at the bottom of the code, theres the line that wont work properly. -
adb.setMessage("You Have Selected: "+taxiNames);
If anyone can help into seeing why this wont show would be of great help.
Thanks
taxiNames is an Array, not a String. You should try this:
adb.setMessage("You Have Selected: "+taxiNames[selectedPosition]);
When you type +taxiNames you're performing taxiNames.toString(). taxiNames is an array containing a number of items. You need to just change it to + taxiNames[position]. Or, to keep it in line with your other Taxi objects, you could also use + taxiList.get(position).getName().
EDIT: Out of curiosity, why are you setting another final int for selectedPosition? You already have the final int position passed in on the method call.
Related
I face a problem in list view. In my list view have edit text and text view. When i scroll the list my data that is entered in text view has lost the value and show the default value. i have two button in list view i increase the quantity and scroll the list for next product when i come back text view lost the value and show default value 1 . And when i open keyboard for enter data then same issue . please help me.
And its my code
Custom Adapter
private List<ShowProducts> listShowProducts;
private Context context;
private int resource;
private String condition;
String uri;
private static final String TAG = "CustomAdapter";
int i = 0;
float total;
ListView listView;
TextView tvTotal;
float sum = 0;
public CustomAdapter(#NonNull Context context, #LayoutRes int resource, List<ShowProducts> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.listShowProducts = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Nullable
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(resource, parent, false);
{
final ShowProducts showProducts = listShowProducts.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageViewOfSelecteditem);
ImageView plus = (ImageView) view.findViewById(R.id.imageviewPlus);
ImageView minus = (ImageView) view.findViewById(R.id.imageviewminus);
TextView tvSetNameOfSeletedItem = (TextView) view.findViewById(R.id.tvSetNameOfSeletedItem);
TextView tvSetSizeOfSeletedItem = (TextView) view.findViewById(R.id.tvSetSizeOfSeletedItem);
TextView tvSetPriceOfSeletedItem = (TextView) view.findViewById(R.id.tvSetPriceOfSeletedItem);
final TextView tvQunatitySetOfSelectedItem = (TextView) view.findViewById(R.id.tvQunatitySetOfSelectedItem);
for (int a = 0; a < 10; a++) {
Log.d(TAG, "onnnnView: ");
}
Log.d(TAG, "getView: +++++");
tvSetNameOfSeletedItem.setText(showProducts.getProduct_name().toString());
tvSetSizeOfSeletedItem.setText(showProducts.getSize_name());
tvSetPriceOfSeletedItem.setText(String.valueOf(showProducts.getSize_price()).toString());
uri = showProducts.getProduct_photo().toString();
Picasso.with(context).load(uri).into(imageView);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
Log.d(TAG, "getView: ");
if (a <= showProducts.getSize_quantity()) {
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a--;
if (a > 0)
{
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price - showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
}
return view;
}
And activity code
public class SelectedProductFromShopingCartShow extends AppCompatActivity {
ArrayList<ShowProducts> arrayList = new ArrayList<>();
String condition = "SelectedItemsFromShoppingCart";
CustomAdapter customAdapter;
ListView listView;
TextView tvTotal;
EditText etDiscount;
int total;
float sum = 0;
Button discount;
private static final String TAG = "SelectedProductFromShop";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_product_from_shoping_cart_show);
listView = (ListView) findViewById(R.id.listViewSelectedItemsOfShopingCart);
tvTotal = (TextView) findViewById(R.id.tvTotalShow);
etDiscount = (EditText) findViewById(R.id.etDiscount);
arrayList = (ArrayList<ShowProducts>) getIntent().getSerializableExtra("selectedList");
ShowProducts showProducts = arrayList.get(0);
Log.d(TAG, "onnnnCreate: " + showProducts.getProduct_name());
customAdapter = new CustomAdapter(SelectedProductFromShopingCartShow.this, R.layout.show_selected_item_of_shopingcart, condition, arrayList);
listView.setAdapter(customAdapter);
getTotalListView();
Log.d(TAG, "onnnnCreate: Before inner class");
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(SelectedProductFromShopingCartShow.this);
builder.setTitle("Delete this product");
builder.setMessage("Are you sure you want to delete it?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(position);
customAdapter.notifyDataSetChanged();
Toast.makeText(SelectedProductFromShopingCartShow.this, "item deleted", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.show();
return true;
}
});
}
public void getTotalListView() {
sum = 0;
for (int i = 0; i < arrayList.size(); i++) {
ShowProducts showProducts = arrayList.get(i);
sum = sum + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
And watch this video for understand problems
https://youtu.be/WAjtRkI5dl4
You need to follow viewholder pattern. It will resolve your issue. You can check it here https://developer.android.com/training/improving-layouts/smooth-scrolling.html
The only place you're keeping count is in the view. You should make your count a field in the list item ShowProducts and create a getter & setter. For example, in the plus onClickListener, instead of
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
You'll have
// for example, in the `plus` listener
int a = showProducts.getCount();
a++;
showProducts.setCount(a);
And don't forget
notifyDataSetChanged();
In ListView here i have all my contacts with check box. When i select 2 contacts from list and hit a button then selected list's value should be display in next activity. How can i do this?
Its my Activity class :
public class ContactListActivity extends Activity implements OnItemClickListener {
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
ContanctAdapter objAdapter = new ContanctAdapter(ContactListActivity.this, R.layout.alluser_row, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position, long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
private void showCallDialog(String name, final String phoneNo) {
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("Call?");
alert.setMessage("Are you sure want to call " + name + " ?");
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + phoneNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phoneNumber));
startActivity(intent);
}
});
alert.show();
}
And My Adapter Class to Hold Data is
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
private Activity activity;
private List<ContactBean> items;
private int row;
private LayoutInflater inflater = null;
public ContanctAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(row, null);
holder.tvname = (TextView) convertView.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) convertView.findViewById(R.id.tvphone);
holder.checkbox = (ImageView) convertView.findViewById(R.id.img_checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return convertView;
ContactBean objBean = items.get(position);
holder.checkbox.setSelected((objBean.getIsSelected() == 1) ? true : false);
if (holder.tvname != null && null != objBean.getName() && objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo() && objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
holder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
items.get(position).isSelected = (v.isSelected()) ? 0 : 1;
notifyDataSetChanged();
}
});
return convertView;
}
public class ViewHolder {
public TextView tvname, tvPhoneNo;
private ImageView checkbox;
}
}
There is multiple ways to achieve that :
Method 1:
Use static class setter and getter method:
create static class and set values from first activity and get value from second activity
Method 2:
Post your values through the intent
Method 3:
Use database to store data from one activity and get data from other activity
Method 4:
Use Shared preference
Example:
Post values using Intent like this
Post values in Shared preference
Another tutorial for Shared preference
Try this, It may Help you
Add this code in your onitemClicklistener Listview Page
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
String TVNameitem = ((TextView) view.findViewById(R.id.tvname)).getText().toString();
String TVPhoneitem = ((TextView) view.findViewById(R.id.tvphone)).getText().toString();
Intent intent1 = new Intent(this,NextActivity.class);
intent1.putExtra("STRING_I_NEED_From_TVNAME", TVNameitem );
intent1.putExtra("STRING_I_NEED_From_TVPHONE",TVPhoneitem );
startActivity(intent1);
}
Add this code in your Nextactivty Oncreate for Getting Values, Then Show in Textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find);
Bundle extras = getIntent().getExtras();
String VALUE_1= extras.getString("STRING_I_NEED_From_TVNAME");
String Value_2 =extras.getString("STRING_I_NEED_From_TVPHONE");
TextView Textview1=(TextView)findViewById(R.id.CompanyText);
Textview1.setText(VALUE_1+":"+Value_2);
}
Create getter and setter to share contact details.
public class GetContacts {
private String contactNumber;
private String contactName;
GetContacts(){}// constructor without parameter.
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
}
Now set contact values to the setters in GetContact class
create an instance of GetContact class in your first Activity.
GetContact getContact= new GetContact();
And Set Parameters.
getContact.setContactNumber(phoneNumber);
getContact.setContactName(name);
Now its time to get those values in second activity.
create an instance of GetContact class in your second Activity like you did before.
And Get Parameters, and display into TextView.
textView1.setText(getContact.getContactNumber(phoneNumber));
textView2.setText(getContact.getContactName(name));
I have created an applicaton that shows a listview of some pictures from the internet in ListView. I want to show it in a GridView.I have tried using base adapter in place of list adapter! But that doesn't work as it cant take arg (the arg is in the code)
Can anyone help me to show this images in gridview?
Here is my code.
MainPage.java
public class MainPage extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
setContentView(R. layout. contacts_list);
final List<Model> list = new ArrayList<Model>();
/** This block is for getting the <span id="IL_AD9" class="IL_AD">image url</span> to <span id="IL_AD2" class="IL_AD">download from</span> the server **/
final GetDataFromDB getvalues = new GetDataFromDB();
final ProgressDialog dialog = ProgressDialog.show(MainPage.this,
"", "Gettting values from DB", true);
final CountDownLatch latch = new CountDownLatch(1);
new Thread (new Runnable() {
public void run() {
String response = getvalues.getImageURLAndDesciptionFromDB();
System.out.println("Response : " + response);
dismissDialog(dialog);
if (!response.equalsIgnoreCase("")) {
if (!response.equalsIgnoreCase("error")) {
dismissDialog(dialog);
// Got the response, now split it to get the image Urls and description
String all[] = response.split("##");
for(int k = 0; k < all.length; k++){
String urls_and_desc[] = all[k].split(","); // urls_and_desc[0] contains image url and [1] -> description.
list.add(get(urls_and_desc[1],urls_and_desc[0]));
}
}
} else {
dismissDialog(dialog);
}
latch.countDown();
}
}).start();
/*************************** GOT data from Server ********************************************/
try {
latch.await();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent intent = new Intent(MainPage.this, ViewImage.class);
Model model = list.get(position);
String myURL = model.getURL();
intent.putExtra("image", myURL);
startActivity(intent);}
});
}
public void dismissDialog(final ProgressDialog dialog){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
private Model get(String s, String url) {
return new Model(s, url);
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle("Exit!");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to leave?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainPage.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// your code.
}
MyCustomArrayAdapter.java
public class MyCustomArrayAdapter extends ArrayAdapter<Model> {
private final Activity context;
private final List<Model> list;
public MyCustomArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.list_layout_relative, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected ImageView image;
protected ProgressBar pb;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.list_layout_relative, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.text.setTextColor(Color.BLACK);
viewHolder.image = (ImageView) view.findViewById(R.id.image);
viewHolder.image.setVisibility(View.GONE);
viewHolder.pb = (ProgressBar) view.findViewById(R.id.progressBar1);
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.image.setTag(list.get(position).getURL());
holder.image.setId(position);
PbAndImage pb_and_image = new PbAndImage();
pb_and_image.setImg(holder.image);
pb_and_image.setPb(holder.pb);
new DownloadImageTask().execute(pb_and_image);
return view;
}
}
Model.java
public class Model {
private String name;
private String url;
public Model(String name, String url) {
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getURL() {
return url;
}
public void setURL(String url) {
this.url = url;
}
}
i wanna ask something else too.kinda off topic.. i am downlaoding images from the urls and display in gridview. but it downloads huge images that takes lots of data. is there anyway i can download thumbnails to that images to reduce data usage?
same code but instead of extend listActivity extend normal activity and defining xml with GridView with id foo or what ever you want.
GridView foo = (GridView) findViewById(R.id.foo);
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
foo.setAdapter(adapter);
The problem is as follows: When I click on the row, dialog opens where I enter new row value and click ok to save changes. The row is updated, but I need to exit view and go back again to see changes. How can I refresh view automatically when the sava button is clicked?
Here is my code for Dialog:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
And here is the code where I want to refresh view instead of doing it manually:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
I hope it's clear enough what I am looking for. Where my list is, I want the list to be refreshed automatically after updating row so the new content of the row shows up immediately instead of navigating to other view and going back. I will be appreciated for your help.
At some point, after you call EditListItemDialog and it finishes, you need to run NotifyDataSetChanged() on your listview adapter. onResume() is a good place to do it,
Hai i'm trying to develop an app where by i can send sms and email to a particular group of people..
I have a listview showing the contacts which are in my group.Each row is of the form
TextView(Name)TextView(phone) Checkbox(sms)
TextView(email id) Checkbox(mail)
I have used custom adapter to display the contact details to the listview.ihave set the onitemclick listener to find the position of the row..
I have to send sms and email to those contacts for which checkboxes have been set as true.how can i find the state of each of the checkboxes.
Please help me..lotz of thanx in advance..
I hav added below the custom adapetr i hv created..
public class ContactInfoAdapter extends ArrayAdapter{
private ArrayList<Boolean> mChecked_sms,mChecked_email;
Context context;
int layoutResourceId;
ContactInfo data[] = null;
public ContactInfoAdapter(Context context, int layoutResourceId, ContactInfo[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
mChecked_sms = new ArrayList<Boolean>();
mChecked_email = new ArrayList<Boolean>();
for (int i = 0; i < this.getCount(); i++) {
mChecked_sms.add(i, false);
mChecked_email.add(i,false);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ContactHolder holder;
View row = convertView;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ContactHolder();
holder.txtName = (TextView)row.findViewById(R.id.textViewName);
holder.txtPhone = (TextView) row.findViewById(R.id.textViewPhone);
holder.txtEmail = (TextView) row.findViewById(R.id.textViewEmail);
holder.cb_sms_state = (CheckBox) row.findViewById(R.id.checkBox1);
holder.cb_email_state = (CheckBox) row.findViewById(R.id.checkBox2);
row.setTag(holder);
}
else
{
holder = (ContactHolder)row.getTag();
}
ContactInfo contact = data[position];
holder.txtName.setText(contact.name);
holder.cb_sms_state.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (holder.cb_sms_state.isChecked()) {
mChecked_sms.set(position, true);
Toast.makeText(getContext(), "checked", 2).show();
} else {
mChecked_sms.set(position, false);
}
}
});
holder.cb_sms_state.setChecked(mChecked_sms.get(position));
holder.cb_email_state.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (holder.cb_email_state.isChecked()) {
mChecked_email.set(position, true);
Toast.makeText(getContext(), "checked", 2).show();
} else {
mChecked_email.set(position, false);
}
}
});
holder.cb_email_state.setChecked(mChecked_email.get(position));
holder.txtPhone.setText(contact.number);
holder.txtEmail.setText(contact.email);
return row;
}
static class ContactHolder
{
TextView txtName;
TextView txtPhone;
TextView txtEmail;
CheckBox cb_sms_state;
CheckBox cb_email_state;
}
}
The ContactInfo class is :
public class ContactInfo {
public String name;
public String number;
public String email;
public boolean sms_state;
public boolean email_state;
public ContactInfo(){
super();
}
public ContactInfo(String name,String number,String email,boolean sms_state,boolean email_state) {
super();
this.name = name;
this.number = number;
this.email = email;
this.sms_state = sms_state;
this.email_state = email_state;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setNUmber(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setSms_state(Boolean sms_state)
{
this.sms_state = sms_state;
}
public Boolean getSms_state(){
return sms_state;
}
public void setEmail_state(Boolean email_state)
{
this.email_state = email_state;
}
public Boolean getEmail_state(){
return email_state;
}
Inside the getView() method, you have to implement a OnCheckedChangeListener for the CheckBox.
Here is a listener code, say for example:
ChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
See the doc.
I think you need :
checkbox.isChecked()
Here's a simple sample:
mContactListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
CheckBox chkContact = (CheckBox) view.findViewById(R.id.listrow_contact_chkContact);
if (chkContact.isChecked()) {
...
}
});
I've had this problem with my app Hasta La Vista I've create a with custom listview with checked items and I needed to get checked items this was the solution:
ListView lv = getListView(); //ver listview
if(lv != null){
final SparseBooleanArray checkedItems = lv.getCheckedItemPositions(); //get checked items
if (checkedItems == null) {
return;
}
final int checkedItemsCount = checkedItems.size();
for (int i = 0; i < checkedItemsCount; ++i) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// This tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if(isChecked){
//get item from list and do something
lv.getAdapter().getItem(position);
}
}
}
As ListView views are recycled, you can not rely on listening on particular instance, you will have to store "checked" state in your data model. You will also need custom list adapter, where you create and populate individual entries. Following shall be done:
- in overriden getView(), either create new view ( in case no convertView was supplied ) or inflate new one
- populate viewv fields from you data model
- remove old onclick listener, and set new one ( can be anonymous inner class ) modifying your data model
PS: recycling views is important if your list is big