I am using a ViewPager in my application and I have three tabs in it; I am using ViewPager inside a fragment. Now my problem here is, I am getting data correctly while loading the application, but when I go next page and then back to ViewPager, the data is lost and tabs are not working. Please assist me. Below is my code:
import com.devpoint.rprtjobs.R;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.design.widget.TabLayout;
public class MainActivity extends Fragment {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
SwipeViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"OnGoing","UpComing","Expired"};
int Numboftabs =3;
private View rootView;
#SuppressWarnings("deprecation")
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
rootView = inflater.inflate(R.layout.activity_main,
container, false);
adapter = new SwipeViewPagerAdapter(getActivity().getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
pager.setOffscreenPageLimit(3);
pager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
if(position ==0)
{
SwipeViewPagerAdapter.Pagename = "ListOnGoing";
}
else if(position ==1)
{
SwipeViewPagerAdapter.Pagename = "ListUpComing";
}
else if(position ==2)
{
SwipeViewPagerAdapter.Pagename = "ListExpired";
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return rootView;
}
}
Here is my adapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Edwin on 15/02/2015.
*/
public class SwipeViewPagerAdapter extends FragmentPagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
public static String Pagename="ListOnGoing";
// Build a Constructor and assign the passed Values to appropriate values in the class
public SwipeViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
//Pagename = "ListOnGoing";
ListOnGoing mListOnGoing = new ListOnGoing();
return mListOnGoing;
case 1:
//Pagename = "ListUpComing";
ListUpComing mListUpComing = new ListUpComing();
return mListUpComing;
case 2:
//Pagename = "ListExpired";
ListExpaire mListExpaire = new ListExpaire();
return mListExpaire;
default:
return null;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
And here is one of my fragments:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
#SuppressLint("ShowToast")
public class ListOnGoing extends Fragment implements OnItemClickListener {
Boolean isInternetPresent = false;
ConnectionDetector connectdetector;
public static ListView swipelisview;
Activity activity;
public static ProductListAdapter productListAdapter;
SharedPreference sharedPreference;
String LoggedIn;
boolean fragmentAlreadyLoaded = false;
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.listener = (FragmentActivity) activity;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
try {
super.onViewCreated(view, savedInstanceState);
swipelisview = (ListView) rootView.findViewById(R.id.list);
View emptyView = rootView.findViewById(R.id.emptyView);
swipelisview.setEmptyView(emptyView);
if (savedInstanceState == null && !fragmentAlreadyLoaded) {
fragmentAlreadyLoaded = true;
repoObject = SplashScreen.getRepo();
session = new SessionManager(getActivity());
HashMap<String, String> Radious = session.getRadiousName();
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
//LoadActivity.Status="";
GPlaces = new GetAllGooglePlaces();
GPlaces.GetOpportunityList("", Radiosname, getActivity());
DisPlayOppList();
}
productListAdapter = new ProductListAdapter(getActivity(),
GetAllGooglePlaces.ArrayListOngoing);
swipelisview.setAdapter(productListAdapter);
productListAdapter.notifyDataSetChanged();
session = new SessionManager(getActivity());
HashMap<String, String> Radious = session.getRadiousName();
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
searchedit = (EditText) rootView.findViewById(R.id.searchbox);
Button searchbtn = (Button) rootView.findViewById(R.id.searchbtn);
searchedit = (EditText) rootView.findViewById(R.id.searchbox);
clearbtn = (Button) rootView.findViewById(R.id.clearbtn);
searchedit.addTextChangedListener(watch);
clearbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
LoadActivity.Status="";
searchedit.setText("");
GPlaces.GetOpportunityList("", Radiosname, getActivity());
DisPlayOppList();
}
});
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
multipleCat = "";
GetAllGooglePlaces.ArrayListOngoing = new CopyOnWriteArrayList<>();
SearchText = searchedit.getText()
.toString();
LoadActivity.Status = "Search";
if (LoadActivity.isOnline) {
GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity());
DisPlayOppList();
}
else {
List<OpportunityTable> alloffers = repoObject.roffertable
.getAlloffersbySearchKeyword(SearchText);
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
}
}
});
}
});
HashMap<String, String> user = session.getLogin();
LoggedIn = user.get(SessionManager.KEY_Login);
if (LoggedIn == null) {
LoggedIn = "";
}
connectdetector = new ConnectionDetector(getActivity());
try {
// Check if Internet present
isInternetPresent = connectdetector.isConnectingToInternet();
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
footerlayout = (LinearLayout) rootView.findViewById(R.id.footerlayout);
footerlayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
swipelisview.requestDisallowInterceptTouchEvent(true);
return true;
}
});
swipelisview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
final int position, long id) {
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0);
try {
final DetailsViewpagerFragment mDetailsViewpagerFragment = new DetailsViewpagerFragment();
String url;
if (LoadActivity.isOnline) {
progresdialog = new ProgressDialog(getActivity());
progresdialog.setMessage(Html
.fromHtml("<b>Search</b><br/>Loading Details..."));
progresdialog.setIndeterminate(false);
progresdialog.setCancelable(false);
progresdialog.show();
ListDetails product = GetAllGooglePlaces.ArrayListOngoing
.get(position);
OpportunityID = product.getOfferID();
url = LoadActivity.BaseUri + "SaveUserViewedOpportunities";
JsonObjectRequest jsObjRequest;
jsObjRequest = new JsonObjectRequest(
Request.Method.POST, url,
getSaveViewUserParams(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pagename = "Userplaceslist";
mDetailsViewpagerFragment
.setClickList(position);
FragmentManager fragment = getFragmentManager();
fragment.beginTransaction()
.replace(R.id.frame_container,
mDetailsViewpagerFragment)
.commit();
LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity;
ModuleFragmentBackStackingClass
.AddtoStack(
mDetailsViewpagerFragment,
EnumModuleTags.SinglePlaceActivity,
getString(R.string.mainfrgment_rprt));
LoadActivity.updateActionbarMenu();
progresdialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
Toast.makeText(getActivity(), "False",
Toast.LENGTH_LONG).show();
progresdialog.dismiss();
}
});
AppController.getInstance().addToRequestQueue(
jsObjRequest);
} else {
mDetailsViewpagerFragment.setClickList(position);
FragmentManager fragment = getFragmentManager();
fragment.beginTransaction()
.replace(R.id.frame_container,
mDetailsViewpagerFragment).commit();
LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity;
ModuleFragmentBackStackingClass.AddtoStack(
mDetailsViewpagerFragment,
EnumModuleTags.SinglePlaceActivity,
getString(R.string.mainfrgment_rprt));
}
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
private JSONObject getSaveViewUserParams() {
JSONObject params = new JSONObject();
HashMap<String, String> UserId = session.getUserID();
String UserIdVal = UserId.get(SessionManager.KEY_UserID);
if (!(UserIdVal == null)) {
UserIdVal = UserId.get(SessionManager.KEY_UserID);
} else {
UserIdVal = "0";
}
try {
params.put("UserId", UserIdVal);
params.put("OpportunityID", OpportunityID);
params.put("UserViewedID", 0);
params.put("Shortlisted", true);
params.put("KeyValue", null);
} catch (JSONException e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
return params;
}
});
// Click The FavoritesItem on LongPress
swipelisview.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
InputMethodManager imm;
imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0);
try {
ImageView button;
button = (ImageView) view
.findViewById(R.id.fav_checkbox);
String tag = button.getTag().toString();
if (tag.equals(getString(R.string.grey_favcolor))) {
sharedPreference.addFavorite(activity,
GetAllGooglePlaces.ArrayListOngoing.get(position));
button.setTag(getString(R.string.red_favcolor));
button.setImageResource(R.drawable.checked);
} else if (tag.equals(getString(R.string.red_favcolor))){
sharedPreference.removeFavorite(activity,
GetAllGooglePlaces.ArrayListOngoing.get(position));
button.setTag(getString(R.string.grey_favcolor));
button.setImageResource(R.drawable.unchecked);
}
return true;
} catch (NotFoundException e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
Toast.makeText(getActivity(), e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return true;
}
});
// Code placed here will be executed even when the fragment comes from
// backstack
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
// String APIkey ="AIzaSyCAekTB0o1MuSYvUb-8HTZxhlJHE8yBUfI";
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
//setRetainInstance(true);
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
#SuppressWarnings("static-access")
#SuppressLint({ "CutPasteId", "ClickableViewAccessibility" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
//setRetainInstance(true);
try
{
Tracker t = ((Analytics) getActivity().getApplication()).getTracker(
TrackerName.APP_TRACKER);
t.setScreenName("UserPlaces Listview");
t.send(new HitBuilders.AppViewBuilder().build());
}
catch(Exception e)
{
Toast.makeText(getActivity().getApplication(), "Error"+e.getMessage(), 1).show();
}
rootView = inflater.inflate(R.layout.user_places_listview, container,
false);
swipelisview = (ListView) rootView.findViewById(R.id.list);
View emptyView = rootView.findViewById(R.id.emptyView);
swipelisview.setEmptyView(emptyView);
return rootView;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootView;
}
TextWatcher watch = new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void onTextChanged(CharSequence s, int a, int b, int c) {
if(c == 0){
clearbtn.setVisibility(View.GONE);
}
else {
clearbtn.setVisibility(View.VISIBLE);
}
}};
protected void LoadSearchPlaces(String searchparam) {
try {
if (LoadActivity.isOnline) {
JsonArrayRequest movieReq = new JsonArrayRequest("http://192.168.2.10/RPRT.WebApi/api/RPRT/" + "SearchPlaces/"+searchparam,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
List<HashMap<String, String>> aList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject json_data;
try {
json_data = response.getJSONObject(i);
HashMap<String, String> hm = new HashMap<>();
hm.put("Address", json_data.getString("Address"));
hm.put("City", json_data.getString("City"));
hm.put("Latitude", json_data.getString("Latitude"));
hm.put("Longitude", json_data.getString("Longitude"));
aList.add(hm);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String[] from = { "Address"} ;
int[] to = { R.id.tv };
SimpleAdapter adapterId = new SimpleAdapter(getActivity(), aList,
R.layout.user_places_dropdown_listitem, from, to);
//final AutoCompleteTextView autoCompView = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(adapterId);
autoCompView.setThreshold(1);
// Pname.setThreshold(1);
autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> hm = (HashMap<String, String>) parent
.getAdapter().getItem(position);
autoCompView.setText(hm.get("Address"));
SplashScreen.nwLocation.setLatitude(Double.parseDouble(hm.get("Latitude")));
SplashScreen.nwLocation.setLongitude(Double.parseDouble(hm.get("Longitude")));
HashMap<String, String> Radious = session.getRadiousName();
final String Radiosname;
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
multipleCat="";
ProgressDialog progresdialog = new ProgressDialog(getActivity());
progresdialog.setMessage(Html
.fromHtml("<b>Search</b><br/>Loading Details..."));
progresdialog.setIndeterminate(false);
progresdialog.setCancelable(false);
//progresdialog.show();
LoadActivity.Status="";
GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity());
DisPlayOppList();
searchdialog.cancel();
}
});
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void DisPlayOppList() {
try {
pdialog = new ProgressDialog(getActivity());
pdialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Details..."));
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
if(LoadActivity.Status.equals("Slidemenulist"))
{
int CategoryId = 0;
switch (CopyOfListOnGoing.multipleCat) {
case "Books":
CategoryId = 1;
break;
case "BeautyandFashion":
CategoryId = 2;
break;
case "Electronic":
CategoryId = 3;
break;
case "Food":
CategoryId = 4;
break;
case "HomeService":
CategoryId = 5;
break;
case "Jobs":
CategoryId = 6;
break;
case "RealEstate":
CategoryId = 7;
break;
case "Vehicles":
CategoryId = 8;
break;
}
List<OpportunityTable> alloffers = repoObject.roffertable
.getAllCatOpp(CategoryId , Radiosname);
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
} else {
List<OpportunityTable> alloffers = repoObject.roffertable
.getAlloffers(Integer.parseInt(Radiosname));
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
}
}
catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
multipleCat = "";
DisPlayOppList();
}
/* #Override
public void onResume() {
Log.e("DEBUG", "onResume of Userplace ListView");
super.onResume();
}*/
#Override
public void onPause() {
Log.e("DEBUG", "OnPause of Userplace ListView");
super.onPause();
}
}
And the remaining fragments look the same. Please help me.
After a little research, I found the solution to my problem.
I was originally calling getactivity().getSupportFragmentmanager(). However, the correct code is getChildFragmentManager()
In you adapter extend FragmentStatePagerAdapter instead of FragmentPagerAdapter it will solve your problem. Let me know if you have any problem.
Reason (quoting from javadoc)
/**
The [android.support.v4.view.PagerAdapter] that will provide
fragments for each of the sections. We use a
{#link FragmentPagerAdapter} derivative, which will keep every
loaded fragment in memory. If this becomes too memory intensive, it
may be best to switch to a
[android.support.v4.app.FragmentStatePagerAdapter].
*/
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setOffscreenPageLimit(2);// no of fragments
public float getPageWidth(int position)
{
if (position == 0 || position == 2)
{
return 0.8f;
}
return 1f;
}
I think your problem has already being solved let this be a help to others.I had this same issue and I solved it by extending the adapter class with FragmentStatePagerAdapter instead of FragmentPagerAdapter. This worked for me perfectly hope it works for you guys as well...
Related
I need to send a value when i click on a row in recyclerview to another fragment (I thin on OnBind in the adapter). Then i need to close the fragment that contain the recyclerview and open the receiver fragment. I read somewhere that we can use bundle, but I am pretty new to android programming so I am confused.
This is the Fragment that contain RecyclerView
public class PasienFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
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 OnPasienFragmentInteractionListener mPasienListener;
public PasienFragment() {
// Required empty public constructor
}
int countICU=0;
int countINAP=0;
int countUMUM=0;
int countBPJS=0;
RequestQueue queue;
String jenisAsuransi,jenisKamar;
String id="C0E0607E";
ImageView ivTotal,ivIcu,ivInap,ivBpjs,ivUmum;
TextView tvTOTAL,tvICU,tvINAP,tvBPJS,tvUMUM;
public static final String URL_JUMLAH = "http:";
public static PasienFragment newInstance(String param1, String param2) {
PasienFragment fragment = new PasienFragment();
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);
}
queue = Volley.newRequestQueue(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_pasien, container, false);
ivTotal = (ImageView) view.findViewById(R.id.ivTotal);
ivIcu = (ImageView) view.findViewById(R.id.ivICU);
ivBpjs = (ImageView) view.findViewById(R.id.ivBPJS);
ivInap = (ImageView) view.findViewById(R.id.ivINAP);
ivUmum = (ImageView) view.findViewById(R.id.ivUMUM);
tvTOTAL = (TextView) view.findViewById(R.id.tvTotal);
tvICU = (TextView) view.findViewById(R.id.tvICU);
tvBPJS = (TextView) view.findViewById(R.id.tvBPJS);
tvINAP = (TextView) view.findViewById(R.id.tvINAP);
tvUMUM = (TextView) view.findViewById(R.id.tvUMUM);
ivTotal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien");
}
});
ivIcu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien ICU");
}
});
ivBpjs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien BPJS");
}
});
ivInap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien INAP");
}
});
ivUmum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPasienListener.onPasienFragmentInteraction("Daftar Pasien UMUM");
}
});
String url1 = URL_JUMLAH+id;
JsonObjectRequest req = new JsonObjectRequest(url1, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = null;
try {
users = response.getJSONArray("result1");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < users.length(); i++) {
try {
JSONObject obj = users.getJSONObject(i);
jenisAsuransi = (String) obj.get("Jenis_Asuransi");
jenisKamar = (String) obj.get("Jenis_Kamar");
if(jenisAsuransi.equals("BPJS")){
countBPJS++;
}
if(jenisAsuransi.equals("UMUM")){
countUMUM++;
}
if(jenisKamar.equals("INAP")){
countINAP++;
}
if(jenisKamar.equals("ICU")){
countICU++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
tvTOTAL.setText(String.valueOf(users.length()));
tvBPJS.setText(String.valueOf(countBPJS));
tvUMUM.setText(String.valueOf(countUMUM));
tvINAP.setText(String.valueOf(countINAP));
tvICU.setText(String.valueOf(countICU));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
}
});
queue.add(req);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String sentence) {
if (mPasienListener != null) {
mPasienListener.onPasienFragmentInteraction(sentence);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPasienFragmentInteractionListener) {
mPasienListener = (OnPasienFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mPasienListener = null;
}
public interface OnPasienFragmentInteractionListener {
// TODO: Update argument type and name
void onPasienFragmentInteraction(String sentence);
}
}
This is the RecyclerView adapter
public class ListPasienAdapter extends RecyclerView.Adapter<ListPasienAdapter.PasienViewHolder> {
private List<Pasien> pasienList;
public int count = 0;
public ListPasienAdapter(List<Pasien> pasienList) {
this.pasienList = pasienList;
}
#Override
public void onBindViewHolder(final PasienViewHolder pasienViewHolder, int i) {
final Pasien pi = pasienList.get(i);
pasienViewHolder.tvTanggal.setText(pi.Tgl_Masuk);
pasienViewHolder.tvNama.setText(pi.Nama_Pasien + "/" + pi.Gender);
pasienViewHolder.tvKamar.setText(pi.No_Kamar);
if (pi.Perawatan.toString().equals("Merah")) {
pasienViewHolder.ivRambu.setImageResource(R.drawable.merah);
} else if (pi.Perawatan.toString().equals("Kuning")) {
pasienViewHolder.ivRambu.setImageResource(R.drawable.kuning);
} else if (pi.Perawatan.toString().equals("Hijau")) {
pasienViewHolder.ivRambu.setImageResource(R.drawable.hijau);
}
pasienViewHolder.ivRambu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public ListPasienAdapter.PasienViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_pasien, viewGroup, false);
return new ListPasienAdapter.PasienViewHolder(itemView);
}
#Override
public int getItemCount() {
return pasienList.size();
}
public static class PasienViewHolder extends RecyclerView.ViewHolder {
protected TextView tvTanggal;
protected TextView tvNama;
protected TextView tvKamar;
protected TextView tvGender;
protected ImageView ivRambu;
protected ImageView ivDown;
protected ImageView btnIngat;
protected ImageView btnTerkirim;
protected TextView tvPeringatan;
protected LinearLayout btnDetail;
public PasienViewHolder(View v) {
super(v);
tvTanggal = (TextView) v.findViewById(R.id.tvTanggal);
tvNama = (TextView) v.findViewById(R.id.tvNama);
tvKamar = (TextView) v.findViewById(R.id.tvKamar);
ivRambu = (ImageView) v.findViewById(R.id.ivRambu);
ivDown = (ImageView) v.findViewById(R.id.ivDown);
//btnIngat = (ImageView) v.findViewById(R.id.btnIngat);
//btnTerkirim = (ImageView) v.findViewById(R.id.btnTerkirim);
btnDetail = (LinearLayout) v.findViewById(R.id.btnDetail);
//tvPeringatan = (TextView) v.findViewById(R.id.tvPeringatan);
}
}
}
This is the receiver Fragment
public class ListAktivitas 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;
public ListAktivitas() {
// Required empty publtic constructor
}
public static final String URL_LIST_Aktivitas = "http";
public static final String URL_Pasien = "http://";
String id="3";
RequestQueue queue;
List<Aktivitas> resultAktivitas = new ArrayList<>();
List<Pasien> resultPasien = new ArrayList<>();
Aktivitas a = new Aktivitas();
ListAktivitasAdapter laa;
RecyclerView cardListAktivitas;
Integer Urut;
String Nama_Prosedur;
String Id_Prosedur;
String Id_Aktivitas;
String Status;
String Nama_Pasien, No_Kamar, Gender;
Context context;
TextView tvNamaPasien,tvKamar;
public static ListAktivitas newInstance(String param1, String param2) {
ListAktivitas fragment = new ListAktivitas();
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);
}
queue = Volley.newRequestQueue(getActivity());
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list_aktivitas, container, false);
cardListAktivitas = (RecyclerView) view.findViewById(R.id.cardListAktivitas);
cardListAktivitas.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
cardListAktivitas.setLayoutManager(llm);
tvNamaPasien = (TextView) view.findViewById(R.id.tvNamaPasien);
tvKamar = (TextView) view.findViewById(R.id.tvKamar);
String url2 = URL_Pasien+id;
JsonObjectRequest req2 = new JsonObjectRequest(url2, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = null;
try {
users = response.getJSONArray("result1");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject obj = users.getJSONObject(0);
Nama_Pasien = (String) obj.get("Nama_Pasien");
No_Kamar = (String) obj.get("No_Kamar");
if(obj.get("Gender").toString().equals("Laki-laki")){
Gender = "L";
}else if (obj.get("Gender").toString().equals("Perempuan")){
Gender = "P";
}
resultPasien.add(new Pasien(Nama_Pasien, No_Kamar,Gender));
} catch (JSONException e) {
e.printStackTrace();
}
tvNamaPasien.setText(Nama_Pasien+"/"+Gender);
tvKamar.setText("kamar:"+No_Kamar);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
}
});
queue.add(req2);
String url1 = URL_LIST_Aktivitas+id;
Toast.makeText(getActivity(), url1, Toast.LENGTH_SHORT).show();
JsonObjectRequest req = new JsonObjectRequest(url1, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = null;
try {
users = response.getJSONArray("result1");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "yes", Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), String.valueOf(users.length()), Toast.LENGTH_SHORT).show();
for (int i = 0; i < users.length(); i++) {
try {
JSONObject obj = users.getJSONObject(i);
Urut = (Integer) obj.get("Urut");
Nama_Prosedur= (String) obj.get("Nama_Prosedur");
Id_Prosedur = (String) obj.get("Id_Prosedur");
Id_Aktivitas = String.valueOf(obj.getInt(Id_Aktivitas));
Status = (String) obj.get("Status");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(context,Nama_Prosedur, Toast.LENGTH_SHORT).show();
resultAktivitas.add(new Aktivitas(Urut, Nama_Prosedur, Id_Prosedur, Id_Aktivitas, Status));
laa = new ListAktivitasAdapter(resultAktivitas);
cardListAktivitas.setAdapter(laa);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
}
});
queue.add(req);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
/*
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
This is the activity that contain the 2 fragment
public class PasienActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,PasienFragment.OnPasienFragmentInteractionListener {
PasienFragment pasienFragment;
ListPasienFragment listPasienFragment;
ListAktivitas listAktivitasFragment;
RequestQueue queue;
String Nama_Dokter,Nama_RS;
public static final String URL_LIST = "http:";
String id="vvvv";
View navHeaderView;
TextView tvNavDokter, tvNavRS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pasien);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
queue = Volley.newRequestQueue(this);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
listPasienFragment = new ListPasienFragment();
listPasienFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.listPasienContainer, listPasienFragment).commit();
pasienFragment = new PasienFragment();
pasienFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.pasienFragmentContainer,pasienFragment).commit();
listAktivitasFragment = new ListAktivitas();
listAktivitasFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.listAktivitasContainer, listAktivitasFragment).commit();
View navHeaderView = navigationView.getHeaderView(0);
tvNavDokter = (TextView) navHeaderView.findViewById(R.id.tvNavDokter);
tvNavRS = (TextView) navHeaderView.findViewById(R.id.tvNavRS);
String url1 = URL_LIST+id;
JsonObjectRequest req = new JsonObjectRequest(url1, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray users = null;
try {
users = response.getJSONArray("result1");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject obj = users.getJSONObject(0);
Nama_Dokter = (String) obj.get("Nama_Dokter");
Nama_RS = (String) obj.get("Rumah_Sakit");
tvNavDokter.setText(Nama_Dokter);
tvNavRS.setText(Nama_RS);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(Home.this,"Terjadi Kendala Koneksi",Toast.LENGTH_LONG ).show();
}
});
queue.add(req);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pasien, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
/*
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onPasienFragmentInteraction(String sentence) {
if(listPasienFragment!=null)
listPasienFragment.updateSentence(sentence);
}
}
You can send data using bundle to fragment.
EG. `Bundle data = new Bundle();
data.putString("key", "value");
NewFragment newFragment = new NewFragment ();
newFragment.setArguments(eventDetailsData);`
Then load fragment.
To kill/remove current fragment execute below code
getActivity().onBackPressed();
My adapter item is removed in arraylist but listview not updating still showing deleted item from database. it has bug only when navigated from other fragments to this fragment.
any help please. dunno where went wrong. have been calling
following is my fragment file.
public class SupplierViewFragment extends Fragment {
private ArrayList<Supplier> suppliers = new ArrayList<>();
ListView lvListView;
FunDapter adapter;
ListView lvSupplierList;
TextView tvSupplierViewMessage;
private FragmentTransaction fragmentTransaction;
ViewPager pager;
private AdapterView.AdapterContextMenuInfo info;
BindDictionary<Supplier> dictionary = new BindDictionary<>();
public SupplierViewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_supplier_view, container, false);
tvSupplierViewMessage = (TextView) view.findViewById(R.id.tvSupplierViewMessage);
tvSupplierViewMessage.setVisibility(View.INVISIBLE);
getData("supplier-view-servlet");
dictionary = new BindDictionary<>();
dictionary.addStringField(R.id.tvSupplierListID, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return "ID: " + item.getSupplierID();
}
});
dictionary.addStringField(R.id.tvSupplierListCompanyName, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierCompanyName();
}
});
dictionary.addStringField(R.id.tvSupplierListName, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return "(" + item.getSupplierName() + ")";
}
});
dictionary.addStringField(R.id.tvSupplierListAddress, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierAddress();
}
});
dictionary.addStringField(R.id.tvSupplierListTelp, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierTelp();
}
});
dictionary.addStringField(R.id.tvSupplierListMobile, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierMobile();
}
});
dictionary.addStringField(R.id.tvSupplierListEmail, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierEmail();
}
});
dictionary.addStringField(R.id.tvSupplierListCity, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return getCityName("cities-servlet?city-id=" + item.getSupplierCity());
}
});
dictionary.addStringField(R.id.tvSupplierListCountry, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return getCountryName("countries-servlet?city-id=" + item.getSupplierCity());
}
});
adapter = new FunDapter(SupplierViewFragment.this.getActivity(),suppliers,R.layout.supplier_list_layout,dictionary);
lvSupplierList = (ListView) view.findViewById(R.id.lvSupplierView);
lvSupplierList.setAdapter(adapter);
adapter.notifyDataSetChanged();
registerForContextMenu(lvSupplierList);
pager = (ViewPager) getActivity().findViewById(R.id.pager);
return view;
}
public void refreshApi(){
suppliers.clear();
adapter.resetData();
getData("supplier-view-servlet");
lvSupplierList.setAdapter(adapter);
adapter.notifyDataSetChanged();
lvSupplierList.invalidate();
//adapter = new FunDapter(SupplierViewFragment.this.getActivity(),suppliers,R.layout.supplier_list_layout,dictionary);
Log.d("REFRESH", suppliers.size()+" -------------------");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String text = null;
switch (item.getItemId()){
case R.id.supplier_view_delete_id:
AlertDialog.Builder builder = new AlertDialog.Builder(SupplierViewFragment.this.getActivity());
builder.setMessage("Are sure to delete selected supplier?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Supplier supplier = new Supplier(suppliers.get(info.position).getSupplierID());
try {
Log.d("Supplier Size:",suppliers.size() + "to delete:" + info.position);
deleteData("supplier-delete-servlet?supplier-id=" + supplier.getSupplierID() );
suppliers.clear();
refreshApi();
Log.d("Supplier AFTER:",suppliers.size() + "to delete:" + info.position);
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
pager.setCurrentItem(0);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(SupplierViewFragment.this.getActivity(),"Supplier Deleted",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No",null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
case R.id.supplier_view_edit_id:
//StaffEditFragment staffEditFragment = new StaffEditFragment.newInstance("Some1","Some2");
Log.d("Current Position:",""+info.position);
Supplier supplierEdit = suppliers.get(info.position);
Bundle bundle = new Bundle();
bundle.putInt("supplierID",supplierEdit.getSupplierID());
SupplierEditFragment supplierEditFragment = new SupplierEditFragment();
supplierEditFragment.setArguments(bundle);
fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,supplierEditFragment);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Edit Supplier");
fragmentTransaction.commit();
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.supplier_context_menu,menu);
}
public void deleteData(String servletAddress){
JsonRequestHelper requestHelper = new JsonRequestHelper();
JSONArray jsonArray = requestHelper.getJsonArrayViaGET(servletAddress);
}
public String getCountryName(String servletAddress){
String countryName = null;
try {
JsonRequestHelper requestHelper = new JsonRequestHelper();
JSONArray jsonArray = requestHelper.getJsonArrayViaGET(servletAddress);
for (int i = 0; i < jsonArray.length(); i++) {
countryName = jsonArray.getJSONObject(i).getString("country-name").toString();
}
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("cityName:",countryName);
return countryName;
}
public String getCityName(String servletAddress){
String cityName = null;
try {
JsonRequestHelper requestHelper = new JsonRequestHelper();
JSONArray jsonArray = requestHelper.getJsonArrayViaGET(servletAddress);
for (int i = 0; i < jsonArray.length(); i++) {
cityName = jsonArray.getJSONObject(i).getString("city-name").toString();
}
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("cityName:",cityName);
return cityName;
}
public void getData(String servletAddress){
JsonRequestHelper requestHelper = new JsonRequestHelper();
JSONArray jsonArray = requestHelper.getJsonArrayViaGET(servletAddress);
Supplier supplier = new Supplier();
if (jsonArray == null) {
//Log.d("Reach000","#####################");
tvSupplierViewMessage.setVisibility(View.VISIBLE);
tvSupplierViewMessage.setText("Error Connecting Database");
Toast.makeText(SupplierViewFragment.this.getActivity(), "Error Connection", Toast.LENGTH_SHORT).show();
}
else {
tvSupplierViewMessage.setVisibility(View.INVISIBLE);
tvSupplierViewMessage.setText("");
try {
for (int i = 0; i < jsonArray.length(); i++) {
supplier = new Supplier();
supplier.setSupplierID(Integer.parseInt(jsonArray.getJSONObject(i).get("id").toString()));
supplier.setSupplierCompanyName(jsonArray.getJSONObject(i).get("company-name").toString());
supplier.setSupplierName(jsonArray.getJSONObject(i).get("name").toString());
supplier.setSupplierAddress(jsonArray.getJSONObject(i).get("address").toString());
supplier.setSupplierCity(Integer.parseInt(jsonArray.getJSONObject(i).get("city-id").toString()));
supplier.setSupplierEmail(jsonArray.getJSONObject(i).get("email").toString());
supplier.setSupplierTelp(jsonArray.getJSONObject(i).get("telp").toString());
supplier.setSupplierMobile(jsonArray.getJSONObject(i).get("mobile").toString());
suppliers.add(supplier);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
You can add a updateDataset(ArrayList suppliers) method in adapter and call it whenever you want to update listview content.
Add below method in adapter,
public void updateDataset(ArrayList<Supplier> suppliers) {
this.suppliers = suppliers;
notifyDatasetChanged();
}
When you delete item from database,fetch new data and call,
adapter.updateDataset(ArrayList<Supplier> suppliers)
problem solved by replacing it as a new fragment everytime it deletes an item. not sure if it's the right way but at least work for the moments. Thanks for the response guys. hope it helps for others looking for similiar problems.
fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new SupplierFragment());
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("View Supplier");
fragmentTransaction.commit();
return super.onContextItemSelected(item);
I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.
Below is my code.
UserListFragment.java
public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
* 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 UsersListFragment.
*/
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
UsersListFragment fragment = new UsersListFragment();
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);
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
Log.i(TAG, "UsersListFragment onCreate");
users = new ArrayList<>();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh","userlistview");
preferenceEditor.commit();
FirebaseUtil uts = new FirebaseUtil(getContext());
uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
Log.i(TAG, Success);
setHasOptionsMenu(true);
String partnerKey = (String) response.get("key");
if (partnerKey != null) {
Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
String type = (String) typeCheck.get("type");
if (type.equals("chat")) {
String key1 = Global.getInstance().ownerId;
String key2 = partnerKey;
partnerKeyValue = partnerKey;
if (key2 != null) {
String currentPartner = Global.getInstance().partnerId;
if (currentPartner.length() > 0) {
if (currentPartner.equals(partnerKey)) {
} else {
Global.getInstance().unreadMessageUsers.add(partnerKey);
}
Global.getInstance().unreadMessageUsers.add(partnerKey);
} else {
}
}
}
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "UsersListFragment onResume");
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "UsersListFragment onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
FirebaseUtil util = new FirebaseUtil(getContext());
util.updateUserStatus(Global.getInstance().ownerId, "4");
Log.i(TAG, "UsersListFragment onDestroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(actionBar!=null) {
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setLogo(R.drawable.ic_logo);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
actionBar.setBackgroundDrawable(colorDrawable);
}
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
int vd = users.size();
view = inflater.inflate(R.layout.fragment_userslist, container, false);
listView = (ListView) view.findViewById(R.id.userdisplay);
adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
listView.setAdapter(adapter);
if (users.size()==0){
usersList();
}else {
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserData data = users.get(position);
Global.getInstance().someData = data.getId();
Global.getInstance().partnerId = data.getId();
int i = 0;
for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
String element = iter.next();
if (element.equals(data.getId().toString())) {
iter.remove();
}
}
data.setUnreadMessageCount(0);
users.remove(position);
users.add(position, data);
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(ChatFragment.DATA_RECEIVE, data.getName());
fragmentOne .setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.framecontainerMain, fragmentOne).commit();
}
});
// Inflate the layout for this fragment
return view;
}
public void usersList () {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
//get the data from userlist api
final String URL = "url";
String token = preferenceSettings.getString("authToken","");
final String userId = preferenceSettings.getString("userId","");
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id",userId);
params.put("auth_token",token);
progressBar.show();
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse:" +response);
String success = null;
try {
success = response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success == "true") {
JSONArray Array = null;
try {
//get the users
} else {
users.add(data);
}
}
Log.i(TAG, "arraylist");
adapter.notifyDataSetChanged();
onlineUsers();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
progressBar.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj;
} else {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.dismiss();
VolleyLog.e("Error: ", error.getMessage());
Log.i(TAG, "onErrorResponse:" +error.networkResponse);
}
});
ApplicationController.getInstance().addToRequestQueue(myRequest);
myRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void sortingArray(){
if (users.size()>0) {
synchronized (this) {
if (Global.getInstance().unreadMessageUsers.size() > 0) {
System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : Global.getInstance().unreadMessageUsers) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
System.out.println("\nSorted Map");
Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);
for (String key : unreadCount.keySet()) {
int count_unread = unreadCount.get(key);
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setUnreadMessageCount(count_unread);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}
synchronized (this) {
if (Global.getInstance().userStatus.size() > 0) {
try {
for (Object dict : Global.getInstance().userStatus) {
Map<String, Object> val = (Map<String, Object>) dict;
String key = val.keySet().iterator().next();
val.get(key).toString().trim();
int statusValue;
if (val.get(key).toString().equals("")) {
statusValue = 4;
} else {
statusValue = Integer.valueOf(val.get(key).toString());
}
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setOnlineStatus(statusValue);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}catch (ConcurrentModificationException e){
e.printStackTrace();
}
}
}
Log.i(TAG, users.get(0).getName());
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
return 1;
} else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
return -1;
} else {
return 0;
}
}
});
}
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
return -1;
} else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
return 1;
} else {
return 0;
}
}
});
Global.getInstance().userStatus.clear();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
public void TimerMethod() {
synchronized(this) {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
String checkView = preferenceSettings.getString("refresh", "");
if (checkView.equals("userlistview")) {
if (Global.getInstance().userStatus.size() > 0) {
sortingArray();
}
} else {
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh", "userlistview");
preferenceEditor.commit();
if (Global.getInstance().unreadMessageUsers.size() > 0){
sortingArray();
}
}
}
}
public void onlineUsers (){
String value;
for (UserData data : users) {
value = data.getId();
FirebaseUtil online = new FirebaseUtil(getContext());
online.onlineUsers(value, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
if (response == null) {
} else {
Global.getInstance().userStatus.add(response);
}
}
});
}
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.menu_userlist,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private void logoutUser(){
Intent I = new Intent(getActivity(), LoginActivity.class);
startActivity(I);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSearch :
return true;
case R.id.menuLogout :
logoutUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
myTimer.cancel();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String val);
}
}
menu_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="#string/search"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
<item android:id="#+id/menuLogout"
android:title="#string/logout"
android:icon="#drawable/ic_logout"
android:tint="#android:color/white"
app:showAsAction="always">
</item>
</menu>
CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<UserData> {
private Activity activity;
private List<UserData> messages;
public CustomAdapter(Activity context, int resource, List<UserData> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
packagename.CustomAdapter.ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
UserData data = getItem(position);
int viewType = getItemViewType(position);
layoutResource = R.layout.program_list;
if (convertView != null) {
holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(data.getName());
holder.id = data.geId();
holder.roleMsg.setText(data.getRole());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
private String id;
private TextView roleMsg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.textView1);
roleMsg = (TextView) v.findViewById(R.id.textView2);
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity implements UsersListFragment.OnFragmentInteractionListener {
private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
VideoFragment fragmentTwo ;
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
}
public void attemptLogin1() {
String test = "one";
String tested = "fail";
}
#Override
public void onFragmentInteraction(String uri) {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragmentOne = new ChatFragment();
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
}
I have written setHasOptionsMenu(true); in onCreate of UserFragment.java
The logout functionality works fine but the search isn't working.
I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(
Any help is appreciated.
Thanks in advance.
Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.
Remove this line and it will work
case R.id.menuSearch:
return true;
I have five tabs they are 1.home 2.menu 3.cart 4.account 5.more.Here cart tab consist of list view which is having the remove button in it,when i click on that remove button it must refresh the fragment itself so that it can load new data from the Json
MainActivity.class
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Session cartsession=new Session(getApplicationContext());
if (cartsession.isLoggedIn()){
if (position==2){
((Cart) pageAdapter.getItem(position)).cartdata();
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
}
TabAdapter.class
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Cart.Java
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
SharedPreferences loginPreferences;
SharedPreferences.Editor loginPrefsEditor;
TextView cartstatus,cartempty;
LinearLayout linearlay;
RelativeLayout cartvisible;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartstatus = (TextView) cartfrag.findViewById(R.id.cartstatus);
cartempty = (TextView) cartfrag.findViewById(R.id.cartempty);
linearlay = (LinearLayout) cartfrag.findViewById(R.id.linearlay);
cartvisible = (RelativeLayout) cartfrag.findViewById(R.id.cartvisible);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged = new Session(getActivity());
if (cartlogged.isLoggedIn()) {
cartitems.clear();
cartdata();
} else {
cartstatus.setText("Please Login");
}
return cartfrag;
}
void cartdata() {
cartitems.clear();
SharedPreferences customerid = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid = customerid.getString("customerid", "");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("empty")) {
cartstatus.setVisibility(View.GONE);
cartempty.setText("Your Cart is Empty");
} else {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
linearlay.setVisibility(View.VISIBLE);
cartvisible.setVisibility(View.GONE);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
JSONObject subobj = response.getJSONObject("details");
String subtext = subobj.getString("subtotal");
loginPrefsEditor.putString("Price", subtext);
loginPrefsEditor.commit();
subtotal.setText(subtext);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
}
CartAdapter.class
public class CartAdapter extends BaseAdapter {
Context context;
TextView quantity, basenamecart, cartprice;
ImageButton delete;
private List<JSONParser> cartitems;
LayoutInflater inflater;
String removequantity, removeitemprice,removebasename;
public CartAdapter(Context context, List<JSONParser> cartitems) {
this.context = context;
this.cartitems = cartitems;
}
#Override
public int getCount() {
return cartitems.size();
}
#Override
public Object getItem(int position) {
return cartitems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart();
}
});
}
return convertView;
}
private void removecart(){
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}
}
You need to remove the concerned object from the list cartitems and then call the notifyDataSetChanged() method to notify the any dependent views to refresh itself.
Documentation here
Also, this is not the correct way to implement a BaseAdapter and handle changes in it. Maybe this will help : http://androidadapternotifiydatasetchanged.blogspot.in/
Also, try using the new RecyclerView in order to implement such things. It is available in the support library and definitely a good way to display collections and also makes it easy to add remove items with default animations too. Please read through it. A starting point http://developer.android.com/training/material/lists-cards.html
see added line and updated line.
add make sure only remove item from list if removed successfully from server.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
final int pos =position; // added line
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart(pos); //updated line
}
});
}
return convertView;
}
public void updateCartitems(List<JSONParser> newCartitems) {
cartitems.clear();
cartitems.addAll(newCartitems);
this.notifyDataSetChanged();
}
private void removecart(int pos){ // updated line
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
cartitems.remove(pos); //added line
updateCartitems(cartitems);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}
hi friends i am new to the android development i am developing an app similar to flipkart. i am using the tab layout where there are 4tabs 1.home 2.menu 3.cart 4.settings
Each tab consists of list view where each one is having fragment in it,when i click the menu button and select an item that i want to order,after ordering it, it is not loading in the cart so i am not able to locate the item in the cart
MenuAdapter.Java
public class Second_adapter extends BaseAdapter {
Context context;
TextView basename, SubItemprice, itemdesc, SubItemdesc;
LayoutInflater inflater;
ImageView order;
private List<JSONParser> items;
String itembasename, itemde, subtmsub, subitempri;
SharedPreferences.Editor loginPrefsEditor;
public Second_adapter(Context context, List<JSONParser> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_clicked, viewGroup, false);
basename = (TextView) view.findViewById(R.id.basename);
SubItemprice = (TextView) view.findViewById(R.id.SubItemprice);
itemdesc = (TextView) view.findViewById(R.id.itemdesc);
SubItemdesc = (TextView) view.findViewById(R.id.SubItemdesc);
order = (ImageView) view.findViewById(R.id.order);
final JSONParser setdata = items.get(i);
basename.setText(setdata.getBaseName());
itemdesc.setText(setdata.getItemdesc());
SubItemdesc.setText(setdata.getSubItemdesc());
SubItemprice.setText(setdata.getSubItemprice());
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itembasename = setdata.getBaseName();
itemde = setdata.getItemdesc();
subtmsub = setdata.getSubItemdesc();
subitempri = setdata.getSubItemprice();
Session userloggedin=new Session(context);
if (userloggedin.isLoggedIn()){
addcart();
Cart cart=new Cart();
cart.cartdata();
Toast.makeText(context, "LoggedIn" +itembasename+itemde+subtmsub+subitempri, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Please Login", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void addcart() {
SharedPreferences customerid=context.getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String addcarturl = "http://standardtakeaway.co.uk/json/cart_process.php?userid="+customid+"&Item="+itembasename+itemde+subtmsub+"&Itemcount=1&price="+subitempri;
Log.d("Cart",addcarturl);
JsonArrayRequest cartreq=new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
try {
JSONObject cartobj=response.getJSONObject(i);
String count=cartobj.getString("count");
loginPrefsEditor.putString("Badge",count);
loginPrefsEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(cartreq);
}
}
Cart.Class
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged=new Session(getActivity());
if (cartlogged.isLoggedIn()){
cartdata();
}else {
Toast.makeText(getActivity(),"Not Logged", Toast.LENGTH_SHORT).show();
}
cartdata();
return cartfrag;
}
void cartdata() {
SharedPreferences customerid=getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
}
JSONObject subobj=response.getJSONObject("details");
String subtext=subobj.getString("subtotal");
subtotal.setText(subtext);
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
TabLayout.java
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
}
MainActivity.java
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
mViewpager.setOffscreenPageLimit(4);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can fix this way by setting setOnPageChangeListener on viewPager:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int index) {
// TODO Auto-generated method stub
if(index==3){
((Cart) mAdapter.getItem(index)).cartdata();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
Your cartdata() must be public.