Search Filter moves to tab fragments - android

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:

Related

Search filter on listview returns wrong position on item click

I have listview and after filtering items of listview when I click on item its always returning wrong position of listview item.
Following is Adapter Class:
public class AdmitPatientAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> TempArrList = new ArrayList<>();
private static LayoutInflater inflater = null;
public static final String TAG_MRDNO = "mrd_no";
public AdmitPatientAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
TempArrList.addAll(d);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return TempArrList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
TempArrList.clear();
if (charText.length() == 0) {
TempArrList.addAll(data);
} else {
HashMap<String, String> tMap;
for (int i = 0; i < data.size(); i++) {
tMap = data.get(i);
if (charText.length() != 0 && tMap.get("mrd_no").toLowerCase(Locale.getDefault()).contains(charText)) {//mrd_no
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("pname").toLowerCase(Locale.getDefault()).contains(charText)) {//pname
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("bed_no").toLowerCase(Locale.getDefault()).contains(charText)) {
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("nursingstation").toLowerCase(Locale.getDefault()).contains(charText)) {
TempArrList.add(tMap);
}
}
notifyDataSetChanged();
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View viw = convertView;
if (convertView == null)
viw = inflater.inflate(R.layout.ip_ptn_items, null);
TextView txt_Mr_dno = (TextView) viw.findViewById(R.id.txtMrdno);
TextView txt_pitnt_Name = (TextView) viw.findViewById(R.id.txtpitntName);
TextView txt_Bed_no = (TextView) viw.findViewById(R.id.txtBedno);
TextView txt_Dob = (TextView) viw.findViewById(R.id.txtDob);
TextView txt_drNme = (TextView) viw.findViewById(R.id.txtDr);
TextView txt_Sex = (TextView) viw.findViewById(R.id.txtSex);
TextView txt_Wrdnm = (TextView) viw.findViewById(R.id.txtWrdnm);
HashMap<String, String> item = new HashMap<String, String>();
item = TempArrList.get(position);
String mrd_no = item.get(TAG_MRDNO);
item.put(TAG_MRDNO, mrd_no);
mrd_no = item.get(TAG_MRDNO);
if (mrd_no.endsWith("*")) {
txt_Mr_dno.setTextColor(Color.RED);
txt_pitnt_Name.setTextColor(Color.RED);
txt_Dob.setTextColor(Color.RED);
txt_Sex.setTextColor(Color.RED);
txt_Wrdnm.setTextColor(Color.RED);
txt_Bed_no.setTextColor(Color.RED);
} else {
txt_Mr_dno.setTextColor(Color.BLACK);
txt_pitnt_Name.setTextColor(Color.BLACK);
txt_Dob.setTextColor(Color.BLACK);
txt_Sex.setTextColor(Color.BLACK);
txt_Wrdnm.setTextColor(Color.BLUE);
txt_Bed_no.setTextColor(Color.BLUE);
}
//Setting all values in listview
txt_Mr_dno.setText(item.get("mrd_no"));
txt_pitnt_Name.setText(item.get("pname"));
txt_Bed_no.setText(item.get("bed_no"));
txt_Dob.setText(item.get("dob"));
//txt_admit_Date.setText(item.get("admission_date"));
txt_Sex.setText(item.get("sex"));
txt_Wrdnm.setText(item.get("nursingstation"));
txt_drNme.setText(item.get("doctor"));
// item = data.get(position);
/// String userType = item.get(TAG_UTYPE);
// item.put(TAG_UTYPE, mrd_no);
// userType = item.get(TAG_UTYPE);
try {
if (item.get("userType").equals("doctor")) {
txt_drNme.setVisibility(View.INVISIBLE);
} else {
txt_drNme.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
return viw;
}
}
and another one is on click event class:
public class AdmitPatientFragment extends Fragment implements FragmentCycle {
ListView lstViw;
AdmitPatientAdapter adapter;
String DcId = "";
String userType = "";
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
// generic array list
ArrayList<HashMap<String, String>> dlst = new ArrayList<HashMap<String, String>>();
// json url
private static String url = "http://scanweb.dmhospital.org:81/amrita_login/AdmList.php?auth=Yes";
#Override
public void onResumeFragment() {
}
#Override
public void onPauseFragment() {
}
// json node names
private static final String TAG_ADMITLIST = "AdmissionList";
private static final String TAG_MRD = "mrd_no";
private static final String TAG_PNAME = "pname";
private static final String TAG_BNO = "bed_no";
private static final String TAG_DOB = "dob";
private static final String TAG_ADMIT_DATE = "admission_date";
private static final String TAG_DOCTOR = "doctor";
private static String TAG_SEX = "sex";
private static String TAG_PATN_ID = "patient_id";
private static String TAG_VISIT_ID = "visit_id";
private static final String TAG_WARD_NAME = "nursingstation";
public static final String TAG_UTYPE = "userType";
JSONArray AdmissionList = null;
public AdmitPatientFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setReturnTransition(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
LinearLayout rootView = (LinearLayout) inflater.inflate(
R.layout.ip_ptn_lstviw, container, false);
dlst = new ArrayList<HashMap<String, String>>();
Intent intent = getActivity().getIntent();
DcId = intent.getStringExtra("drid");
if (CheckNetwork.isInternetAvailable(getActivity())) //returns true if internet available
{
} else {
Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
// to read doctor id from shared preferences
sharedPreferences = getActivity().getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
DcId = sharedPreferences.getString("drid", DcId);
userType = sharedPreferences.getString("usertype", userType);
url = url + "&docID=" + DcId;
new paAsyncTask().execute();
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.three_dots_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
final MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
//*** setOnQueryTextFocusChangeListener ***
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String searchQuery) {
adapter.filter(searchQuery.toString().trim());
lstViw.invalidate();
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
private class paAsyncTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait admit patient list is loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
AdmissionList = json.getJSONArray(TAG_ADMITLIST);
dlst = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < AdmissionList.length(); i++) {
JSONObject c = AdmissionList.getJSONObject(i);
String admission_date = c.getString(TAG_ADMIT_DATE);
HashMap<String, String> map = new HashMap<String, String>();
String ageSex = "(" + c.getString(TAG_DOB) + " | " + c.getString(TAG_SEX) + ")";
String[] admDte = admission_date.split(":");
String[] admDte1 = admission_date.split(":");
String resultDte = admDte[0] + ":" + admDte1[1];
map.put(TAG_MRD, c.getString(TAG_MRD).toString());
map.put(TAG_PNAME, c.getString(TAG_PNAME));
map.put(TAG_BNO, c.getString(TAG_BNO));
map.put(TAG_DOB, ageSex);
map.put(TAG_ADMIT_DATE, resultDte);
map.put(TAG_UTYPE, userType);
map.put(TAG_DOCTOR, c.getString(TAG_DOCTOR).toString());
// map.put(TAG_SEX, str);
map.put(TAG_WARD_NAME, c.getString(TAG_WARD_NAME));
map.put(TAG_PATN_ID, c.getString(TAG_PATN_ID));
map.put(TAG_VISIT_ID, c.getString(TAG_VISIT_ID));
dlst.add(map);
}
lstViw = (ListView) getView().findViewById(R.id.lstAdmsion);
adapter = new AdmitPatientAdapter(getActivity(), dlst);
adapter.notifyDataSetChanged();
lstViw.setAdapter(adapter);
lstViw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
HashMap<String, String> map = dlst.get(position);
Intent imp = new Intent(getActivity(),
NavigationDrawerActivity.class);
imp.putExtra("drid", DcId);
// imp.putExtra(TAG_ADMIT_DATE, map.get(""));
imp.putExtra("docNme", map.get(TAG_DOCTOR));
imp.putExtra("ptnId", map.get(TAG_PATN_ID));
imp.putExtra("vst_id", map.get(TAG_VISIT_ID));
startActivity(imp);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try changing
HashMap<String, String> map = dlst.get(position);
to
HashMap<String, String> map = adapter.getItem(position);
Basically, the OnItemClickListener is grabbing objects from your ListView rather than your Adapter that has updated references...
EDIT 1: You also need to implement getItem in your Adapter so it returns an object from your filtered list. I'm assuming that's dlst...
So, you would need to put this in your adapter class:
public HashMap<String, String> getItem(int position){
return dlst.get(position);
}

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 refresh fragment from out of activity or fragment but from baseAdapter class

I have some problem. when I click a delete(btnPlus.setOnClickListener in the interestAdepter class) button from listview baseAdapter, I want to refresh the fragment which contains the listview.
1.InterestAdapter class{edtied}
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
public InterestAdapter() {
m_List = new ArrayList<InterestClass>();
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
2.InterestFragment{edited}
public class InterestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private ListView interest_ListView;
private InterestAdapter interest_Adapter;
String TAG="response";
RbPreference keep_Login;
public InterestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment InterestFragment.
*/
// TODO: Rename and change types and number of parameters
public static InterestFragment newInstance(String param1, String param2) {
InterestFragment fragment = new InterestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
keep_Login = new RbPreference(getContext());
Log.v("interFrag","oncreate");
// Inflate the layout for this fragment
/*if(keep_Login.get("name",null)!=null) {
return inflater.inflate(R.layout.fragment_interest, container, false);
}else{
return inflater.inflate(R.layout.need_login, container, false);
}*/
return inflater.inflate(R.layout.fragment_interest, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("ListFragment", "onActivityCreated().");
Log.v("ListsavedInstanceState", savedInstanceState == null ? "true" : "false");
if(keep_Login.get("no",null)!=null) {
String enc_Id="";
Crypto enc=new Crypto();
try{
enc_Id=enc.AES_Encode(keep_Login.get("no",null),enc.global_deckey);
}catch(Exception e){
}
interest_Adapter = new InterestAdapter();
interest_ListView = (ListView) getView().findViewById(R.id.i_ListView);
AsyncCallInterest task = new AsyncCallInterest();
task.execute(enc_Id);
}
}
private class AsyncCallInterest extends AsyncTask<String, Void, JSONArray> {
JSONArray interest_Array;
InterestFragment interest;
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected JSONArray doInBackground(String... params) {
String id=params[0];
dbConnection db_Cont=new dbConnection();
interest_Array=db_Cont.getFavorite(id);
Log.v("doinbackgroud", interest_Array.toString());
return interest_Array;
}
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interest_Adapter.add(i_Class);
}
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
Is there any way to refresh the fragment from the button in baseAdapter class? I searched a lot but I couldn't fine answer. Please help me, Thank you.
{edited}
I add AsyncCallAddDelFavorite class and AsyncCallInterest class. Thank you.
Update your adapter constructor. After deleting content, remove the item from the arraylist and notify dataset changed.
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
private Context mContext;
public InterestAdapter(Context context, ArrayList<InterestClass> list) {
m_List = list;
mContext = context;
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
**m_List.remove(position);
notifyDatasetChanged();**
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
Update Adapter initialization in fragment. You are adding item to adapter directly. Use arraylist and after downloading data create adapter instance.
private ArrayList<InterestClass> interestList = new ArrayList<>();
and update your onPostExecute Method
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interestList.add(i_Class);
}
interest_Adapter = new InterestAdapter(getActivity,interestList);
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
If I understand you correctly you want to remove the item from your ListView too after your removing it from your Database, to achieve that you can call this
m_List.remove(position);
interest_Adapter..notifyDataSetChanged();
First line removes the item and Second one will insure that the Adapter gets updated after the item has been removed.
Hope this helps

How to set listview row clickable only one time in android?

Explanation:
I have a listview in my fragment. When I click one of the row of the listview it goes to another activity.In listview,I got the data from the adapter.
Inside the adapter view,I set the setOnClick().
Problem is when I click one of the row multiple time it is opening multiple activity.I want to restrict only one time click on the particular row over the listview item.
Here is my fragment where I get the listview and set the adapter-
public class HomeFragment extends Fragment{
public HomeFragment() {
}
public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
private static String url = "";
List<String> lst_key = null;
List<JSONObject> arr_completed = null;
List<String> lst_key2 = null;
List<JSONObject> lst_obj = null;
List<String> list_status = null;
ListView completed_listview;
int PagerLength = 0,exeption_flag=0;
View rootView;
private ViewPager pagerRecentMatches;
private ImageView imgOneSliderRecent;
private ImageView imgTwoSliderRecent;
private ImageView imgThreeSliderRecent;
private ImageView imgFourSliderRecent;
private ImageView imgFiveSliderRecent;
private ImageView imgSixSliderRecent;
private ImageView imgSevenSliderRecent;
private ImageView imgEightSliderRecent;
LinearLayout selector_dynamic;
LinearLayout Recent_header_layout;
FrameLayout adbar;
String access_token = "";
SharedPreferences sharedPreferences;
int current_pos=0,status_flag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
findViews();
selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
new AddLoader(getContext()).LoadAds(adbar);
MainActivity activity = (MainActivity) getActivity();
access_token = activity.getMyData();
sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (access_token == null || access_token=="") {
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";
} else {
editor.putString("access_token", access_token);
editor.commit();
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
}
completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);
Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);
Recent_header_layout.setVisibility(View.GONE);
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
new TabJson().execute();
}
pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
return rootView;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void dialog_popup() {
final Dialog dialog = new Dialog(getContext());
DisplayMetrics metrics = getResources()
.getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.internet_alert_box);
dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
getActivity().finish();
}
});
dialog.show();
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
dialog.dismiss();
new TabJson().execute();
}
}
});
dialog.show();
}
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
exeption_flag=0;
status_flag = 0;
if (jsonStr != null) {
try {
if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
exeption_flag = 1;
} else {
JSONObject obj = new JSONObject(jsonStr);
if (obj.has("status") && !obj.isNull("status")) {
if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
status_flag = 1;
} else {
JSONObject data = obj.getJSONObject("data");
JSONArray card = data.getJSONArray("cards");
PagerLength = 0;
lst_obj = new ArrayList<>();
list_status = new ArrayList<>();
lst_key = new ArrayList<>();
lst_key2 = new ArrayList<>();
arr_completed = new ArrayList<>();
for (int i = 0; i < card.length(); i++) {
JSONObject card_obj = card.getJSONObject(i);
if (card_obj.getString("status").equals("started")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("notstarted")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("completed")) {
arr_completed.add(card_obj);
lst_key2.add(card_obj.getString("key"));
}
}
}
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Utils.Pdialog_dismiss();
if (status_flag == 1 || exeption_flag==1) {
dialog_popup();
} else {
Recent_header_layout.setVisibility(View.VISIBLE);
LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
adapterTabRecent.notifyDataSetChanged();
pagerRecentMatches.setAdapter(adapterTabRecent);
pagerRecentMatches.setCurrentItem(current_pos);
ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
CmAdapter.notifyDataSetChanged();
completed_listview.setAdapter(CmAdapter);
}
}
}
private void findViews() {
pagerRecentMatches = (ViewPager) rootView
.findViewById(R.id.pager_recent_matches);
imgOneSliderRecent = (ImageView) rootView
.findViewById(R.id.img_one_slider_recent);
imgTwoSliderRecent = (ImageView) rootView
.findViewById(R.id.img_two_slider_recent);
imgThreeSliderRecent = (ImageView) rootView
.findViewById(R.id.img_three_slider_recent);
imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
After load the data from the server it passed to the onPost() i called an adapter which extends BaseAdpter
Here is my BaseAdapter
package adapter;
public class ScheduleAdapter extends BaseAdapter{
private Context context;
private List<JSONObject> arr_schedule;
private List<String> arr_matchKey;
private static LayoutInflater inflater;
int flag = 0;
String time="";
String status="";
String match_title = "";
String match_key="";
public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
this.context=context;
this.arr_schedule=arr_schedule;
this.arr_matchKey=arr_matchKey;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.arr_schedule.size();
}
#Override
public Object getItem(int position) {
return this.arr_schedule.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder{
TextView txt_one_country_name;
TextView txt_two_country_name;
TextView txt_venue;
TextView txtTimeGMT;
TextView txtDate;
TextView txtTimeIST;
ImageView team_one_flag_icon;
ImageView team_two_flag_icon;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
String[] parts;
String[] state_parts;
String[] match_parts;
Typeface tf=null;
String winner_team = "";
String final_Score="";
String now_bat_team="",team_name="";
String related_status="";
if(convertView==null) {
convertView = inflater.inflate(R.layout.recent_home_layout, null);
holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
holder.txt_one_country_name.setTypeface(tf);
holder.txt_two_country_name.setTypeface(tf);
holder.txt_venue.setTypeface(tf);
holder.txtTimeIST.setTypeface(tf);
holder.txtTimeGMT.setTypeface(tf);
holder.txtDate.setTypeface(tf);
convertView.setTag(holder);
}
else{
holder=(Holder)convertView.getTag();
}
try {
String overs="";
String wickets_now="";
String now_runs="";
String[] over_parts;
time = "";
JSONObject mainObj = this.arr_schedule.get(position);
status = mainObj.getString("status");
String name = mainObj.getString("short_name");
String state = mainObj.getString("venue");
String title = mainObj.getString("title");
related_status=mainObj.getString("related_name");
JSONObject start_date = mainObj.getJSONObject("start_date");
JSONObject teams=null;
JSONObject team_a=null;
JSONObject team_b=null;
String team_a_key="";
String team_b_key="";
time = start_date.getString("iso");
parts = name.split("vs");
match_parts = title.split("-");
state_parts = state.split(",");
int length = state_parts.length;
flag=0;
match_title="";
winner_team="";
if (!mainObj.isNull("msgs")) {
JSONObject msgs = mainObj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
flag = 1;
}
}
match_title=name+" - "+match_parts[1];
JSONObject now=null;
if(mainObj.has("now") && !mainObj.isNull("now")) {
now = mainObj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if(now.getString("runs_str").equals("null")){
overs="0";
}
else{
over_parts=now.getString("runs_str").split(" ");
overs=over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
try {
if (!mainObj.isNull("teams") && mainObj.has("teams")) {
teams = mainObj.getJSONObject("teams");
team_a = teams.getJSONObject("a");
team_b = teams.getJSONObject("b");
team_a_key = team_a.getString("key");
team_b_key = team_b.getString("key");
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
}
}
catch (NullPointerException e){
e.printStackTrace();
}
if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
final_Score="";
}
else{
final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
}
}
holder.txt_one_country_name.setText(parts[0]);
holder.txt_two_country_name.setText(parts[1]);
if(length==1){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
holder.txtTimeGMT.setText(state_parts[0]);
}
if(length==2){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);
}
if(length==3){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
}
if(length==4){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
}
holder.txtDate.setText(final_Score);
holder.txtDate.setTypeface(tf, Typeface.BOLD);
holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
holder.txtTimeIST.setText(winner_team);
holder.txt_venue.setText(related_status);
} catch (JSONException e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
}
});
return convertView;
}
#Override
public boolean isEnabled(int position) {
return super.isEnabled(position);
}
}
This adapter set the listrow item into listview.
In ScheduleAdapter.java i set the onclick() on the convertView in which i called a GetValue class which is only implement a Asynctask to get the data and called and intent then it goes to an activity.
Means HomeFragment->ScheduleAdapter->GetValue->Scorecard
Here,
HomeFragment is fragment which have listview
ScheduleAdpter is an adapter which set data to listview which reside in homefragment
GetValue is class which implement some important task and it passed an intent and goes to an activity(It's work as a background)
ScoreCard is my activity which called after click on the row of the listview which reside in HomeFragment.
Please, help me to solve out this problem.
You can use a flag in Listview click - isListClicked, and set flag value as false in onPostexecute method of Aysnc task class -GetValue
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isListClicked){
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
isListClicked = true;
}
}
});
If you want to prevent multiple activities being opened when the user spams with touches, add into your onClick event the removal of that onClickListener so that the listener won't exist after the first press.
Easy way is you can create a model class of your json object with those field you taken in holder class. And add one more boolean field isClickable with by default with true value.Now when user press a row for the first time you can set your model class field isClickable to false. Now second time when user press a row,you will get a position of row and you can check for isClickable. it will return false this time.
Model Class :
public class CountryInfoModel {
//other fields to parse json object
private boolean isClickable; //<- add one more extra field
public boolean isClickable() {
return isClickable;
}
public void setIsClickable(boolean isClickable) {
this.isClickable = isClickable;
}
}
listview click perform :
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//country_list is your list of model class List<CountryInfo>
if(country_list.get(position).isClickable())
{
//Perform your logic
country_list.get(position).setIsClickable(false);
}else{
//Do nothing : 2nd time click
}
}
});
Try creating your custom click listener for your listview and use it. In this way
public abstract class OnListItemClickListener implements OnItemClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public abstract void onListItemSingleClick(View parent, View view, int position, long id);
public OnListItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
onListItemSingleClick(parent, view, position, id);
}
}

Adapter not displaying correct data

I am developing an application in which i am getting a large json data from the server. i want to display it in the list view. But i am getting the same value repeated. The no of items shown by the list view is proper. only same data repeated in all the list items.
Here is my code.
public class HistoryActivity extends AppCompatActivity {
private Toolbar toolbar;
String strServerResponse = null;
ProgressDialog nDialog;
ArrayList<String>clicklat;
ArrayList<String>clicklong;
ArrayList<String>dttime;
ArrayList<Pojo> history;
HistoryAdapter myAdapter;
ListView list;
public String date, inTime, outTime, inLat, inLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("History");
clicklat=new ArrayList<String>();
clicklong=new ArrayList<String>();
dttime=new ArrayList<String>();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
list = (ListView) findViewById(R.id.historyList);
history = new ArrayList<Pojo>();
new NetCheck().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArrayList<String>clicklat= new ArrayList<String>(history.get(position).getLati());
ArrayList<String>clicklong= new ArrayList<String>(history.get(position).getLongi());
ArrayList<String>dttime= new ArrayList<String>(history.get(position).getDatetime());
Intent i = new Intent(HistoryActivity.this, DetailsActivity.class);
i.putStringArrayListExtra("clicklat", clicklat);
i.putStringArrayListExtra("clicklong", clicklong);
i.putStringArrayListExtra("clickdatetime", dttime);
startActivity(i);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class NetCheck extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
nDialog.dismiss();
// TODO Auto-generated method stub
myAdapter = new HistoryAdapter(HistoryActivity.this, history);
list.setAdapter(myAdapter);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://myurl");
httpRequest.setHeader("Content-Type", "application/json");
SharedPreferences mmm = getSharedPreferences(
"MyPref", MODE_PRIVATE);
String logempid = mmm.getString("id", null);
JSONObject json = new JSONObject();
json.put("empid", logempid);
Log.e("JSON Object", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpRequest.setEntity(se);
HttpResponse httpRes = httpClient.execute(httpRequest);
java.io.InputStream inputStream = httpRes.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
strServerResponse = sb.toString();
Log.e("Server Response", "" + strServerResponse.toString());
if (strServerResponse != null) {
try {
JSONArray arr = new JSONArray(strServerResponse);
for (int k = 0; k < arr.length(); k++) {
JSONObject jsonObj1 = arr.getJSONObject(k);
Pojo pojo = new Pojo();
JSONArray subArrayLat = jsonObj1.getJSONArray("lati_long");
List<String> lati= new ArrayList<String>();
List<String> longi= new ArrayList<String>();
List<String> dateandtime= new ArrayList<String>();
for (int i = 0; i < subArrayLat.length(); i++) {
String lat = subArrayLat.getJSONObject(i).getString("Latitude").toString();
String loong = subArrayLat.getJSONObject(i).getString("Longitude").toString();
String datetimee = subArrayLat.getJSONObject(i).getString("date_time").toString();
lati.add(lat);
longi.add(loong);
dateandtime.add(datetimee);
}
pojo.setLati(lati);//adding latitude list
pojo.setLongi(longi); //adding longitude list
pojo.setDatetime(dateandtime);
String dateee = arr.getJSONObject(k).getString("login_date");
String timeeee = arr.getJSONObject(k).getString("login_time");
String timeeee2 = arr.getJSONObject(k).getString("logout_time");
pojo.setDate(dateee);
pojo.setLoginTime(timeeee);
pojo.setLogoutTime(timeeee2);
history.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
And this is Adapter
public class HistoryAdapter extends BaseAdapter {
private Context activity;
TextView tv_date;
TextView tv_loginTime;
TextView tv_logoutTime;
ArrayList<Pojo> list;
private ArrayList<Pojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public HistoryAdapter(Context a, ArrayList<Pojo> history) {
// TODO Auto-generated constructor stub
activity = a;
list = history;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<Pojo>();
this.arraylist.addAll(list);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(convertView == null) {
v = inflater.inflate(R.layout.history_item, parent, false);
}
final Pojo pojo = list.get(position);
tv_date = (TextView) v.findViewById(R.id.historyDate);
tv_loginTime = (TextView) v.findViewById(R.id.historyLoginTime);
tv_logoutTime = (TextView) v.findViewById(R.id.historyLogoutTime);
tv_date.setText(pojo.getDate());
tv_loginTime.setText(pojo.getLoginTime());
tv_logoutTime.setText(pojo.getLogoutTime());
return v;
}
}
and setters and getters
public class Pojo {
public static String empid11;
public static String loginTime;
public static String date;
public static String logoutTime;
public static List<String> lat;
public static List<String> datetime;
public static List<String> longi;
public static List<String> inlogin;
public static List<String> inDate;
public List<String> getInTime(){
return this.inlogin;
}
public List<String> getInDate(){
return this.inDate;
}
public void setInDate(List<String> inDate){
this.inDate = inDate;
}
public List<String> getLati(){
return this.lat;
}
public List<String> getLongi(){
return this.longi;
}
public void setLati(List<String> lat){
this.lat = lat;
}
public void setLongi(List<String> longi){
this.longi = longi;
}
public void setId(String empid) {
this.empid11 = empid;
}
public String getId() {
return empid11;
}
public void setLoginTime(String loginTime) {
this.loginTime = loginTime;
}
public String getLoginTime() {
return loginTime;
}
public void setLogoutTime(String logoutTime) {
this.logoutTime = logoutTime;
}
public String getLogoutTime() {
return logoutTime;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public List<String> getDatetime(){
return this.datetime;
}
public void setDatetime(List<String> datetime){
this.datetime = datetime;
}
}
Hello see the modifiy version of your adapter. Let me know if you have any problem with it.
public class HistoryAdapter extends BaseAdapter
{
private Context activity;
TextView tv_date;
TextView tv_loginTime;
TextView tv_logoutTime;
private ArrayList<Pojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public HistoryAdapter(Context a) {
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<Pojo>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addHistoryData(ArrayList<Pojo> newDataset){
if(arraylist != null){
arraylist.addAll(newDataset);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder = null;
if(convertView == null)
{
mViewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.history_item, parent, false);
mViewHolder.tv_date = (TextView) convertView.findViewById(R.id.historyDate);
mViewHolder.tv_loginTime = (TextView)convertView.findViewById(R.id.historyLoginTime);
mViewHolder.tv_logoutTime = (TextView)convertView.findViewById(R.id.historyLogoutTime);
convertView.setTag(mViewHolder);
}else{
mViewHolder = (ViewHolder) convertView.getTag();
}
final Pojo pojo = list.get(position);
mViewHolder.tv_date.setText(pojo.getDate());
mViewHolder.tv_loginTime.setText(pojo.getLoginTime());
mViewHolder.tv_logoutTime.setText(pojo.getLogoutTime());
return v;
}
public class ViewHolder{
TextView tv_date
TextView tv_loginTime;
TextView tv_logoutTime;
}
}
In next the activity NetCheck class when web service response come change like below :
history.add(pojo);
myAdapter.addHistoryData(history);
myAdapter.notifiyDatasetChanged();
There may be problem you are getting repeated value in array, please check your array first.

Categories

Resources