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;
Related
Add some fragment continuously then RecyclerView scroll lagging
I am remove image load library but not any improvement i am face same
problem.
I am also check this link click
add fragment then facing this problem. but replace fragment then not facing this problem
more add fragment then RecyclerView lagging. i think fragment memory issue
add more then three fragment continuously then face this problem
fragment xml
<FrameLayout
android:id="#+id/frameLayout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_main"
android:layout_above="#+id/linearLayout_adView_main" />
call fragment data
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelatedFragment relatedFragment = new RelatedFragment();
Bundle bundle = new Bundle();
bundle.putString("type", "related");
bundle.putString("post_id", statusLists.getId());
bundle.putString("cat_id", statusLists.getCid());
bundle.putString("typeLayout", "Landscape");
relatedFragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.frameLayout_main, relatedFragment, string).addToBackStack(string).commitAllowingStateLoss();
}
});
xml file
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_sub_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp" />
Fragment
public class RelatedFragment extends Fragment {
private Method method;
private OnClick onClick;
private String type, post_id, cat_id, typeLayout;
private ProgressBar progressBar;
private MaterialTextView textView_noData;
private RecyclerView recyclerView;
private List<SubCategoryList> relatedLists;
private SubCategoryAdapter subCategoryAdapter;
private LayoutAnimationController animation;
private Boolean isOver = false;
private int pagination_index = 1;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.portrait_fragment, container, false);
GlobalBus.getBus().register(this);
MainActivity.toolbar.setTitle(getResources().getString(R.string.related_status));
relatedLists = new ArrayList<>();
onClick = new OnClick() {
#Override
public void position(int position, String title, String type, String status_type, String id, String tag) {
SCDetailFragment scDetailFragment = new SCDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("type", type);
bundle.putString("status_type", status_type);
bundle.putInt("position", position);
scDetailFragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.frameLayout_main, scDetailFragment, title).addToBackStack(title).commitAllowingStateLoss();
}
};
method = new Method(getActivity(), onClick);
assert getArguments() != null;
type = getArguments().getString("type");
post_id = getArguments().getString("post_id");
cat_id = getArguments().getString("cat_id");
typeLayout = getArguments().getString("typeLayout");
int resId = R.anim.layout_animation_fall_down;
animation = AnimationUtils.loadLayoutAnimation(getActivity(), resId);
progressBar = view.findViewById(R.id.progressbar_portrait_fragment);
textView_noData = view.findViewById(R.id.textView_portrait_fragment);
recyclerView = view.findViewById(R.id.recyclerView_portrait_fragment);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
if (!isOver) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
pagination_index++;
callData();
}
}, 1000);
} else {
subCategoryAdapter.hideHeader();
}
}
});
callData();
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.ic_searchView);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener((new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (method.isNetworkAvailable()) {
backStackRemove();
SearchFragment searchFragment = new SearchFragment();
Bundle bundle = new Bundle();
bundle.putString("search_menu", query);
bundle.putString("typeLayout", "Landscape");
searchFragment.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.frameLayout_main, searchFragment, query).commitAllowingStateLoss();
return false;
} else {
method.alertBox(getResources().getString(R.string.internet_connection));
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
}));
super.onCreateOptionsMenu(menu, inflater);
}
private void backStackRemove() {
for (int i = 0; i < getActivity().getSupportFragmentManager().getBackStackEntryCount(); i++) {
getActivity().getSupportFragmentManager().popBackStack();
}
}
#Subscribe
public void getNotify(Events.FavouriteNotify favouriteNotify) {
for (int i = 0; i < relatedLists.size(); i++) {
if (relatedLists.get(i).getId().equals(favouriteNotify.getId())) {
if (relatedLists.get(i).getStatus_type().equals(favouriteNotify.getStatus_type())) {
relatedLists.get(i).setIs_favourite(favouriteNotify.getIs_favourite());
subCategoryAdapter.notifyItemChanged(i);
}
}
}
}
#Subscribe
public void getMessage(Events.InfoUpdate infoUpdate) {
if (subCategoryAdapter != null) {
for (int i = 0; i < relatedLists.size(); i++) {
if (relatedLists.get(i).getId().equals(infoUpdate.getId())) {
if (relatedLists.get(i).getStatus_type().equals(infoUpdate.getStatus_type())) {
switch (infoUpdate.getType()) {
case "all":
relatedLists.get(i).setTotal_viewer(infoUpdate.getView());
relatedLists.get(i).setTotal_likes(infoUpdate.getTotal_like());
relatedLists.get(i).setAlready_like(infoUpdate.getAlready_like());
break;
case "view":
relatedLists.get(i).setTotal_viewer(infoUpdate.getView());
break;
case "like":
relatedLists.get(i).setTotal_likes(infoUpdate.getTotal_like());
relatedLists.get(i).setAlready_like(infoUpdate.getAlready_like());
break;
}
subCategoryAdapter.notifyItemChanged(i);
}
}
}
}
}
private void callData() {
if (getActivity() != null) {
if (method.isNetworkAvailable()) {
if (method.pref.getBoolean(method.pref_login, false)) {
related(method.pref.getString(method.profileId, null), post_id, cat_id, typeLayout);
} else {
related("0", post_id, cat_id, typeLayout);
}
} else {
method.alertBox(getResources().getString(R.string.internet_connection));
}
}
}
private void related(String userId, String post_id, String cat_id, String typeLayout) {
if (subCategoryAdapter == null) {
relatedLists.clear();
progressBar.setVisibility(View.VISIBLE);
}
if (getActivity() != null) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(new API(getActivity()));
jsObj.addProperty("method_name", "related_status");
jsObj.addProperty("post_id", post_id);
jsObj.addProperty("cat_id", cat_id);
jsObj.addProperty("user_id", userId);
jsObj.addProperty("page", pagination_index);
jsObj.addProperty("filter_value", typeLayout);
jsObj.addProperty("lang_ids", method.pref.getString(method.language_ids, ""));
params.put("data", API.toBase64(jsObj.toString()));
client.post(Constant_Api.url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if (getActivity() != null) {
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
if (jsonObject.has(Constant_Api.STATUS)) {
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (status.equals("-2")) {
method.suspend(message);
} else {
method.alertBox(message);
}
} else {
JSONArray jsonArray = jsonObject.getJSONArray(Constant_Api.tag);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String status_type = object.getString("status_type");
String status_title = object.getString("status_title");
String status_layout = object.getString("status_layout");
String status_thumbnail_b = object.getString("status_thumbnail_b");
String status_thumbnail_s = object.getString("status_thumbnail_s");
String total_likes = object.getString("total_likes");
String total_viewer = object.getString("total_viewer");
String category_name = object.getString("category_name");
String already_like = object.getString("already_like");
String quote_bg = object.getString("quote_bg");
String quote_font = object.getString("quote_font");
String is_favourite = object.getString("is_favourite");
relatedLists.add(new SubCategoryList("", id, status_type, status_title, status_layout, status_thumbnail_b, status_thumbnail_s, total_viewer, total_likes, already_like, category_name, quote_bg, quote_font, is_favourite, "", ""));
}
if (jsonArray.length() == 0) {
if (subCategoryAdapter != null) {
isOver = true;
subCategoryAdapter.hideHeader();
}
}
if (subCategoryAdapter == null) {
if (relatedLists.size() == 0) {
textView_noData.setVisibility(View.VISIBLE);
} else {
textView_noData.setVisibility(View.GONE);
subCategoryAdapter = new SubCategoryAdapter(getActivity(), relatedLists, onClick, type);
recyclerView.setAdapter(subCategoryAdapter);
recyclerView.setLayoutAnimation(animation);
}
} else {
subCategoryAdapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
method.alertBox(getResources().getString(R.string.failed_try_again));
}
}
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
progressBar.setVisibility(View.GONE);
method.alertBox(getResources().getString(R.string.failed_try_again));
}
});
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Unregister the registered event.
GlobalBus.getBus().unregister(this);
}
}
Adapter
public class SubCategoryAdapter extends RecyclerView.Adapter {
private Activity activity;
private Method method;
private int columnWidth;
private String type;
private Animation myAnim;
private List<SubCategoryList> subCategoryLists;
private final int VIEW_TYPE_LOADING = 0;
private final int VIEW_TYPE_ITEM = 1;
private final int VIEW_TYPE_QUOTES = 2;
public SubCategoryAdapter(Activity activity, List<SubCategoryList> subCategoryLists, OnClick interstitialAdView, String type) {
this.activity = activity;
this.type = type;
this.subCategoryLists = subCategoryLists;
method = new Method(activity, interstitialAdView);
columnWidth = (method.getScreenWidth());
myAnim = AnimationUtils.loadAnimation(activity, R.anim.bounce);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(activity).inflate(R.layout.sub_category_adapter, parent, false);
return new ViewHolder(view);
} else if (viewType == VIEW_TYPE_QUOTES) {
View v = LayoutInflater.from(activity).inflate(R.layout.quotes_adapter, parent, false);
return new Quotes(v);
} else if (viewType == VIEW_TYPE_LOADING) {
View v = LayoutInflater.from(activity).inflate(R.layout.layout_loading_item, parent, false);
return new ProgressViewHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") final int position) {
if (holder.getItemViewType() == VIEW_TYPE_ITEM) {
final ViewHolder viewHolder = (ViewHolder) holder;
if (status_type.equals("gif")) {
Glide.with(activity)
.asBitmap()
.load(subCategoryLists.get(position).getStatus_thumbnail_s())
.placeholder(R.drawable.placeholder_landscape).into(viewHolder.imageView);
} else {
Glide.with(activity)
.load(subCategoryLists.get(position).getStatus_thumbnail_s())
.placeholder(R.drawable.placeholder_landscape).into(viewHolder.imageView);
}
viewHolder.imageView.setLayoutParams(new RelativeLayout.LayoutParams(columnWidth, columnWidth / 2 - 60));
viewHolder.textView_title.setText(subCategoryLists.get(position).getStatus_title());
viewHolder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
method.onClickData(position, subCategoryLists.get(position).getStatus_title(), type, subCategoryLists.get(position).getStatus_type(), subCategoryLists.get(position).getId(), "");
}
});
} else if (holder.getItemViewType() == VIEW_TYPE_QUOTES) {
final Quotes quotes = (Quotes) holder;
quotes.relativeLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, columnWidth / 2));
Typeface typeface = Typeface.createFromAsset(activity.getAssets(), "text_font/" + subCategoryLists.get(position).getQuote_font());
quotes.textView.setTypeface(typeface);
quotes.textView.setText(subCategoryLists.get(position).getStatus_title());
quotes.textView.post(new Runnable() {
#Override
public void run() {
ViewGroup.LayoutParams params = quotes.textView.getLayoutParams();
if (params == null) {
params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
final int widthSpec = View.MeasureSpec.makeMeasureSpec(quotes.textView.getWidth(), View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(quotes.textView.getHeight(), View.MeasureSpec.UNSPECIFIED);
quotes.textView.measure(widthSpec, heightSpec);
quotes.textView.setMaxLines(heightSpec / quotes.textView.getLineHeight());
quotes.textView.setEllipsize(TextUtils.TruncateAt.END);
}
});
quotes.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
method.onClickData(position, subCategoryLists.get(position).getStatus_title(), type, subCategoryLists.get(position).getStatus_type(), subCategoryLists.get(position).getId(), "");
}
});
}
}
#Override
public int getItemCount() {
return subCategoryLists.size() + 1;
}
public void hideHeader() {
ProgressViewHolder.progressBar.setVisibility(View.GONE);
}
#Override
public int getItemViewType(int position) {
if (position != subCategoryLists.size()) {
if (subCategoryLists.get(position).getStatus_type().equals("quote")) {
return VIEW_TYPE_QUOTES;
} else {
return VIEW_TYPE_ITEM;
}
} else {
return VIEW_TYPE_LOADING;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout relativeLayout;
private ImageView imageView;
private MaterialTextView textView_title;
public ViewHolder(View itemView) {
super(itemView);
relativeLayout = itemView.findViewById(R.id.relativeLayout_subCat_adapter);
imageView = itemView.findViewById(R.id.imageView_subCat_adapter);
textView_title = itemView.findViewById(R.id.textView_title_subCat_adapter);
}
}
public class Quotes extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private RelativeLayout relativeLayout;
private MaterialTextView textView;
public Quotes(#NonNull View itemView) {
super(itemView);
linearLayout = itemView.findViewById(R.id.ll_quotes_adapter);
textView = itemView.findViewById(R.id.textView_quotes_adapter);
relativeLayout = itemView.findViewById(R.id.rel_quotes_adapter);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public static ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = v.findViewById(R.id.progressBar);
}
} }
This is my MediaTab.java Activity and it has fragment TabImage.
public class MediaTab extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
TabImage.OnFragmentInteractionListener,
TabPdf.OnFragmentInteractionListener {
Toolbar toolbar;
HashMap<String, String> groupName;
private ArrayList<String> groupNameArray;
Spinner group;
UserService userService;
SharedPreferences.Editor sharedPref;
String groupIdString;
private String TAG = MediaTab.class.getSimpleName();
ViewPager viewPager;
TabImage obj;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_tab);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sharedPref = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE).edit();
groupNameArray = new ArrayList<>();
userService = ApiUtils.getUserService();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Media");
group = findViewById(R.id.groupspinner);
groupName = new HashMap<>();
viewPager = findViewById(R.id.viewpager);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
getCategories();
group.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
groupIdString = groupName.get(groupNameArray.get(position));
Log.d(TAG, "onItemClick:valueID " + groupIdString);
Bundle bundle = new Bundle();
bundle.putString("params", groupIdString);
obj = new TabImage();
obj.setArguments(bundle);
setupViewPager(viewPager);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(obj, "MEDIA");
adapter.addFragment(new TabPdf(), "FILE");
viewPager.setAdapter(adapter);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void getCategories() {
Call<CreatePostList> userServicePost = userService.getschema(App.getToken());
userServicePost.enqueue(new Callback<CreatePostList>() {
#Override
public void onResponse(Call<CreatePostList> call, Response<CreatePostList> response) {
if (response.isSuccessful()) {
CreatePostList createPostList = response.body();
List<Group> groups;
groups = createPostList.getGroups();
for (int j = 0; j < groups.size(); j++) {
groupName.put(groups.get(j).getName(), groups.get(j).getId());
}
Set<String> strings1 = groupName.keySet();
ArrayList<String> arrayList1 = new ArrayList<>();
arrayList1.addAll(strings1);
groupNameArray = arrayList1;
SpinnerMediaAdapter customAdapter2 = new SpinnerMediaAdapter(getApplicationContext(), R.layout.spinnertems_layout, R.id.spinnertems_text, groupNameArray);
group.setAdapter(customAdapter2);
// if(groupNameArray.size() > 0) {
// groupIdString = groupName.get(groupNameArray.get(0));
// Log.d(TAG, "onResponse: .... setting at load " + groupIdString);
// Bundle bundle = new Bundle();
// bundle.putString("params", groupIdString);
// TabImage myObj = new TabImage();
// myObj.setArguments(bundle);
// }
// setupViewPager(viewPager);
}
}
#Override
public void onFailure(Call<CreatePostList> call, Throwable t) {
Toast.makeText(MediaTab.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
This is my fragment "TabImage" where i am getting bundle.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_image, container, false);
if (getArguments() != null) {
myDataFromActivity = getArguments().getString("params");
Log.d(TAG, "onCreate: tab activity " + myDataFromActivity);
}
mRecyclerView = view.findViewById(R.id.tabimgrv);
mRecyclerView.setFitsSystemWindows(true);
mRecyclerView.setHasFixedSize(true);
progressBar = view.findViewById(R.id.myprog);
userService = ApiUtils.getUserService();
activity = (MediaTab) getActivity();
GridLayoutManager manager = new GridLayoutManager(this.getActivity(), 2, GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(manager);
getPostList(currentPage);
mRecyclerView.addOnScrollListener(new PaginationMediaScrolling(manager) {
#Override
protected void loadMoreItems() {
Log.d("TabImage :", "loadMoreItems() called");
if (!isLastPage()) {
{
isLoading = true;
currentPage = currentPage + 1;
loadNextpage(currentPage);
}
}
}
#Override
public int getTotalPageCount() {
return TOTAL_PAGES;
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
return view;
}
private void getPostList(int currentPage) {
// progressBar.setVisibility(View.VISIBLE);
Call<GetImage> userServicePost = userService.getMediaImage(App.getToken(), myDataFromActivity, currentPage);
userServicePost.enqueue(new Callback<GetImage>() {
#Override
public void onResponse(Call<GetImage> call, Response<GetImage> response) {
// progressBar.setVisibility(View.GONE);
if (response.isSuccessful()) {
GetImage getImagemodel = response.body();
TOTAL_PAGES = totalPages(response);
Media media = getImagemodel.getMedia();
List<ResultMedia> resultMediaList = media.getResults();
mAdapter = new TabImageAdapter(getContext(), resultMediaList);
mRecyclerView.setAdapter(mAdapter);
if (currentPage <= TOTAL_PAGES) mAdapter.addLoadingFooter();
else isLastPage = true;
isLoading = false;
} else {
Toast.makeText(context, "Could not complete the request! Please try again.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<GetImage> call, Throwable t) {
}
});
}
how to change "myDataFromActivity" every time when i select value from spinner. and how to pass this changed value through bundle
Because groupid is dynamic value which will change every time
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();
I have recyclerview (in fragment) and fragment with details information to one of the element. All is good, but when my data was saved. I have bad results in my JSON file. All times when i open element of list he add new element inside JSON file, while he must overwrite oneself.
My Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_page_activity);
Log.i("MainActivity", "onCreate");
if(savedInstanceState==null) {
getFragment(new ObjectListFragment());
}
}
public void getFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
if (mFragment == null) {
mFragment = fragment;
fm.beginTransaction()
.add(R.id.fragment_container, mFragment)
.commit();
}
if (mFragment != null) {
mFragment = fragment;
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}
}
My Model:
public class Object {
private static final String JSON_ID = "id";
private static final String JSON_TITLE = "title";
private UUID mId;
private String mTitle;
public Object() {
mId=UUID.randomUUID();
}
public Object(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString(JSON_ID));
mTitle = json.getString(JSON_TITLE);
}
public JSONObject toJSON()throws JSONException{
JSONObject json = new JSONObject();
json.put(JSON_ID, mId.toString());
json.put(JSON_TITLE, mTitle);
return json;
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
#Override
public String toString() {
return mTitle;
}
}
ObjectLab:
public class ObjectLab {
private static final String TAG = "ObjectLab";
private static final String FILENAME = "reminder.json";
private ObjectJSON mSerializer;
private ArrayList<Object> mObjects;
private static ObjectLab sObjectLab;
private Context mContext;
private ObjectLab(Context context){
mContext = context;
mSerializer = new ObjectJSON(mContext, FILENAME);
try {
mObjects = mSerializer.loadReminders();
} catch (Exception e) {
mObjects = new ArrayList<Object>();
Log.e(TAG, "Error loading crimes: ", e);
}
}
public static ObjectLab get(Context c){
if(sObjectLab == null){
sObjectLab = new ObjectLab(c.getApplicationContext());
}
return sObjectLab;
}
public ArrayList<Object> getObjects(){
return mObjects;
}
public Object getReminder(UUID id){
for(Object c : mObjects){
if(c.getId().equals(id))
return c;
}
return null;
}
public void addReminder(Object c){
mObjects.add(0,c);
}
public void deleteReminder(Object c){
mObjects.remove(c);
}
public boolean saveReminders(){
try{
mSerializer.saveReminders(mObjects);
Log.d(TAG, "reminders saved to file");
return true;
}catch (Exception e){
Log.e(TAG, "Error saving crimes: ", e);
return false;
}
}
ObjectJSON:
public class ObjectJSON {
private Context mContext;
private String mFilename;
public ObjectJSON(Context context, String filename) {
mContext = context;
mFilename = filename;
}
public void saveReminders(ArrayList<Object> objects) throws JSONException, IOException {
Log.i("Save","saveReminders");
JSONArray array = new JSONArray();
for (Object f : objects)
array.put(f.toJSON());
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_APPEND);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
} finally {
if (writer != null)
writer.close();
}
}
public ArrayList<Object> loadReminders() throws IOException, JSONException {
Log.i("Save","loadReminders");
ArrayList<Object> objects = new ArrayList<Object>();
BufferedReader reader = null;
try {
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
jsonString.append(line);
}
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString())
.nextValue();
for (int i = 0; i < array.length(); i++) {
objects.add(new Object(array.getJSONObject(i)));
}
} catch (FileNotFoundException e) {
//when 0
} finally {
if (reader != null)
reader.close();
}
return objects;
}
ObjectListFragment:
public class ObjectListFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerAdapter mAdapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.reminder_activity, container, false);
Log.i("ObjectListFragment", "onCreateView");
final ArrayList<Object> mData = ObjectLab.get(getActivity()).getObjects();
getActivity().setTitle("Object");
mRecyclerView = (RecyclerView)v. findViewById(R.id.my_recycler_view);
//registerForContextMenu(mRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(mData);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(v.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.i("ObjectListFragment", "onItemClick");
Object f = mData.get(position);
FragmentManager fm = getFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
Bundle bundle = new Bundle();
bundle.putSerializable(ObjectFragment.EXTRA_REMINDER_ID, f.getId());
if (mFragment != null) {
mFragment = new ObjectFragment();
mFragment.setArguments(bundle);
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}
}));
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.d("Testing", "ID == " + id);
switch (id) {
case R.id.action_settings: {
Log.d("onOptionsItemSelected", " SETTings");
Object f = new Object();
ObjectLab.get(getActivity()).addReminder(f);
FragmentManager fm = getFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
Bundle bundle = new Bundle();
bundle.putSerializable(ObjectFragment.EXTRA_REMINDER_ID, f.getId());
if (mFragment != null) {
mFragment = new ObjectFragment();
mFragment.setArguments(bundle);
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
RecyclerAdapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
ArrayList<Object> mData;
public RecyclerAdapter(ArrayList<Object> objects) {
mData = objects;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reminder_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTitleTextView.setText(mData.get(position).getTitle());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView mTitleTextView;
public ViewHolder(View itemView) {
super(itemView);
mTitleTextView = (TextView) itemView.findViewById(R.id.forget_list_titleTextView);
}
}
RecyclerItemClickListener:
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildLayoutPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
and last ObjectFragmet
public class ObjectFragment extends Fragment{
public static final String EXTRA_REMINDER_ID = "id";
private Object mObject;
public static ObjectFragment newInstance(UUID crimeId) {
Log.i("ObjectFragment", "newInstance");
Bundle args = new Bundle();
args.putSerializable(EXTRA_REMINDER_ID, crimeId);
ObjectFragment fragment = new ObjectFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID uuid = (UUID) getArguments().getSerializable(EXTRA_REMINDER_ID);
Log.i("ObjectFragment", " "+uuid);
mObject = ObjectLab.get(getContext()).getReminder(uuid);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.remind_act, container, false);
EditText editText = (EditText)v.findViewById(R.id.editText1);
editText.setText(mObject.getTitle());
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
mObject.setTitle(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return v;
}
#Override
public void onPause() {
super.onPause();
Log.i("ObjectFragment", "onPause");
ObjectLab.get(getActivity()).saveReminders();
}
Links to the project(Android Studio).
Where my problem is that I do not. With pleasure hear all your comments and advice on the topic as well as that off-topic.
Your help will not forsake unattended.
When opening the OutputStream for writing into the file, you're using the Context.MODE_APPEND flag, which is causing the write operation to append and not overwrite as you intended, change it to:
OutputStream out = mContext.openFileOutput(mFilename, 0);
Also, there was no need to mention the RecyclerView at all, since it has nothing to do with the problem at hand.
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...