Retrieving data from listview when im using adapter - android

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.

Related

Adapter for objects from JSON

I get data in JSON from API, and there are id and url. Now, i need to create a button "Add to favorites" for each image that i display. When i try to set adapter.setListener(this);, i get an error, because i can't use string format.
How can i resolve this problem? I spend 5 hours on this, and can't resolve it :(
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listItem);
favorites = findViewById(R.id.buttonFav);
catDetailsArrayList = new ArrayList<>();
myAdapter = new MyAdapter(MainActivity.this ,catDetailsArrayList);
searchbtn = findViewById(R.id.buttonSearch);
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
catDetailsArrayList.clear();
myAdapter.notifyDataSetChanged();
displayCats();
}
});
});
}
private void displayCats() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String jsonCatUrl2 = jsonObject1.getString("url");
String jsonCatId2 = jsonObject1.getString("id");
CatDetails catDetails = new CatDetails();
catDetails.setUrl(jsonCatUrl2);
catDetails.setId(jsonCatId2);
catDetailsArrayList.add(catDetails);
}
listView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
MyAdapter:
public class MyAdapter extends BaseAdapter {
public Activity activity;
public ArrayList<CatDetails> catDetailsArrayList;
public LayoutInflater inflater;
Button btn;
TextView idnr;
public MyAdapter(Activity activity, ArrayList<CatDetails> catDetailsArrayList) {
this.activity = activity;
this.catDetailsArrayList = catDetailsArrayList;
}
#Override
public Object getItem(int position) {
return catDetailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (inflater == null) {
inflater = this.activity.getLayoutInflater();
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
}
ImageView imageView = convertView.findViewById(R.id.ImageView);
final CatDetails catDetails = this.catDetailsArrayList.get(position);
Picasso.get().load(catDetails.getUrl()).into(imageView);
idnr =convertView.findViewById(R.id.textView);
btn = convertView.findViewById(R.id.buttonFav);
final String id = catDetails.getId();
idnr.setText(catDetails.getId());
return convertView;
}
#Override
public int getCount() {
return this.catDetailsArrayList.size();
}
I display the id that i receive from server for each item, it's ok, but i don't know how to set the button "add to favorites" to works fine. It must receive item id (that i received from server) as a param, but id is in string format.
final String id = catDetails.getId();
change it to
final String id = Integer.toString(catDetails.getId());

Search Filter moves to tab fragments

I am working on an Activity which is a search page. It contains some values with edittext and spinner. After giving the values and clicking on search button it moves to tab fragments, there contains search results divided by three tabs (By date, By price, By city). I just tested to do on date first but it is not displaying. Please help me on this.
Search Page:
public class Search extends AppCompatActivity {
EditText name,to,from;
Spinner cscope,strainer,sinstitute,scity,scountry,cstype,sgender,sdisable,sprice;
String[] able={"Yes","No"};
String[] sex={"Male only","Female only","Both Male and Female"};
String[] price={"Free","1900S.R","1500S.R"};
String[] city={"Riyadh"};
Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
name= (EditText) findViewById(R.id.search_csname);
cscope= (Spinner) findViewById(R.id.search_scope);
strainer= (Spinner) findViewById(R.id.search_trainerName);
sinstitute= (Spinner) findViewById(R.id.search_instName);
scity= (Spinner) findViewById(R.id.search_city);
scountry= (Spinner) findViewById(R.id.search_country);
cstype= (Spinner) findViewById(R.id.search_ctype);
sgender= (Spinner) findViewById(R.id.search_gender);
sdisable= (Spinner) findViewById(R.id.search_disabled);
sprice= (Spinner) findViewById(R.id.search_price);
search= (Button) findViewById(R.id.searchNow);
ArrayAdapter<String> gen=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,sex);
gen.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sgender.setAdapter(gen);
ArrayAdapter<String> disableness=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,able);
disableness.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sdisable.setAdapter(disableness);
ArrayAdapter<String> pricess=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,price);
pricess.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sprice.setAdapter(pricess);
ArrayAdapter<String> cities=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,city); cities.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
scity.setAdapter(cities);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String sname=name.getText().toString();
final String seprice=sprice.getSelectedItem().toString();
final String secity=scity.getSelectedItem().toString();
final String sedate=from.getText().toString();
Intent s=new Intent(getApplicationContext(),SearchResults.class);
s.putExtra("csname",sname);
s.putExtra("csprice",seprice);
s.putExtra("cscity",secity);
s.putExtra("csdate",sedate);
startActivity(s);
}
});
}
public void selectToDate(View view){
DialogFragment tofrag=new SelectTodateFragment();
tofrag.show(getSupportFragmentManager(),"Date Picker");
}
public void poptoDate(int date,int month,int year){
to= (EditText) findViewById(R.id.search_to);
assert to != null;
to.setText(date+"/"+month+"/"+year);
}
#SuppressLint("ValidFragment")
public class SelectTodateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar tocal=Calendar.getInstance();
int yy=tocal.get(Calendar.YEAR);
int mm=tocal.get(Calendar.MONTH);
int dd=tocal.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
#Override
public void onDateSet(DatePicker view, int year, int mm, int dd) {
poptoDate(year, mm+1, dd);
}
}
public void selectFromDate(View view){
DialogFragment newfrag=new SelectFromdateFragment();
newfrag.show(getSupportFragmentManager(),"Date Picker");
}
public void popDate(int date,int month,int year){
from= (EditText) findViewById(R.id.search_from);
assert from != null;
from.setText(date+"/"+month+"/"+year);
}
#SuppressLint("ValidFragment")
public class SelectFromdateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
#Override
public void onDateSet(DatePicker view, int year, int mm, int dd) {
popDate(year, mm+1, dd);
}
}
}
Search Results Page:
public class SearchResults extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
private TabLayout tabs;
private ViewPager viewPager;
Bundle bundle=new Bundle();
private SearchPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tabs = (TabLayout) findViewById(R.id.search_tabLayout);
viewPager = (ViewPager) findViewById(R.id.search_pager);
tabs.addTab(tabs.newTab().setText("By Price"));
tabs.addTab(tabs.newTab().setText("By Date"));
tabs.addTab(tabs.newTab().setText("By City"));
tabs.setTabGravity(tabs.GRAVITY_FILL);
tabs.setHorizontalScrollBarEnabled(false);
pager = new SearchPager(getSupportFragmentManager(), tabs.getTabCount());
viewPager.setAdapter(pager);
Intent h=getIntent();
String cname=h.getStringExtra("csname");
String byprice=h.getStringExtra("csprice");
String bydate=h.getStringExtra("csdate");
String bycity=h.getStringExtra("cscity");
bundle.putString("coname",cname);
bundle.putString("coprice",byprice);
bundle.putString("codate",bydate);
bundle.putString("cocity",bycity);
pager.getData(bundle);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabs));
tabs.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Search pagerAdapter:
public class SearchPager extends FragmentStatePagerAdapter {
int tabCount;
private Bundle args=new Bundle();
public SearchPager(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount = tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment tab1 = new SearchPrice();
getData(args);
tab1.setArguments(args);
return tab1;
case 1:
Fragment tab2 = new SearchDate();
getData(args);
tab2.setArguments(args);
return tab2;
case 2:
Fragment tab3 = new SearchCity();
getData(args);
tab3.setArguments(args);
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
public void getData(Bundle bundle) {
this.args=bundle;
}
}
Search BYPrice:
public class SearchPrice extends Fragment {
private ListView listView;
private ProgressDialog mprogress;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private SpriceAdapter adapter;
TextView id;
Handler mHandler;
static String sname;
static String sprice;
public SearchPrice() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_search_price, container, false);
mHandler = new Handler();
id = (TextView) rootView.findViewById(R.id.copriceId);
listView = (ListView) rootView.findViewById(R.id.searchPriceList);
adapter = new SpriceAdapter(getActivity(), alist);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setScrollingCacheEnabled(false);
if (getArguments() != null) {
sname = this.getArguments().getString("coname");
sprice = this.getArguments().getString("coprice");
}
final String turl = "http://adoxsolutions.in/numuww/services/courses";
new ByPrice(this).execute(turl);
return rootView;
}
private class ByPrice extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog;
public ByPrice(SearchPrice activity) {
dialog = new ProgressDialog(activity.getContext());
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Data...");
dialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Void doInBackground(String... turl) {
try {
URL url = new URL(turl[0]);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Course");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jsArray.getJSONObject(k);
final String cid = jobj.getString("id");
final String cn = jobj.getString("course");
final String dt = jobj.getString("date");
map.put("id", cid);
map.put("course", cn);
map.put("date", dt);
map.put("trainer", jobj.getString("trainer"));
map.put("country", jobj.getString("country"));
map.put("city", jobj.getString("city"));
map.put("days", jobj.getString("no_days"));
map.put("hours", jobj.getString("tot_hrs"));
map.put("img", jobj.getString("img"));
alist.add(map);
mHandler.post(new Runnable() {
#Override
public void run() {
if (cn.equals(sname) || dt.equals(sprice)) {
Log.d("Value", cid);
id.setText(cid);
listView.setAdapter(adapter);
}
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
class SpriceAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
private Typeface typeface;
public SpriceAdapter(Context c, ArrayList<HashMap<String, String>> list) {
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final String id = MyArr.get(position).get("id");
if (convertView != null) {
convertView = inflater.inflate(R.layout.searchlist, parent, false);
TextView cname = (TextView) convertView.findViewById(R.id.searchlistName);
TextView tname = (TextView) convertView.findViewById(R.id.strainerName);
TextView country = (TextView) convertView.findViewById(R.id.searchcoName);
TextView city = (TextView) convertView.findViewById(R.id.searchciName);
TextView date = (TextView) convertView.findViewById(R.id.sdateTime);
TextView time = (TextView) convertView.findViewById(R.id.scourseTime);
TextView hours = (TextView) convertView.findViewById(R.id.scourseHours);
ImageView image = (ImageView) convertView.findViewById(R.id.scphoto);
String cn = (MyArr.get(position).get("course"));
String tn = (MyArr.get(position).get("trainer"));
String co = (MyArr.get(position).get("country"));
String ci = (MyArr.get(position).get("city"));
String dat = (MyArr.get(position).get("date"));
String dys = (MyArr.get(position).get("days"));
String hrs = (MyArr.get(position).get("hours"));
String c = context.getString(R.string.comma);
String ob = " ( ";
String cb = " ) ";
String h = " Hours";
String d = " Days";
String trainerName = tn + c;
String cdays = dys + d;
String chrs = ob + hrs + h + cb;
try {
if(hrs != null || !hrs.equals("")) {
String h1="0 Hours";
String chs=ob + h1 + cb;
hours.setText(chs);
}else{
hours.setText(chrs);
}
// image.setImageBitmap(loadBitmap(hlist.get(position).get("img")));
Glide.with(context).load(MyArr.get(position).get("img")).into(image);
cname.setText(cn);
tname.setText(trainerName);
country.setText(co);
city.setText(ci);
date.setText(dat);
time.setText(cdays);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o=new Intent(context,CourseScreen.class);
o.putExtra("id",id);
context.startActivity(o);
}
});
} catch(Exception e){
e.printStackTrace();
}
}
return convertView;
}
}
}
Search ByDate:
public class SearchDate extends Fragment {
private ListView listView;
private ProgressDialog mprogress;
TextView id;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private SdateAdapter adapter;
Handler mHandler;
static String sname;
static String sdate;
public SearchDate() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_search_date, container, false);
mHandler = new Handler();
id= (TextView) rootView.findViewById(R.id.courseId);
listView= (ListView) rootView.findViewById(R.id.searchDateList);
adapter = new SdateAdapter(getActivity(), alist);
listView.setAdapter(adapter);
listView.setScrollingCacheEnabled(false);
adapter.notifyDataSetChanged();
if (getArguments() != null) {
sname = this.getArguments().getString("coname");
sdate = this.getArguments().getString("codate");
}
final String turl = "http://adoxsolutions.in/numuww/services/courses";
new ByDate(this).execute(turl);
return rootView;
}
private class ByDate extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog;
public ByDate(SearchDate activity)
{
dialog = new ProgressDialog(activity.getContext());
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Data...");
dialog.show();
}
protected Void doInBackground(String... turl) {
try {
URL url = new URL(turl[0]);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Course");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jsArray.getJSONObject(k);
final String cid=jobj.getString("id");
final String cn=jobj.getString("course");
final String dt=jobj.getString("date");
map.put("id",cid);
map.put("course",cn);
map.put("date", dt);
map.put("trainer", jobj.getString("trainer"));
map.put("country", jobj.getString("country"));
map.put("city", jobj.getString("city"));
map.put("days", jobj.getString("no_days"));
map.put("hours", jobj.getString("tot_hrs"));
map.put("img", jobj.getString("img"));
alist.add(map);
mHandler.post(new Runnable() {
#Override
public void run() {
if(cn.equals(sname) || dt.equals(sdate) ) {
Log.d("Value",cid);
id.setText(cid);
}
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
class SdateAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
private Typeface typeface;
public SdateAdapter(Context c, ArrayList<HashMap<String, String>> list) {
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final String id = MyArr.get(position).get("id");
final String dt=MyArr.get(position).get("date");
if (convertView != null) {
convertView = inflater.inflate(R.layout.searchlist, parent, false);
TextView cname = (TextView) convertView.findViewById(R.id.searchlistName);
TextView tname = (TextView) convertView.findViewById(R.id.strainerName);
TextView country = (TextView) convertView.findViewById(R.id.searchcoName);
TextView city = (TextView) convertView.findViewById(R.id.searchciName);
TextView date = (TextView) convertView.findViewById(R.id.sdateTime);
TextView time = (TextView) convertView.findViewById(R.id.scourseTime);
TextView hours = (TextView) convertView.findViewById(R.id.scourseHours);
ImageView image = (ImageView) convertView.findViewById(R.id.scphoto);
String cn = (MyArr.get(position).get("course"));
String tn = (MyArr.get(position).get("trainer"));
String co = (MyArr.get(position).get("country"));
String ci = (MyArr.get(position).get("city"));
String dat = (MyArr.get(position).get("date"));
String dys = (MyArr.get(position).get("days"));
String hrs = (MyArr.get(position).get("hours"));
String c = context.getString(R.string.comma);
String ob = " ( ";
String cb = " ) ";
String h = " Hours";
String d = " Days";
String trainerName = tn + c;
String cdays = dys + d;
String chrs = ob + hrs + h + cb;
try {
if(hrs != null || !hrs.equals("")) {
String h1="0 Hours";
String chs=ob + h1 + cb;
hours.setText(chs);
}else{
hours.setText(chrs);
}
// image.setImageBitmap(loadBitmap(hlist.get(position).get("img")));
Glide.with(context).load(MyArr.get(position).get("img")).into(image);
cname.setText(cn);
tname.setText(trainerName);
country.setText(co);
city.setText(ci);
date.setText(dat);
time.setText(cdays);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o=new Intent(context,CourseScreen.class);
o.putExtra("id",id);
context.startActivity(o);
}
});
} catch(Exception e){
e.printStackTrace();
}
}
return convertView;
}
}
}
Same as Search ByCity:

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);
}
}
}

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!

Deleting and editing list items in 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.

Categories

Resources