sir, how do i refresh my listview if i pressed the back button in android emulator? i've clicked an item on activityA then goes to an edit form in activityB. after saving updates, if i pressed the back button, it should refresh the list.
here is my activityA
public class CustomListView extends Activity {
final Context context = this;
public static String name;
public static String number;
int REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
final ListView lv = (ListView) findViewById(R.id.srListView);
lv.setAdapter(new MyCustomBaseAdapter(this, searchResults));
info.close();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// TODO Auto-generated method stub
Object o = lv.getItemAtPosition(position);
final Contact fullObject = (Contact)o;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage("Select action")
.setCancelable(false)
.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(getApplicationContext(), "Edit ", Toast.LENGTH_LONG).show();
name = fullObject.getName();
number = fullObject.getPhoneNumber();
Intent intent = new Intent();
intent.setClass(CustomListView.this, EditDetails.class);
startActivityForResult(intent, REQUEST_CODE);
}
})
.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(getApplicationContext(), "Delete ", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel", 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();
}
});
}
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
info.close();
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_CODE) {
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(CustomListView.this, searchResults);
mcba.updateResults(searchResults);
info.close();
}
}
//edit or delete list when clicked
public void deleteEditOption()
{
}//end deleteEditOption()
}
and here is my activityB
public class EditDetails extends Activity{
public String nameChanged;
public String numChanged;
public String name;
public String num;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editdetails);
final EditText sqlName = (EditText)findViewById(R.id.editName);
final EditText sqlNumber = (EditText)findViewById(R.id.editNumber);
name = CustomListView.name;
num = CustomListView.number;
Button bUpdate = (Button)findViewById(R.id.editUpdate);
Button bView = (Button)findViewById(R.id.editView);
sqlName.setText(name);
sqlNumber.setText(num);
bUpdate.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
nameChanged = sqlName.getText().toString();
numChanged = sqlNumber.getText().toString();
GroupDb info = new GroupDb(EditDetails.this);
info.open();
long rowid = info.getRowId(name, num);
info.updateNameNumber(rowid+1, nameChanged, numChanged);
Toast.makeText(getApplicationContext(), rowid+" "+nameChanged+" "+numChanged, Toast.LENGTH_LONG).show();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
mcba.updateResults(searchResults);
Toast.makeText(getApplicationContext(), "Update Successful!", Toast.LENGTH_LONG).show();
info.close();
}
});
bView.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(EditDetails.this, CustomListView.class);
startActivityForResult(intent, 0);
}
});
}
}
if i clicked this bView button in my activityB, it updates the listview. but pressing the back button just shows my previous unupdated listview. thanks for help in advance
edit
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<Contact> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<Contact> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public void updateResults(ArrayList<Contact> results) {
searchArrayList = results;
//Triggers the list update
notifyDataSetChanged();
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
holder.status = (TextView) convertView.findViewById(R.id.status);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtPhone.setText(searchArrayList.get(position).getPhoneNumber());
holder.status.setText(searchArrayList.get(position).getStatus());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtPhone;
TextView status;
}
}
Rewrite
While I recommend customizing a CursorAdapter to work with your database. Let's change a couple points with your current code:
First create a field variable for mbca, (just like name and number).
MyCustomBaseAdapter mcba;
Second update how you initialize mbca in onCreate():
mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
//mcba.updateResults(searchResults); this line isn't necessary here
Third make a small change to onResume():
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
GroupDb info = new GroupDb(this);
info.open();
mcba.updateResults(info.getView());
info.close();
}
This works because updateResults() calls notifyDataSetChanged() and this updates the ListView automatically.
Related
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));
Hi I am building an android app that uses checkbox to delete checked data from SQLite database. I write this code to populate data from SQlite database.
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public static ArrayList<Integer> position=new ArrayList<Integer>();
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
final Holder mHolder;
final int a=pos;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.checkbox = (CheckBox) child.findViewById(R.id.checkbox);
mHolder.checkbox.setTag(a);
position.add(a);
mHolder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
//Toast.makeText(mContext, ""+a,Toast.LENGTH_LONG).show();
}
}
});
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
return child;
}
public class Holder {
CheckBox checkbox;
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
}
}
I have a button (Delete) on the listView activity.After checking the checkboxes When a user presses delete button It will delete the data which was cecked from database and show the rest of the data remaining in Database.
This is the activity where I am handling the click.
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
Button delete=(Button) findViewById(R.id.deleteBtn);
delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
if(userId.size()>0){
for(int i=0;i<DisplayAdapter.position.size();i++){
Toast.makeText(DisplayActivity.this, ""+i, Toast.LENGTH_SHORT).show();
View getView=userList.findViewWithTag(DisplayAdapter.position.get(i));
CheckBox checkbox = (CheckBox) getView
.findViewById(R.id.checkbox);
if(checkbox.isChecked()){
//Toast.makeText(DisplayActivity.this, ""+i, Toast.LENGTH_SHORT).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+userId.get(i), null);
displayData();
}
}
}
} catch (Exception e) {
Toast.makeText(DisplayActivity.this, "Nothing Selected", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
userList.setAdapter(disadpt);
mCursor.close();
}
}
It only deletes the first checked item from listview and as well databases.But i want to delete all the checked data from database.How do i do that? Details code and explanation would be appreciated. Thank in advance and sorry if i made any mistake.
I can give you a approach how you can implement this.
You can keep an ArrayList as a member variable and pass it to the constructor of DisplayAdapter. Whenever a user clicks your CheckCox add the position of the clicked item into your ArrayList and whenever user clicks it again just remove it from the ArrayList.
Then you can use an AsyncTask and in doInBackground() you can perform your delete operation from database and also delete data from ArrayList as well. Then inside your onpostExecute() you can call your notifyDatasetChanged() of your adapter.
The approach I use and thus recommend is this:
On your adapter add a checked callback:
List<YOUR_OBJ> checkedObjs;
onUserCheckBoxCallback callback;
...
public void OnCheckBoxCheckedCallback(onUserCheckBoxCallback callback) {
this.callback = callback;
}
//this part goes on bindView
yourCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
callback.onUserCheckBoxChanged(your_obj.get(pos), isChecked);
}
});
if (checkedObjs!= null && checkedObjs.size() > 0)
yourCheckbox.setChecked(checkedObjs.contains(your_obj));
//this goes inside the adapter class
public interface onUserCheckBoxCallback {
void onUserCheckBoxChanged(YOUR_OBJECT_HERE, boolean isChecked);
}
And on your activity you simply do this:
declare your adapter
HashSet<YOUR_OBJ> checkedObjs;
...
//this part goes on onCreate()
adapter.OnCheckBoxCheckedCallback(new onUserCheckBoxCallback() {
#Override
public void onUserCheckBoxChanged(your_obj_type your_obj,boolean isChecked) {
if (isChecked)
checkedObjs.add(your_obj);
else
checkedObjs.remove(your_obj);
}
});
Just iterate trough this list deleting all the objects !
Hope it helps!
The problem: I want to remove a item from my listview using a button in another activity.
I have tried several kinds of code, but it just doesn't seem to work.
Right know I use serializable to bundle the object to the other activity.
But I don't know how to remove it, from the other activity.
Can anybody help me with that?
Can I use the button from the second activity, in the first activity to delete the item from the listview?
Class A where I got my ListView
public class ListActivity extends Activity {
ListView list;
Button exit;
SimpleAdapter adapter;
final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
#Override``
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
for (int i = 0; i < title.length; i++) {
Map<String, String> datalist = new HashMap<String, String>();
datalist.put("title", title[i]);
datalist.put("subtitle", subtitle[i]);
data.add(datalist);
}
// getDataInList();
adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, new String[] { "title",
"subtitle" }, new int[] { android.R.id.text1,
android.R.id.text2 });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
Class B where I got my accept button.
When I click accept, the item from the listview in Class A should be removed.
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
int requestCode = 1;
SimpleAdapter adapter;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});``
//Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You should not directly remove the item from the view, but from the data displayed in it.
For example if your ListView is displaying items from an ArrayList, just remove the item in the ArrayList from you Activity B, and call myAdapter.notifyDataSetChanged() when back in the Activity A, which contains the adapter.
You can remove items by accessing to the ArrayList or by overriding the remove() method if you have only access to the adapter (assuming your adapter extends ArrayAdapter).
Also, you may have to override usefull Adapter methods like getCount(), getView()...
Thanks to all.
I found another solution thanks to remove row from another activity
Class A
public class ListActivity extends Activity {
ListView list;
Button exit;
static List<ListItems> items = new ArrayList<ListItems>();
public static int deletePos;
static ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
items = new ArrayList<ListItems>();
for (int i = 0; i < title.length; i++) {
ListItems s = new ListItems(title[i], subtitle[i]);
items.add(s);
}
adapter = new ListAdapter(this, android.R.layout.simple_list_item_2,
items);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
deletePos = position;
adapter.notifyDataSetChanged();
startActivity(intent);
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
Class B
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});
// Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int deletePos = ListActivity.deletePos;
ListActivity.items.remove(deletePos);
ListActivity.adapter.notifyDataSetChanged();
finish();
}
});
}
}
i am calling a web service to get some details and show them in a list view.now i have to show a image on that list view. i can retrieve the image url from JSON object. but when the image url contains null , i want to show a defult image in the list view. i know below code is the code segment which is use to that.but since im going to handle this inside of my adapter class (extends by BaseAdapter Class) i cant use it.. please guide me how to handle this...
here my Adapter class
public class NewsRowAdapter extends BaseAdapter {
static Dialog dialogs;
private static final String STIME = "StartTime";
private static final String END = "EndTime";
private static final String DATE = "Date";
private Context mContext;
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
public ImageLoader imageLoader;
//String response;
//Context context;
//Initialize adapter
public NewsRowAdapter(Context ctx,Activity act, int resource,ArrayList<HashMap<String, String>> d) {
super();
this.resource=resource;
this.data = d;
this.activity = act;
this.mContext = ctx;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public void showFirstDialog(final ArrayList<HashMap<String, String>> list){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle("Confirm your Action!");
// set dialog message
alertDialogBuilder
.setMessage("You Have Similar Kind of Appoinments!! Do you wanna Show them ?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(mContext, "Showing", Toast.LENGTH_LONG).show();
dialogpop(list);
}
})
.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();
}
});
alertDialogBuilder.show();
}
public void dialogshow(final String Date,final String Start,final String End){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle("Confirm your Action!");
// set dialog message
alertDialogBuilder
.setMessage("Click yes Confirm!!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
//MainActivity.this.finish();
Toast.makeText(mContext, "Yes clicked", Toast.LENGTH_LONG).show();
//check similer records
//if duplicates > 1 then show the popup list
//if(duplicateList.size()>1){
/*final Dialog dialogs = new Dialog(activity);
dialogs.setContentView(R.layout.dialog_list);
dialogs.setTitle("Select One");
ListView listView = (ListView) dialogs.findViewById(R.id.dialogList);
NewsRowAdapter nw = new NewsRowAdapter(mContext, activity, R.layout.dialog_row, duplicateList);
listView.setAdapter(nw);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
dialogs.dismiss();
}
});
dialogs.show();*/
// }
}
})
.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();
}
});
alertDialogBuilder.show();
}
public void showDuplicateDialog(ArrayList<HashMap<String, String>> list){
//CharSequence[] cs = list.toArray(new CharSequence[list.size()]);
AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(activity);
LayoutInflater infl = activity.getLayoutInflater();
View view = infl.inflate(R.layout.dialog_list, null);
ListView lv = (ListView) view.findViewById(R.id.dialogList);
//NewsRowAdapter nw = new NewsRowAdapter(mContext, activity, R.layout.dialog_row, list);
SimpleAdapter sim = new SimpleAdapter(mContext, list, R.layout.dialog_row, new String[] { STIME,END, DATE }, new int[] {
R.id.stime2,R.id.etime2, R.id.blank2});
lv.setAdapter(sim);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "item clicked ", Toast.LENGTH_LONG).show();
}
});
/*ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.two_line_list_item, android.R.id.text1, Names);*/
alertDialogBuilder2.setView(view)
/*alertDialogBuilder2.setAdapter(sim, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "item clicked ", Toast.LENGTH_LONG).show();
}
})
*/
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Accepted", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialogBuilder2.show();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row,null);
final TextView firstname = (TextView) vi.findViewById(R.id.fname);
final TextView lastname = (TextView) vi.findViewById(R.id.lname);
final TextView startTime = (TextView) vi.findViewById(R.id.stime);
final TextView endTime = (TextView) vi.findViewById(R.id.etime);
final TextView date = (TextView) vi.findViewById(R.id.blank);
final TextView hidID = (TextView) vi.findViewById(R.id.hidenID);
final ImageView img = (ImageView) vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song =data.get(position);
firstname.setText(song.get(MainActivity.TAG_PROP_FNAME));
lastname.setText(song.get(MainActivity.TAG_PROP_LNAME));
startTime.setText(song.get(MainActivity.TAG_STIME));
endTime.setText(song.get(MainActivity.TAG_ETIME));
date.setText(song.get(MainActivity.TAG_DATE));
hidID.setText(song.get(MainActivity.TAG_HID));
String theUrl = song.get(MainActivity.TAG_IMG);
if(theUrl.equalsIgnoreCase("null")){
/*Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.propic);
profPic.setImageBitmap(bImage);
ViewList v = new ViewList();
v.handleImage(theUrl, img);*/
}
else{
imageLoader.DisplayImage(song.get(MainActivity.TAG_IMG), img);
}
Button accept = (Button) vi.findViewById(R.id.btnAccepted);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final int x = (int) getItemId(position);
/*Intent zoom=new Intent(mContext, Profile.class);
zoom.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
zoom.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(zoom);*/
// get the intent from the hashmap check if there is similar date and time.
//then store them in a list or array.
String getDate = (String) date.getText();
String getStartTime = startTime.getText().toString();
String getEndTime = endTime.getText().toString();
ShortList sh = new ShortList();
ArrayList<HashMap<String, String>> duplicateList;
duplicateList=sh.getDuplicated(getDate, getStartTime, getEndTime);
if(duplicateList.size()>1){
//dialogshow(getDate,getStartTime,getEndTime);
showFirstDialog(duplicateList);
}
else{
dialogshow(getDate, getStartTime, getEndTime);
}
}
});
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getPname = hidID.getText().toString();
Toast.makeText(parent.getContext(), "view clicked: "+getPname , Toast.LENGTH_SHORT).show();
//get the id of the view
//check the id of the request
//call the web service acording to the id
Intent zoom=new Intent(parent.getContext(), Profile.class);
zoom.putExtra("PatientID", getPname);
parent.getContext().startActivity(zoom);
}
});
return vi;
}
public void dialogpop(ArrayList<HashMap<String, String>> list){
dialogs = new Dialog(activity);
dialogs.setContentView(R.layout.dialog_list);
dialogs.setTitle("Select One");
ListView listView = (ListView) dialogs.findViewById(R.id.dialogList);
//SimpleAdapter sim = new SimpleAdapter(mContext, list, R.layout.dialog_row, new String[] { STIME,END, DATE }, new int[] {
// R.id.stime2,R.id.etime2, R.id.blank2});
Adapter_For_Dialog nw = new Adapter_For_Dialog(mContext,activity, R.layout.dialog_row, list);
listView.setAdapter(nw);
dialogs.show();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int possision) {
// TODO Auto-generated method stub
return possision;
}
#Override
public long getItemId(int possision) {
// TODO Auto-generated method stub
return possision;
}
}
please help me :)
My problem is i cant use this code segment in my adapter Class
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.propic);
profPic.setImageBitmap(bImage);
Replace
if(theUrl.equalsIgnoreCase("null")){
with
if(theUrl==null || theUrl.equals("")){
and check if it works or not
I am developing a application which fetches some data from a web service and displays in a list view. I have implemented a custom adapter which is extended by BaseAdapter. In the getView() method I inflate the raw also.. Those are working perfectly.
My problem is I have implemented code to show a dialog box when user click on an list item, but now I want to show another dialog box which has a custom list inside it (when Yes button clicked). I also want to show some data in that listview. [I have a ArrayList filled with the data that I wanted] . I'm writing the code inside my adapter class. Can anyone give me some idea how to do it ?
This is my code:
public class NewsRowAdapter extends BaseAdapter {
private Context mContext;
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
//String response;
//Context context;
//Initialize adapter
public NewsRowAdapter(Context ctx,Activity act, int resource,ArrayList<HashMap<String, String>> d) {
super();
this.resource=resource;
this.data = d;
this.activity = act;
this.mContext = ctx;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void dialogshow(final String Date,final String Start,final String End){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle("Confirm your Action!");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
//MainActivity.this.finish();
// Toast.makeText(mContext, "Yes clicked", Toast.LENGTH_LONG).show();
//check similer records
// ShortList sh = new ShortList();
// ArrayList<HashMap<String, String>> duplicateList;
// duplicateList=sh.getDuplicated(Date, Start, End);
//if duplicates > 1 then show the popup list
// if(duplicateList.size()>1){
AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(activity);
LayoutInflater infl = activity.getLayoutInflater();
//View vi = infl.inflate(id, root)
alertDialogBuilder2.setView(infl.inflate(R.layout.dialog_row, null))
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Accepted", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialogBuilder2.show();
// }
}
})
.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();
}
});
alertDialogBuilder.show();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row,null);
final TextView firstname = (TextView) vi.findViewById(R.id.fname);
final TextView lastname = (TextView) vi.findViewById(R.id.lname);
final TextView startTime = (TextView) vi.findViewById(R.id.stime);
final TextView endTime = (TextView) vi.findViewById(R.id.etime);
final TextView date = (TextView) vi.findViewById(R.id.blank);
final ImageView img = (ImageView) vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song =data.get(position);
firstname.setText(song.get(MainActivity.TAG_PROP_FNAME));
lastname.setText(song.get(MainActivity.TAG_PROP_LNAME));
startTime.setText(song.get(MainActivity.TAG_STIME));
endTime.setText(song.get(MainActivity.TAG_ETIME));
date.setText(song.get(MainActivity.TAG_DATE));
//imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), img);
Button accept = (Button) vi.findViewById(R.id.button1);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final int x = (int) getItemId(position);
/*Intent zoom=new Intent(mContext, Profile.class);
zoom.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
zoom.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(zoom);*/
// get the intent from the hashmap check if there is similar date and time.
//then store them in a list or array.
String getDate = (String) date.getText();
String getStartTime = startTime.getText().toString();
String getEndTime = endTime.getText().toString();
dialogshow(getDate,getStartTime,getEndTime);
}
});
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getFname = firstname.getText().toString();
Toast.makeText(parent.getContext(), "view clicked: "+getFname , Toast.LENGTH_SHORT).show();
//get the id of the view
//check the id of the request
//call the web service acording to the id
Intent zoom=new Intent(parent.getContext(), Profile.class);
parent.getContext().startActivity(zoom);
}
});
return vi;
}
You are on the right track, Here is what i used to dynamically display a Dialog with a list of items in it.
For reference a similar Question was asked here : Android custom list dialog
//String[] list_data; Preloaded with a String array
final CharSequence[] items = new CharSequence[list_data.length];
for (int i = 0; i < list_data.length; i++) {
items[i] = list_data[i];
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select the data you want");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Get the id of the item
diag_callback();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void diag_callback() {
//Do someting when the user has made his selection
}
Hope this sorts out your problem.
For your concern I hope that you know creating customized list view.
Fallow undermentioned code that contains customized dialog with customized list view. I hope you can perform Adapter and model part by your's
final Dialog new_dialog = new Dialog(getParent());
new_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
new_dialog.setContentView(R.layout.customize_dialog_list_view);
new_dialog.setCancelable(false);
cuc = new CommanUtilityClass();
SharedPreferences sp = getSharedPreferences("provider",0);
String services = sp.getString("services","");
Log.i("Servicesss",bAllServices);
TextView service = (TextView) new_dialog.findViewById(R.id.cdlv_service_provider);
TextView hour = (TextView) new_dialog.findViewById(R.id.cdlv_working_hours);
TextView appointment_time = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_time);
TextView appointment_date = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_date);
String[] ampm = myTiming[which].split(":");
Log.d("xxxooo", ampm[0]);
appointment_time.setText(Html.fromHtml("<b>Appointment time :</b>" + myTimingToShow[which].split("/")[0]));
appointment_date.setText(Html.fromHtml("<b>Appointment date :</b>" + selected));
service.setText(Html.fromHtml("<b>Service provider :</b>"+ cuc.toTheUpperCase(bsp_name)));
hour.setText(Html.fromHtml("<b>Working hours :</b>"+ cuc.toTheUpperCase(bsp_availability)));
lv = (ListView) new_dialog.findViewById(R.id.cdlv_list);
CustomDialogArrayAdapter cdaa = new CustomDialogArrayAdapter(getApplicationContext(),m_ArrayList);
lv.setAdapter(cdaa);
new_dialog.show();
ImageButton btn_cdlv_cancel = (ImageButton) new_dialog.findViewById(R.id.cdlv_cancel);
btn_cdlv_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new_dialog.dismiss();
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(
AdapterView<?> arg0,
View arg1,
int arg2,
long arg3) {
Log.d("checkforbookedslots", booked_slots);
final_time_selected = myTiming[which];
String final_duration = m_ArrayList.get(arg2).provider_service_duration;
Log.d("adiadicheck", check_for_booking_list);
if (checkOverlapSlot(final_time_selected,final_duration)) {
Log.d("gp","seven12aa");
SharedPreferences sp = getSharedPreferences("booking_detail",0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("provider_service",m_ArrayList.get(arg2).provider_service);
editor.putString("provider_service_duration",m_ArrayList.get(arg2).provider_service_duration);
editor.putString("provider_service_price",m_ArrayList.get(arg2).provider_service_price);
editor.putString("service_id",m_ArrayList.get(arg2).provider_service_id);
editor.commit();
SessionManagement sm = new SessionManagement(getParent());
// sm.checkLogin();
if (sm.isLoggedIn()) {
Log.d("viv2","1");
Intent edit = new Intent(SelectedService.this,UserLoggedActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("UserLoggedActivity",edit);
} else {
Log.d("viv2","2");
Intent edit = new Intent(SelectedService.this,UserNoLoggedActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("UserNoLoggedActivity",edit);
}
new_dialog.dismiss();
}
}
});
CUSTOM DIALOG BOX WITH CUSTOM LISTVIEW :::
public class MainActivity extends Activity {
private Button btnOpenDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> strArrlst = new ArrayList<String>();
for (int i = 0; i < 15; i++) {
strArrlst.add("Number: " + i);
}
btnOpenDialog = (Button) findViewById(R.id.btn_open_dialog);
btnOpenDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Dialog box is btn click", "");
final Dialog dialog = new Dialog(MainActivity.this);
Toast.makeText(getApplicationContext(), "btn is click", Toast.LENGTH_SHORT).show();
// tell the Dialog to use the dialog.xml as it's layout
// description
dialog.setContentView(R.layout.custom_dailog_box);
dialog.setTitle("Android Custom Dialog Box");
TextView txt = (TextView) dialog.findViewById(R.id.txt);
txt.setText("This is an Android custom Dialog Box Example! Enjoy!");
ListView dialogLIst = (ListView) dialog.findViewById(R.id.lstvw_open_custom_dialog);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, android.R.id.text1,
// values);
// dialogLIst.setAdapter(adapter);
AdapterListC adapListC = new AdapterListC(getApplicationContext(), strArrlst);
dialogLIst.setAdapter(adapListC);
dialogLIst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
dialog.dismiss();
Toast.makeText(getApplicationContext(), "This is click position is" + position, Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
ADAPTER CLASS:::
public class AdapterListC extends BaseAdapter {
public AdapterListC(Context context_, ArrayList<String> arrlstString) {
super();
this.context_ = context_;
this.arrlstString = arrlstString;
mInflater = (LayoutInflater) context_.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Context context_;
ArrayList<String> arrlstString;
private LayoutInflater mInflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrlstString.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrlstString.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Viewolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new Viewolder();
holder.txtName = (TextView) convertView.findViewById(R.id.txt_listitem);
convertView.setTag(holder);
} else {
holder = (Viewolder) convertView.getTag();
}
holder.txtName.setText(arrlstString.get(position).toString());
return convertView;
}
class Viewolder {
TextView txtName;
}
}