Deleting and editing list items in android? - android

I have a list view with two buttons edit and delete.On click of these buttons I either update or delete the items in the list view from my custom adapter.But the problem is if I add a new item to the list my previous changes are discarded and old values are displayed.
The following is my code for the adapter.
public class RoleList extends ArrayAdapter<String>
{
private ArrayList<String> name;
private ArrayList<String> username;
private ArrayList<String> password;
private ArrayList<String> role;
private Activity context;
public RoleList(Activity context, ArrayList<String> name, ArrayList<String> username, ArrayList<String> password, ArrayList<String> role)
{
super(context, R.layout.role_list,name);
this.context = context;
this.name = name;
this.username =username;
this.password = password;
this.role = role;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.role_list, null, true);
final TextView textViewName = (TextView) listViewItem.findViewById(R.id.tv_empname);
final TextView textViewusername = (TextView) listViewItem.findViewById(R.id.tv_empusername);
final TextView textViewPass = (TextView) listViewItem.findViewById(R.id.tv_emppassword);
final TextView textViewRole = (TextView) listViewItem.findViewById(R.id.tv_emprole);
Button edit = (Button) listViewItem.findViewById(R.id.btn_editRole);
Button delete = (Button) listViewItem.findViewById(R.id.btn_delRole);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
name.remove(position);
username.remove(position);
password.remove(position);
role.remove(position);
notifyDataSetChanged();
}
});
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d("Emp Info", name.get(position) + " " + username.get(position) + " " + password.get(position) + " " + role.get(position));
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.userreg);
dialog.setTitle("Edit Employee " + name.get(position) + " details");
final String[] arraySpinner = new String[]{"Manager","Stockist","Cashier","Accountant"};
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
final EditText emp_name = (EditText) dialog.findViewById(R.id.editTextName);
final EditText emp_uname = (EditText) dialog.findViewById(R.id.editTextUserName);
final EditText emp_pw = (EditText) dialog.findViewById(R.id.editTextPassword);
final Spinner emp_role = (Spinner) dialog.findViewById(R.id.spinner_role);
final TextView textRole = (TextView) dialog.findViewById(R.id.tv_selected_role);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item, arraySpinner);
emp_role.setAdapter(adapter);
emp_role.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "Role Selected is " + arraySpinner[position], Toast.LENGTH_SHORT).show();
String employee_role = arraySpinner[position];
textRole.setText(employee_role);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
emp_name.setText(name.get(position));
emp_uname.setText(username.get(position));
emp_pw.setText(password.get(position));
emp_role.setSelection(position);
Button buttoncancel = (Button) dialog.findViewById(R.id.buttonCancel);
buttoncancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button buttonChange = (Button) dialog.findViewById(R.id.buttonRegister);
buttonChange.setText("Change");
buttonChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
textViewName.setText(emp_name.getText().toString());
textViewusername.setText(emp_uname.getText().toString());
textViewPass.setText(emp_pw.getText().toString());
textViewRole.setText(textRole.getText());
dialog.dismiss();
}
});
dialog.show();
}
});
textViewName.setText(name.get(position));
textViewusername.setText(username.get(position));
textViewPass.setText(password.get(position));
textViewRole.setText(role.get(position));
return listViewItem;
}
}
The following is the code inside the activity for the Handler class.
public void userRolehandler()
{
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run()
{
RoleList roleList = new RoleList(UserRegistration.this,employee_name,emp_username,emp_password,employee_role);
Log.d("ARRAY SIZE", String.valueOf(employee_name.size()));
userList.setAdapter(roleList);
roleList.notifyDataSetChanged();
}
});
}
Code for constructing the json array.
public void userRoleArray() throws JSONException {
name = editTextName.getText().toString();
username = editTextUsername.getText().toString();
password = editTextPassword.getText().toString();
emp_role = textRole.getText().toString();
JSONObject jsonobj = new JSONObject();
jsonobj.put("name",name);
jsonobj.put("username",username);
jsonobj.put("password",password);
jsonobj.put("emp_role",emp_role);
rolejson.put(counter,jsonobj);
counter++;
}
Code for Parsing the array.
public void travRoleArray() throws JSONException {
response = "{\"result\":" + rolejson.toString() + "}";
Log.d("RESPONSE",response);
JSONObject jsonOb = new JSONObject(response);
JSONArray result = jsonOb.getJSONArray(JSON_ARRAY);
try
{
employee_name.clear();
emp_username.clear();
emp_password.clear();
employee_role.clear();
for (int i=0; i< result.length();i++)
{
JSONObject jObj = result.getJSONObject(i);
employee_name.add(i,jObj.getString(KEY_NAME));
emp_username.add(i, jObj.getString(KEY_UNAME));
emp_password.add(i, jObj.getString(KEY_PASS));
employee_role.add(i,jObj.getString(KEY_ROLE));
}
for (String name:employee_name)
{
Log.i("Name : ",name);
}
}catch (ArrayIndexOutOfBoundsException e)
{
Toast.makeText(UserRegistration.this, "Array Index out of bound exception", Toast.LENGTH_LONG).show();
}
}
The problem is that the array list gets updated or deleted inside the
adapter class but the json array inside the activity still has the old
values.I would like to know how can I update the activity from the
adapter so that the json array has the updated values?
Any help or suggestion is appreciated.Thank you.

Related

Return Back the Data from the Activity who calls the fragment dialog

I have a code that calls a fragment as an activity. From that fragment I select a data then give it back to the activity caller and here is my code.
Heres how I open the dialog
fragment_customer_list dialog = new fragment_customer_list();
dialog.show(getFragmentManager(),"CustomerList");
And here is how I return the value
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
add callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
}
});
I will call a function from the activity that calls the dialog to update the edittext.
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
The problem is the dialog is fixed in one activity. My question is how can I return the data from the activity caller? Since this fragment will be used by many activity
============================updated=============================
Here is how I open my fragment and i open it as a dialog
/* Open Customer List */
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
show_customer_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment_customer_list dialog = new fragment_customer_list();
dialog.setOnClickItemListener(new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
dialog.show(getFragmentManager(),"CustomerList");
}
});
And here is the whole code fragment_customer_list
public class fragment_customer_list extends DialogFragment {
private static final String TAG = "CustomerList";
DatabaseHelper myDb;
String pattern_email;
SimpleAdapter adapter;
private DialogInterface.OnClickListener listener;
private OnClickItemListener mListener;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_customer_list, container, false);
final ListView listView = (ListView) view.findViewById(R.id.customer_list);
myDb = new DatabaseHelper(getActivity());
pattern_email = credentials.email;
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer(pattern_email);
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
// add_activity callingActivity = (add_activity ) getActivity();
// callingActivity.onUserSelectValue(customer_name, customer_address);
if (mListener != null) {
mListener.value(customer_name, customer_address);
}
getDialog().dismiss();
}
});
android.widget.Button clickButton = (android.widget.Button) view.findViewById(R.id.close);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDialog().dismiss();
}
});
/* Search customer */
EditText customer_search = (EditText) view.findViewById(R.id.search_customer);
customer_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer_search(cs.toString(),pattern_email);
if (data.getCount() == 0) {
//Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
}
});
return view;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), R.style.WideDialog);
}
public void setOnClickItemListener(OnClickItemListener l) {
mListener = l;
}
interface OnClickItemListener {
void value(String name, String address);
}
}
As you can see on the code above there is Listview that has a code that same as this
add_activity callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
The code above will get the value from listview and call the onUserSelectValue from add_activity then close the dialog
and this is onUserSelectValue and it is located at add_activity
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
Here is my question.
How can I return the value of the listview to the textfield of the activity who opens the fragment(where the list view is located).
UPDATED CODE
I created a class called DialogHelper.java and this is the code
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
}
fragment_customer_list dialog = wr.get();
dialog.OnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null) return;
wr.get().dismiss();
}
}
In my customer_fragment_list.java I have a listview listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
TextView position3 = (TextView) view.findViewById(R.id.list_code);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
String customer_code = position3.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address,customer_code );
}
}
});
together with this
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address,String KUNNR);
}
public interface OnClickItemListener { void value(String name, String address, String code); }
and on my Activity this the code on how i open the dialog
/* Open Customer List */
DialogHelper.userSelectValue(add_covplan.this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(name);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(address);
}
});
you can do this. Don't know if you mean this?
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
private static WeakReference<Activity> wrActivity;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null || wrActivity == null || wrActivity.get() == null || wrActivity.get() != context) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
wrActivity = new WeakReference<>(context);
}
fragment_customer_list dialog = wr.get();
dialog.setOnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null || !wr.get().isShowing()) return;
wr.get().dismiss();
}
}
use
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
DialogHelper.userSelectValue(this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
edit answer
// Suppose this is a FragmentDialog
public class FragmentList {
private OnClickListener listener;
private ListView listView;
// Suppose this has your list listener
public void onResume() {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address);
}
}
});
}
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address);
}
}
// Suppose this is a Activity
class YourActivity extends Activity
{
private FragmentList fragmentList;
EditText customer_address;
EditText customer_name;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
fragmentList = new FragmentList();
customer_address = (EditText) findViewById(R.id.address);
customer_name = (EditText) findViewById(R.id.cusname);
fragmentList.setOnClickListener(new FragmentList.OnClickListener()
{
#Override
public void click(String name, String address)
{
// ...
customer_name.setText(name);
customer_address.setText(address);
}
});
}
}
You can use a ViewModel class implementation to share resources between Activity and Fragment. Share the single context across multiple usages of ViewModel, each sharing a the same ViewModel. It works with the observer and observable pattern and perfect for this use case. You can check details on how to implement it here

ListView with checkbox and send checked data to server in Android

I am creating app like e-commerce with listview that containing images, textbox and one checkbox. Now my question is that, i want send cheched item with their hole to serve on onClickListener.Before send it to server, I will pass it to next activity and this activity contains one application form where user can fill form after completion filling form when user click on button all user info and checked item data send to server database. I don't know how to pass checked item data to server. And one more main thing is that my listview data is retrieve from server using json and php. so please send me code or links that i can use for to do this things. Thank You
Here is my code of lisview:
public class Hotels extends Activity
{
// Declare Variables
JSONArray jsonarray = null;
SQLiteDatabase sqLite;
public static final String TAG_NAME = "name";
public static final String TAG_LOCATION = "location";
public static final String TAG_DESC = "description";
String name,arrival_date,departure_date,image,location,description,adult,kids;
ProgressDialog loading;
ListView list;
Button booknow;
ListViewAdapter adapter;
private ArrayList<Product> itemlist;
Product product;
static String Array = "MyHotels";
View view;
CheckBox click;
ArrayList<String> checked = new ArrayList<String>();
String hotel = "http://app.goholidays.info/getHotelData.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_item_layout);
itemlist = new ArrayList<Product>();
new ReadJSON().execute();
click = (CheckBox) findViewById(R.id.mycheckbox);
booknow = (Button) findViewById(R.id.bookhotel);
product = new Product();
list = (ListView) findViewById(R.id.myimagelist);
booknow.setOnClickListener(new MyPersonalClickListener("book_hotel",product,getApplicationContext()));
}
class ReadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Hotels.this,"Fetching Data","Please wait...",false,false);
}
#Override
protected String doInBackground(String... args) {
Product tempMenu;
try {
JSONObject jsonobject = JSONfunctions.getJSONfromURL(hotel);
jsonarray = jsonobject.optJSONArray(Array);
//parse date for dateList
for (int i = 0; i < jsonarray.length(); i++) {
tempMenu = new Product();
jsonobject = jsonarray.getJSONObject(i);
tempMenu.setName(jsonobject.getString("name"));
tempMenu.setLocation(jsonobject.getString("location"));
tempMenu.setImage_path(jsonobject.getString("image_name"));
tempMenu.setDescription(jsonobject.getString("description"));
tempMenu.setFacility1(jsonobject.getString("facility1"));
tempMenu.setFacility2(jsonobject.getString("facility2"));
tempMenu.setFacility3(jsonobject.getString("facility3"));
tempMenu.setFacility4(jsonobject.getString("facility4"));
tempMenu.setStar(jsonobject.getString("star"));
itemlist.add(tempMenu);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
adapter = new ListViewAdapter(Hotels.this, itemlist);
list.setAdapter(adapter);
loading.dismiss();
}
}
private class MyPersonalClickListener implements View.OnClickListener {
String book_hotel;
Product name;
Context context;
public MyPersonalClickListener(String book_hotel, Product product, Context context) {
this.book_hotel = book_hotel;
this.name = product;
this.context = context;
}
#Override
public void onClick(View v){
if (click.isChecked()) {
startActivity(new Intent(Hotels.this, BookHotel.class));
}
else
{
Toast.makeText(context, "Please Select Hotel", Toast.LENGTH_SHORT).show();
}
}
}
}
Adapter class of listview
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<Product> AllMenu = new ArrayList<>();
ImageLoader imageLoader;
int checkCounter = 0;
public ListViewAdapter(Context context, ArrayList<Product> itemlist) {
this.context=context;
AllMenu = itemlist;
imageLoader = new ImageLoader(context);
checkCounter = 0;
}
public int getCount() {
return AllMenu.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
// Declare Variables
final Product tempMenu = AllMenu.get(position);
final CheckBox c;
final ImageView image_path,facility1,facility_1;
ImageView facility2,facility_2;
ImageView facility3,facility_3;
ImageView facility4,facility_4;
ImageView star1,star2,star3,star4,star5;
TextView name,location,desc;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.viewpage, parent, false);
// Get the position
c = (CheckBox) view.findViewById(R.id.mycheckbox);
name = (TextView) view.findViewById(R.id.fh_name);
location = (TextView) view.findViewById(R.id.fh_loc);
desc = (TextView) view.findViewById(R.id.fh_desc);
facility1 = (ImageView) view.findViewById(R.id.fh_fc1);
facility_1 = (ImageView) view.findViewById(R.id.fh_fc11);
facility2 = (ImageView) view.findViewById(R.id.fh_fc2);
facility_2 = (ImageView) view.findViewById(R.id.fh_fc22);
facility3 = (ImageView) view.findViewById(R.id.fh_fc3);
facility_3 = (ImageView) view.findViewById(R.id.fh_fc33);
facility4 = (ImageView) view.findViewById(R.id.fh_fc4);
facility_4 = (ImageView) view.findViewById(R.id.fh_fc44);
star1 = (ImageView) view.findViewById(R.id.fh_s1);
star2 = (ImageView) view.findViewById(R.id.fh_s2);
star3 = (ImageView) view.findViewById(R.id.fh_s3);
star4 = (ImageView) view.findViewById(R.id.fh_s4);
star5 = (ImageView) view.findViewById(R.id.fh_s5);
image_path = (ImageView) view.findViewById(R.id.image_all_main);
c.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
if(c.isChecked() && checkCounter >=3) {
AllMenu.get(position).setSelected(false);
c.setChecked(false);
Toast.makeText(context, "You can select max 3 hotels!!", Toast.LENGTH_SHORT).show();
}
else {
Product p = (AllMenu).get(position);
p.setSelected(c.isChecked());
if(c.isChecked()) {
checkCounter++;
}
else {
checkCounter--;
}
}
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...");
ArrayList<Product> p = AllMenu;
for(int i=0;i<p.size();i++){
Product pp = p.get(i);
if(pp.isSelected()){
responseText.append("\n" + pp.getName() + "\t");
responseText.append("\t" + pp.getLocation());
}
}
Toast.makeText(context,
responseText, Toast.LENGTH_SHORT).show();
}
});
c.setTag(tempMenu);
c.setChecked(tempMenu.isSelected());
name.setText(tempMenu.getName());
location.setText(tempMenu.getLocation());
desc.setText(tempMenu.getDescription());
imageLoader.DisplayImage(tempMenu.getImage_path(),image_path);
if(tempMenu.getFacility1().equals("Pool")) {
facility1.setVisibility(view.VISIBLE);
facility_1.setVisibility(view.INVISIBLE);
}else {
facility_1.setVisibility(view.VISIBLE);
facility1.setVisibility(view.INVISIBLE);
}
if(tempMenu.getFacility2().equals("Bar")) {
facility2.setVisibility(view.VISIBLE);
facility_2.setVisibility(view.INVISIBLE);
}else {
facility_2.setVisibility(view.VISIBLE);
facility2.setVisibility(view.INVISIBLE);
}
if(tempMenu.getFacility3().equals("Gym")) {
facility3.setVisibility(view.VISIBLE);
facility_3.setVisibility(view.INVISIBLE);
}else {
facility_3.setVisibility(view.VISIBLE);
facility3.setVisibility(view.INVISIBLE);
}
if(tempMenu.getFacility4().equals("Theater")) {
facility4.setVisibility(view.VISIBLE);
facility_4.setVisibility(view.INVISIBLE);
}else {
facility_4.setVisibility(view.VISIBLE);
facility4.setVisibility(view.INVISIBLE);
}
if(tempMenu.getStar().equals("1")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.INVISIBLE);
star3.setVisibility(view.INVISIBLE);
star4.setVisibility(view.INVISIBLE);
star5.setVisibility(view.INVISIBLE);
}else if(tempMenu.getStar().equals("2")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.VISIBLE);
star3.setVisibility(view.INVISIBLE);
star4.setVisibility(view.INVISIBLE);
star5.setVisibility(view.INVISIBLE);
}else if(tempMenu.getStar().equals("3")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.VISIBLE);
star3.setVisibility(view.VISIBLE);
star4.setVisibility(view.INVISIBLE);
star5.setVisibility(view.INVISIBLE);
}else if(tempMenu.getStar().equals("4")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.VISIBLE);
star3.setVisibility(view.VISIBLE);
star4.setVisibility(view.VISIBLE);
star5.setVisibility(view.INVISIBLE);
}else if(tempMenu.getStar().equals("5")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.VISIBLE);
star3.setVisibility(view.VISIBLE);
star4.setVisibility(view.VISIBLE);
star5.setVisibility(view.VISIBLE);
}
else {
star1.setVisibility(view.INVISIBLE);
star2.setVisibility(view.INVISIBLE);
star3.setVisibility(view.INVISIBLE);
star4.setVisibility(view.INVISIBLE);
star5.setVisibility(view.INVISIBLE);
}
return view;
}
}
After selecting item from list it will come on this activity.
public class BookHotel extends AppCompatActivity {
EditText arrival,departure;
Calendar myCalendar;
Button booknow;
final String[] qtyValues = {"0","1","2","3","4"};
Spinner adult,children;
String chkin,chkout,persons,kids;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_hotel);
booknow = (Button) findViewById(R.id.bookmyhotel);
arrival = (EditText) findViewById(R.id.arrival_date);
departure = (EditText) findViewById(R.id.departure_date);
myCalendar = Calendar.getInstance();
adult = (Spinner) findViewById(R.id.adults);
children = (Spinner) findViewById(R.id.childrens);
booknow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(arrival.getText().length() <= 0){
arrival.setError("Please fill the field.!!");
}else if(departure.getText().length() <= 0){
departure.setError("Please fill the field.!!");
}else {
chkin = arrival.getText().toString();
chkout = departure.getText().toString();
persons = adult.getSelectedItem().toString();
kids = children.getSelectedItem().toString();
//Submit(chkin, chkout, persons, kids);
}
}
});
ArrayAdapter<String> aa=new ArrayAdapter<String>(getApplicationContext(),R.layout.qty_spinner_item,qtyValues);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adult.setAdapter(aa);
children.setAdapter(aa);
final DatePickerDialog.OnDateSetListener adate = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateArrival();
}
};
final DatePickerDialog.OnDateSetListener ddate = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDeparture();
}
};
arrival.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(BookHotel.this, adate, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
departure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(BookHotel.this, ddate, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateArrival() {
String myFormat = " MM/dd/yy "; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
arrival.setText(sdf.format(myCalendar.getTime()));
//departure.setText(sdf.format(myCalendar.getTime()));
}
private void updateDeparture() {
String myFormat = " MM/dd/yy "; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
//arrival.setText(sdf.format(myCalendar.getTime()));
departure.setText(sdf.format(myCalendar.getTime()));
}
}
I don't know how i can pass those selecting item and this info to server on onClickListener please help me solve this problem. Thank You
And here is another problem i will posted on it is this
Why people are giving negative mark to it. :( If u don't like then ignore it please. :( . I know my english is very bad. but please don't do like this i m really facing this problem. I will search all over but nothing i will find thier like this.
Finally i done this. Here is the my answer.
public class Hotels extends AppCompatActivity {
// Declare Variables
JSONParser jsonParser = new JSONParser();
JSONArray jsonarray = null;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_LOCATION = "location";
public static final String TAG_DESC = "description";
String f_date, l_date;
ArrayList<String> ne = new ArrayList<String>();
ProgressDialog loading;
ListView list;
Button booknow;
private ArrayList<Product> itemlist;
Product product;
static String Array = "MyHotels";
View view;
CheckBox click;
String user_id,start_date,end_date,chk_status;
String[] hotel_id;
String hotel = "http://app.goholidays.info/getHotelData.php";
String booking = "http://app.goholidays.info/insertIntoBooking.php";
SharedPreferences sp;
SharedPreferences.Editor editor;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_item_layout);
product = new Product();
itemlist = new ArrayList<Product>();
click = (CheckBox) findViewById(R.id.mycheckbox);
booknow = (Button) findViewById(R.id.bookhotel);
product = new Product();
list = (ListView) findViewById(R.id.myimagelist);
//get current date and time
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
sp = PreferenceManager.getDefaultSharedPreferences(Hotels.this);
editor = sp.edit();
//get all variables into string
user_id = sp.getString("id", TAG_ID);
start_date = sp.getString("start_date", f_date);
end_date = sp.getString("end_date", l_date);
chk_status = df.format(c.getTime());
booknow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hotel_id = new String[ne.size()];
hotel_id = ne.toArray(hotel_id);
for(int i = 0; i < hotel_id.length ; i++){
Log.d("string is",(String)hotel_id[i]);
}
if (hotel_id.length == 0) {
Toast.makeText(Hotels.this, "Please select Hotel..!", Toast.LENGTH_SHORT).show();
}else {
new BackTask().execute();
}
}
});
}
public class ListViewAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ArrayList<Product> AllMenu = new ArrayList<>();
ImageLoader imageLoader;
int checkCounter = 0;
public ListViewAdapter(Context context, ArrayList<Product> itemlist)
{
this.context = context;
AllMenu = itemlist;
imageLoader = new ImageLoader(context);
checkCounter = 0;
}
public int getCount() {
return AllMenu.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, final View convertView, final ViewGroup parent)
{
// Declare Variables
final Product tempMenu = AllMenu.get(position);
final CheckBox c;
final ImageView image_path, facility1, facility_1;
ImageView facility2, facility_2;
ImageView facility3, facility_3;
ImageView facility4, facility_4;
ImageView star1, star2, star3, star4, star5;
final TextView name, location, desc;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.viewpage, parent, false);
// Get the position
c = (CheckBox) view.findViewById(R.id.mycheckbox);
name = (TextView) view.findViewById(R.id.fh_name);
location = (TextView) view.findViewById(R.id.fh_loc);
desc = (TextView) view.findViewById(R.id.fh_desc);
facility1 = (ImageView) view.findViewById(R.id.fh_fc1);
facility_1 = (ImageView) view.findViewById(R.id.fh_fc11);
facility2 = (ImageView) view.findViewById(R.id.fh_fc2);
facility_2 = (ImageView) view.findViewById(R.id.fh_fc22);
facility3 = (ImageView) view.findViewById(R.id.fh_fc3);
facility_3 = (ImageView) view.findViewById(R.id.fh_fc33);
facility4 = (ImageView) view.findViewById(R.id.fh_fc4);
facility_4 = (ImageView) view.findViewById(R.id.fh_fc44);
star1 = (ImageView) view.findViewById(R.id.fh_s1);
star2 = (ImageView) view.findViewById(R.id.fh_s2);
star3 = (ImageView) view.findViewById(R.id.fh_s3);
star4 = (ImageView) view.findViewById(R.id.fh_s4);
star5 = (ImageView) view.findViewById(R.id.fh_s5);
image_path = (ImageView) view.findViewById(R.id.image_all_main);
c.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (c.isChecked() && checkCounter >= 3) {
AllMenu.get(position).setSelected(false);
c.setChecked(false);
Toast.makeText(context, "You can select max 3 hotels!!", Toast.LENGTH_SHORT).show();
} else {
Product p = (AllMenu).get(position);
p.setSelected(c.isChecked());
if (c.isChecked()) {
ne.add(AllMenu.get(position).getId());
checkCounter++;
} else {
ne.remove(AllMenu.get(position).getId());
checkCounter--;
}
}
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...");
ArrayList<Product> p = AllMenu;
for (int i = 0; i < p.size(); i++) {
Product pp = p.get(i);
if (pp.isSelected()) {
responseText.append("\n" + pp.getName() + "\t");
responseText.append("\t" + pp.getLocation());
}
}
Toast.makeText(context, responseText, Toast.LENGTH_SHORT).show();
}
});
c.setTag(tempMenu.get(position));
c.setChecked(tempMenu.isSelected());
name.setText(tempMenu.getName()+",");
location.setText(tempMenu.getLocation().trim());
desc.setText(tempMenu.getDescription().trim());
imageLoader.DisplayImage(tempMenu.getImage_path(), image_path);
if (tempMenu.getFacility1().equals("Pool")) {
facility1.setVisibility(view.VISIBLE);
facility_1.setVisibility(view.INVISIBLE);
} else {
facility_1.setVisibility(view.VISIBLE);
facility1.setVisibility(view.INVISIBLE);
}
if (tempMenu.getFacility2().equals("Bar")) {
facility2.setVisibility(view.VISIBLE);
facility_2.setVisibility(view.INVISIBLE);
} else {
facility_2.setVisibility(view.VISIBLE);
facility2.setVisibility(view.INVISIBLE);
}
if (tempMenu.getFacility3().equals("Gym")) {
facility3.setVisibility(view.VISIBLE);
facility_3.setVisibility(view.INVISIBLE);
} else {
facility_3.setVisibility(view.VISIBLE);
facility3.setVisibility(view.INVISIBLE);
}
if (tempMenu.getFacility4().equals("Theater")) {
facility4.setVisibility(view.VISIBLE);
facility_4.setVisibility(view.INVISIBLE);
} else {
facility_4.setVisibility(view.VISIBLE);
facility4.setVisibility(view.INVISIBLE);
}
if (tempMenu.getStar().equals("1")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.INVISIBLE);
star3.setVisibility(view.INVISIBLE);
star4.setVisibility(view.INVISIBLE);
star5.setVisibility(view.INVISIBLE);
} else if (tempMenu.getStar().equals("2")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.VISIBLE);
star3.setVisibility(view.INVISIBLE);
star4.setVisibility(view.INVISIBLE);
star5.setVisibility(view.INVISIBLE);
} else if (tempMenu.getStar().equals("3")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.VISIBLE);
star3.setVisibility(view.VISIBLE);
star4.setVisibility(view.INVISIBLE);
star5.setVisibility(view.INVISIBLE);
} else if (tempMenu.getStar().equals("4")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.VISIBLE);
star3.setVisibility(view.VISIBLE);
star4.setVisibility(view.VISIBLE);
star5.setVisibility(view.INVISIBLE);
} else if (tempMenu.getStar().equals("5")) {
star1.setVisibility(view.VISIBLE);
star2.setVisibility(view.VISIBLE);
star3.setVisibility(view.VISIBLE);
star4.setVisibility(view.VISIBLE);
star5.setVisibility(view.VISIBLE);
} else {
star1.setVisibility(view.INVISIBLE);
star2.setVisibility(view.INVISIBLE);
star3.setVisibility(view.INVISIBLE);
star4.setVisibility(view.INVISIBLE);
star5.setVisibility(view.INVISIBLE);
}
return view;
}
}
class BackTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("start_date", start_date));
param.add(new BasicNameValuePair("end_date", end_date));
param.add(new BasicNameValuePair("chk_status", chk_status));
for (String value : hotel_id) {
param.add(new BasicNameValuePair("hotel_id[]", value));
}
param.add(new BasicNameValuePair("user_id", user_id));
JSONObject json = jsonParser.makeHttpRequest(booking, "POST", param);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully book a hotels
Intent intent = new Intent(Hotels.this, HomePage.class);
startActivity(intent);
// closing this screen
finish();
} else {
Log.d("failed to book hotel", json.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}

Retrieving data from listview when im using adapter

I am able to display the toast in my menuactivity but now i will need to get the selected data from listview and display it on another page. I have tried alot of methods and search on it but i cant seem to get it.
menuactivity :
public class MenuActivity extends Activity {
private String server = "http://172.16.156.56";
private String sql_table = "orders";
private ListView list;
private TextView txtOrder, txtMember, txtPrice;
private Button btnAdd;
ArrayList<String> rows;
ListView listView1;
Button btnSubmit;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
list=(ListView) findViewById(R.id.listView);
btnAdd = (Button)findViewById(R.id.button);
rows = new ArrayList<String>();
itemList=new ArrayList<CustomItem>();
itemList.add(new CustomItem("Fried Rice","description","1","Quantity"));
itemList.add(new CustomItem("Fried Noodle","description","2","Quantity"));
itemList.add(new CustomItem("Prawn noodle","description","3","Quantity"));
itemList.add(new CustomItem("Chicken Rice","description","4","Quantity"));
int[] prgmImages={R.drawable.friedrice,R.drawable.friednoodle,R.drawable.pnoodle,R.drawable.chickenrice};
listView1 = (ListView) findViewById(R.id.listView);
final CustomLVAdapter customLVAdapter = new CustomLVAdapter(this, itemList,prgmImages);
listView1.setAdapter(customLVAdapter);
txtOrder = (TextView) findViewById(R.id.txt1);
txtMember = (TextView) findViewById(R.id.txt2);
txtPrice = (TextView) findViewById(R.id.txt3);
btnSubmit = (Button) findViewById(R.id.button);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
selectedList = new ArrayList<CustomItem>();
int total = 0;
for (int i = 0; i < itemList.size(); i++) {
CustomItem object = itemList.get(i);
if (object.isSelected()) {
responseText.append(object.getItem() + "," + object.getQty() + ",");//item
selectedList.add(object);
//calculate price
total = total + Integer.parseInt(object.getQty()) * Integer.parseInt(object.getPrice());
}
}
Add(responseText.toString(), "5565", String.valueOf(total));
Intent i = new Intent(v.getContext(), ReceiptActivity.class);
startActivity(i);
Toast.makeText(getApplicationContext(), responseText + " $" + total,
Toast.LENGTH_SHORT).show();
SelectAll();
//store in database
//go to ReceiptActivity - membership, item, totalprice
}
});
}
public void Add(final String item, final String membership, final String price)
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/insertorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("item",item );
MyData.put("membership",membership );
MyData.put("price",price );
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
SelectAll();
}
public void SelectAll()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/fetchorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
rows.clear();
for(int i=0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String order = jsonChildNode.optString("item").toString();
String membership = jsonChildNode.optString("membership").toString();
String price = jsonChildNode.optString("price").toString();
rows.add(order + ", " + membership + ", " + price );
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MenuActivity.this,
android.R.layout.simple_list_item_1, rows);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue.add(MyStringRequest);
}
}
Receipt activity ( the page i wan to display my results)
public class ReceiptActivity extends Activity {
static public String txtOrder = "";
TextView foodorder;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
CustomLVAdapter item = (CustomLVAdapter) parent.getItemAtPosition(position);
TextView foodorder = (TextView)findViewById(R.id.foodorder);
foodorder.setText("Order:" +strOrder+" ");
Custom adapter
public class CustomLVAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<CustomItem> objectList;
private int[] imageId;
public static ArrayList<CustomItem> arl_food=new ArrayList<>();
private class ViewHolder {
TextView txt1,txt2,txt3;
CheckBox ckBox;
ImageView image;
NumberPicker np;
}
public CustomLVAdapter(Context context, ArrayList<CustomItem> objectList,int[]prgmImages){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.objectList = objectList;
this.imageId = prgmImages;
}
public int getCount(){
return objectList.size();
}
public CustomItem getItem (int position) {
return objectList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_checkbox_textview, null);
holder.txt1 = (TextView) convertView.findViewById(R.id.txt1);
holder.txt2 = (TextView) convertView.findViewById(R.id.txt2);
holder.txt3 = (TextView) convertView.findViewById(R.id.txt3);
holder.image=(ImageView) convertView.findViewById(R.id.image);
holder.ckBox = (CheckBox) convertView.findViewById(R.id.ckBox);
holder.np = (NumberPicker) convertView.findViewById(R.id.numberPicker);
holder.np.setMinValue(0);
holder.np.setMaxValue(10);
convertView.setTag(holder);
holder.ckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
CustomItem object = (CustomItem) cb.getTag();
Toast.makeText(context,
"You have selected: " + object.getItem() +
"Price: " + object.getPrice() +
"Qty: " + object.getQty(),
Toast.LENGTH_LONG).show();
object.setSelected(cb.isChecked());
}
}
);
holder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
NumberPicker p = picker;
CustomItem object = (CustomItem) p.getTag();
object.setQty(String.valueOf(newVal));
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
CustomItem object = objectList.get(position);
holder.txt1.setText(object.getItem());
holder.txt2.setText(object.getDesc());
holder.txt3.setText(object.getPrice());
holder.np.setTag(object);
holder.image.setImageResource(imageId[position]);
holder.ckBox.setChecked(object.isSelected());
holder.ckBox.setTag(object);
return convertView;
}
}
It looks like you are already starting an activity when the submit button is clicked. Now all you have to do is pass a couple extras in the intent you are creating.
So when you make the intent you should also do this:
...
Intent i = new Intent(v.getContext(), ReceiptActivity.class);
i.putExtra("PRICE", price);
i.putExtra("MEMBERSHIP", membership);
i.putExtra("ITEM", item);
startActivity(i);
...
Then in your new activity you will read out the extras in your onCreate method like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
int price = getIntent().getStringExtra("PRICE");
String membership = getIntent().getStringExtra("MEMBERSHIP");
CustomItem item = getIntent().getStringExtra("ITEM");
...
One Caveat! It looks like you are representing your items with the object CustomItem. In order to pass that as an extra it will have to implement Parcelable. When you implement Parcelable you will define how to turn the object and its fields into a "parcel" and how to turn a "parcel" back into your object. The google docs give a pretty good example for it.
I lied, another caveat! I would recommend that you make the keys for the extras "public static final String"s inside of your ReceiptActivity. That way you will have an easier time managing them.

How to retrieve values from ListView with JSON values on new activity?

The code below works fine. It populates a list with values from a JSON response and will open a new activity on selection of any of the items, as well as displaying the number of the item.
My question is how to have the selected item open an activity with the specific information from that item. Example: I select "Bob" from the List, I am taken to a new activity with the name of Bob, his email, and his phone. Or any other values that the JSON might have sent. If I select "George" it will do the same, but with the details for George.
I attempted unsuccessfully to do this on my own. Any help is appreciated.
Details.java code:
public class Details extends AppCompatActivity implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = Details.class.getSimpleName();
private static String url = "removed";
private List<LoadUsers> detailList = new ArrayList<LoadUsers>();
private ListView listView;
private CustomListAdapter adapter;
private Button ShowDetailsButton;
private Button AddDetails;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_view);
listView = (ListView) findViewById(R.id.lv);
adapter = new CustomListAdapter(this, detailList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
ShowDetailsButton = (Button) findViewById(R.id.show_details);
AddDetails = (Button) findViewById(R.id.add_details);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Loading...");
// changing action bar color
// getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#1b1b1b")));
ShowDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
detailList.clear();
// Showing progress dialog before making http request
showPDialog();
// Creating volley request obj
JsonArrayRequest detailsReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
LoadUsers details = new LoadUsers();
details.setTitle(obj.getString("name"));
details.setThumbnailUrl(obj.getString("image"));
details.setEmail(obj.getString("email"));
details.setPhone(obj.getString("phone"));
// adding to array
detailList.add(details);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(detailsReq);
}
});
AddDetails.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Details.this, MoreDetails.class);
startActivity(i);
}
});
}
private void showPDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidePDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, "Item Clicked: " + position, Toast.LENGTH_SHORT).show();
Intent i = new Intent(Details.this, onDetailsSelect.class);
startActivity(i);
}
}
CustomListAdapter.java code:
public class CustomListAdapter extends BaseAdapter {
public Activity activity;
private LayoutInflater inflater;
private List<LoadUsers> usersItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<LoadUsers> usersItems) {
this.activity = activity;
this.usersItems = usersItems;
}
#Override
public int getCount() {
return usersItems.size();
}
#Override
public Object getItem(int location) {
return usersItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView email = (TextView) convertView.findViewById(R.id.lvemail);
TextView phone = (TextView) convertView.findViewById(R.id.lvphone);
// getting user data for the row
LoadUsers m = usersItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// email
email.setText("Email: " + String.valueOf(m.getEmail()));
// phone
phone.setText("Phone: " + String.valueOf(m.getPhone()));
return convertView;
}
}
New Activity that is being opened on selection of item:
onDetailsSelect.java:
public class onDetailsSelect extends AppCompatActivity {
Toolbar toolbar;
ActionBarDrawerToggle mActionBarDrawerToggle;
DrawerLayout drawerLayout;
private TextView title, email, phone;
private List<LoadUsers> usersItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onuserselect);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NetworkImageView thumbNail = (NetworkImageView) findViewById(R.id.thumbnail);
title = (TextView) findViewById(R.id.title);
email = (TextView) findViewById(R.id.lvemail);
phone = (TextView) findViewById(R.id.lvphone);
}
}
Modify your onItemClick like that:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, "Item Clicked: " + position, Toast.LENGTH_SHORT).show();
TextView title = (TextView) view.findViewById(R.id.title);
String title_text = title.getText().toString();
TextView email = (TextView) view.findViewById(R.id.lvemail);
String email_text = email.getText().toString();
TextView phone = (TextView) view.findViewById(R.id.lvphone);
String phone_text = phone.getText().toString();
Intent i = new Intent(Details.this, onDetailsSelect.class);
i.putExtra("title_intent", title_text);
i.putExtra("email_intent", email_text);
i.putExtra("phone_intent", phone_text);
startActivity(i);
}
And retrieve the intent values in onDetailsSelect Activity, in onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
Intent i = getIntent();
String title = i.getStringExtra("title_intent");
String email = i.getStringExtra("email_intent");
String phone = i.getStringExtra("phone_intent");
}
You can pass your ArrayList and item position on which you have clicked in the ListView, to the new activity like this --
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String item_position = String.valueOf(position);
ArrayList<ListRowItem> full_listitem = listitem;
Intent intent = new Intent(context,SecondActivity.class);
Bundle extras = new Bundle();
extras.putString(CRRNT_ROW_NUMBER, item_position);
extras.putSerializable(LISTITEM, full_listitem);
intent.putExtras(extras);
startActivity(intent);
}
});
In your 2nd Activity, you have to receive these using the below code --
Intent intent = getIntent();
Bundle extras = intent.getExtras();
item_position = extras.getString(FirstActivity.CRRNT_ROW_NUMBER);
listitem = (ArrayList<ListRowItem>)extras.getSerializable(FirstActivity.LISTITEM);
position = Integer.parseInt(item_position);
currentlistitem = listitem.get(position);
String a = currentlistitem.getA();
String b = currentlistitem.getB();
For all these implementations, you have to implement Serializable interface in both your Activities and also in the LoadUsers (Getter/Setter) class.
Hope this helps!

Android - How to delete multiple items from listView with checkBox ?

i have an issue when i try to delete multiple checked items from my listView. If i start deleting from down to up items are removed from my list, but there is a problem when i do it from up to down or if random items are checked. The problem is the checked items are not deleted, but the unchecked items are deleted.
public class MainActivity extends ActionBarActivity {
private EditText etn,etl,etd;
private Button add;
private Button rmv;
private ListView listView;
private ArrayList<Data> list;
private MyCustomAdapter dataAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<Data>();
add = (Button) findViewById(R.id.btn_add);
etn = (EditText) findViewById(R.id.edit_name);
eta = (EditText) findViewById(R.id.edit_lastname);
etd = (EditText) findViewById(R.id.edit_document);
rmv = (Button) findViewById(R.id.btn_delete);
displayView();
}
public class Data {
long document;
String name;
String lastname;
boolean selected = false;
public Data(long document, String name, String lastname, boolean selected){
this.document=document;
this.name=nom;
this.lastname=lastname;
this.selected = selected;
}
public String getName(){
return name;
}
public String getLastName(){
return lastname;
}
public long getDocument(){
return document;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public void displayView(){
String name = etn.getText().toString();
String lastname= eta.getText().toString();
long document = Integer.valueOf(etd.getText().toString());
Data edata = new Data(document,name,lastname,false);
list.add(edata);
dataAdapter = new MyCustomAdapter(this,
R.layout.list_info, list);
listView.setAdapter(dataAdapter);
}
public void delete(View view){
deleteListItem();
}
private void deleteListItem(){
if(list.isEmpty()){
Toast.makeText(getApplicationContext(),
"No items to delete.",
Toast.LENGTH_LONG).show();
return;
}
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
dataAdapter.notifyDataSetChanged();
}
private class MyCustomAdapter extends ArrayAdapter<Data> {
private ArrayList<Data> list;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Data> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Data>();
this.list.addAll(list);
}
private class ViewHolder {
TextView name;
TextView lname;
TextView doc;
CheckBox ck;
}
#Override
public View getView(int position, View convertView, ViewGroupparent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ck = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.lname = (TextViewconvertView.findViewById(R.id.lastname);
holder.doc = (TextView)convertView.findViewById(R.id.document);
convertView.setTag(holder);
holder.ck.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Data edata = (Data) cb.getTag();
Toast.makeText(getApplicationContext(),
"Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
edata.setSelected(cb.isChecked());
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Data aux = list.get(position);
long document = aux.getDocument();
holder.doc.setText("Doc:" + Long.toString(document));
holder.name.setText (" " + "Name:" + aux.getName()+ " ");
holder.lname.setText("Last name:" + aux.getLastName());
holder.ck.setTag(aux);
holder.ck.setChecked(aux.isSelected());
return convertView;
}
}
I think problem resides in this block :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Try like this :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = dataAdapter.getItem(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Note : I am not sure, Please try and let me know the result .:)

Categories

Resources