I have a problem with my detail activity layout screen. The details in the screen are showing but the screen loading does not stop after that. I need help to stop my screen loading after the details in the screen has been shown.
The main layout activity loads for a certain amount of time and it works fine but the detail activity layout keeps on loading without stopping.
DetailsFragment.java
public class DetailsFragment extends Fragment {
private static final String LOG_TAG = DetailsFragment.class.getSimpleName();
private static final String ARG_NEWS = "arg_news";
private static final String SAVE_NEWS = "save_news";
private static final String SAVE_FAVORITE_NEWS = "save_favorite_news";
private static final String SAVE_FAVORITE_SORT = "save_favorite_sort";
private static final String SAVE_FULLY_LOADED = "save_fully_loaded";
private static final String SAVE_SHARE_MENU_VISIBILITY = "save_share_menu_visibility";
private final ResponseReceiver mReceiver = new ResponseReceiver();
private Context mContext;
private News mNews;
private ShareActionProvider mShareActionProvider;
private MenuItem mShareMenuItem;
private ImageView mPosterImageView;
private OnLoadingFragmentListener mLoadingListener;
private boolean mIsFavoriteNews;
private boolean mIsFavoriteSort;
private boolean mIsFullyLoaded;
private boolean mIsShareMenuItemVisible;
public DetailsFragment() {
// Required empty public constructor
}
// Create new Fragment instance
public static DetailsFragment newInstance(News newsSelected) {
DetailsFragment fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_NEWS, newsSelected);
fragment.setArguments(args);
return fragment;
}
public static DetailsFragment newInstance() {
DetailsFragment fragment = new DetailsFragment();
return fragment;
}
// Listener to handle star button clicks. This button adds and remove news from
// content provider
private final View.OnClickListener mStarButtonOnClickListener = new View.OnClickListener() {
public void onClick(View view) {
// Can't save it to favorites db if news poster is not ready yet
if (mPosterImageView != null && !Utils.hasImage(mPosterImageView)) {
Toast.makeText(mContext, R.string.please_wait_poster_download,
Toast.LENGTH_SHORT).show();
return;
}
if (mIsFavoriteNews) {
if (removeFavoriteNews(mNews) > 0) {
Toast.makeText(mContext, R.string.success_remove_favorites, Toast
.LENGTH_SHORT)
.show();
((ImageButton) view).setImageResource(R.drawable.ic_star_border);
// Delete poster image stored in internal storage
Utils.deleteFileFromInternalStorage(mContext, mNews.getTitle());
mIsFavoriteNews = false;
} else {
Toast.makeText(mContext, R.string.fail_remove_favorites,
Toast.LENGTH_SHORT).show();
}
} else {
if (addFavoriteNews(mNews) != null) {
Toast.makeText(mContext, R.string.success_add_favorites, Toast
.LENGTH_SHORT).show();
((ImageButton) view).setImageResource(R.drawable.ic_star);
// Save poster image to internal storage
Bitmap posterBitmap = Utils.getBitmapFromImageView(mPosterImageView);
Utils.saveBitmapToInternalStorage(mContext, posterBitmap, mNews.getTitle());
mIsFavoriteNews = true;
} else {
Toast.makeText(mContext, R.string.fail_add_favorites, Toast
.LENGTH_SHORT).show();
}
}
}
};
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnLoadingFragmentListener) {
mLoadingListener = (OnLoadingFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnLoadingInteractionListener");
}
mContext = context;
}
#Override
public void onDetach() {
super.onDetach();
mLoadingListener = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mNews = getArguments().getParcelable(ARG_NEWS);
mIsFavoriteNews = isFavoriteNews(mContext, mNews);
mIsFavoriteSort = Utils.isFavoriteSort(mContext);
}
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.details_menu, menu);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
mShareMenuItem = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider
(mShareMenuItem);
setShareMenuItemAction();
super.onPrepareOptionsMenu(menu);
}
private void setShareMenuItemAction() {
if (mNews != null ) {
//String videoKey = mNews.getVideos()[0].getKey();
if (mShareActionProvider != null
&& mShareMenuItem != null) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
mShareActionProvider.setShareIntent(shareIntent);
mShareMenuItem.setVisible(true);
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(SAVE_NEWS, mNews);
outState.putBoolean(SAVE_FAVORITE_NEWS, mIsFavoriteNews);
outState.putBoolean(SAVE_FAVORITE_SORT, mIsFavoriteSort);
outState.putBoolean(SAVE_FULLY_LOADED, mIsFullyLoaded);
outState.putBoolean(SAVE_SHARE_MENU_VISIBILITY, mIsShareMenuItemVisible);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (mNews == null) {
return null;
}
// Restore objects value
if (savedInstanceState != null) {
mNews = savedInstanceState.getParcelable(SAVE_NEWS);
mIsFavoriteNews = savedInstanceState.getBoolean(SAVE_FAVORITE_NEWS);
mIsFavoriteSort = savedInstanceState.getBoolean(SAVE_FAVORITE_SORT);
mIsFullyLoaded = savedInstanceState.getBoolean(SAVE_FULLY_LOADED);
mIsShareMenuItemVisible = savedInstanceState.getBoolean(SAVE_SHARE_MENU_VISIBILITY);
}
View view = inflater.inflate(R.layout.fragment_details, container, false);
mPosterImageView = (ImageView) view.findViewById(R.id.news_img);
Glide.with(mContext).load(mNews.getImageUri())
.dontAnimate().into(mPosterImageView);
TextView titleView = (TextView) view.findViewById(R.id.title_content);
titleView.setText(mNews.getTitle());
TextView publishDateView = (TextView) view.findViewById(R.id.publish_date_content);
String date = Utils.formatDateForLocale(mNews.getPublishedDate());
publishDateView.setText(date);
TextView author = (TextView) view.findViewById(R.id.author_name);
author.setText(mNews.getAuthor());
TextView descriptionView = (TextView) view.findViewById(R.id.description_content);
TextView fullNewsUrl = (TextView) view.findViewById(R.id.news_full);
fullNewsUrl.setText(mNews.getFullNewsUrl());
// In portuguese, some news does not contain overview data. In that case, displays
// default text: #string/overview_not_available
if (!TextUtils.isEmpty(mNews.getDescription())) {
descriptionView.setText(mNews.getDescription());
}
ImageButton starButton = (ImageButton) view.findViewById(R.id.star_button);
starButton.setOnClickListener(mStarButtonOnClickListener);
if (mIsFavoriteNews) {
starButton.setImageResource(R.drawable.ic_star);
} else {
starButton.setImageResource(R.drawable.ic_star_border);
}
starButton.setVisibility(View.VISIBLE);
FrameLayout detailFrame = (FrameLayout) view.findViewById(R.id.detail_frame);
detailFrame.setVisibility(View.VISIBLE);
return view;
}
// Method that adds a News to content provider
private Uri addFavoriteNews(News news) {
Uri newsReturnUri = null;
try {
ContentValues newsContentValues = createNewsValues(news);
newsReturnUri = mContext.getContentResolver().insert(FavoriteNewsContract
.NewsEntry
.CONTENT_URI, newsContentValues);
} catch (SQLException e) {
Log.d(LOG_TAG, "SQLException while adding news to Favorite db");
e.printStackTrace();
}
return newsReturnUri;
}
// Method that removes a News from content provider
private int removeFavoriteNews(News news) {
int newsRemoved = mContext.getContentResolver().delete(FavoriteNewsContract
.NewsEntry.CONTENT_URI,
FavoriteNewsContract
.NewsEntry._ID + " = ?", new String[]{news.getTitle()});
return newsRemoved;
}
// Create news content values
private ContentValues createNewsValues(News news) {
ContentValues newsContentValues = new ContentValues();
// newsContentValues.put(FavoriteNewsContract.NewsEntry._ID, Integer.parseInt(news
// .getId()));
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_TITLE, news.getTitle());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_PUBLISH_DATE, news
.getPublishedDate());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_AUTHOR, news
.getAuthor());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_DESCRIPTION, news
.getDescription());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_FULL_NEWS_URL, news
.getFullNewsUrl());
newsContentValues.put(FavoriteNewsContract.NewsEntry.COLUMN_IMG_URL, news
.getImageUri()
.toString());
return newsContentValues;
}
// Method that query content provider and checks whether is a Favorite news or not
private boolean isFavoriteNews(Context ctx, News news) {
String newsID = news.getTitle();
Cursor cursor = ctx.getContentResolver().query(FavoriteNewsContract.NewsEntry
.CONTENT_URI, null,
FavoriteNewsContract.NewsEntry._ID + " = " + newsID, null, null);
if (cursor != null && cursor.moveToNext()) {
int newsIdColumnIndex = cursor.getColumnIndex(FavoriteNewsContract.NewsEntry._ID);
if (TextUtils.equals(newsID, cursor.getString(newsIdColumnIndex))) {
return true;
}
}
if (cursor != null) {
cursor.close();
}
return false;
}
#Override
public void onResume() {
super.onResume();
if (mNews != null) {
if (mReceiver != null) {
LocalBroadcastManager.getInstance(mContext)
.registerReceiver(mReceiver, new IntentFilter(Constants
.ACTION_EXTRA_INFO_RESULT));
}
if (!mIsFullyLoaded && !mIsFavoriteSort) {
Intent intent = new Intent(mContext, NewsIntentService.class);
intent.setAction(Constants.ACTION_EXTRA_INFO_REQUEST);
intent.putExtra(NewsIntentService.EXTRA_INFO_NEWS_ID, mNews.getTitle());
mContext.startService(intent);
if (mLoadingListener != null) {
mLoadingListener.onLoadingDisplay(true, true);
}
}
}
}
#Override
public void onPause() {
super.onPause();
if (mReceiver != null) {
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);
}
}
// BroadcastReceiver for network call
public class ResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getAction() == null) {
return;
}
if (intent.getAction().equals(Constants.ACTION_EXTRA_INFO_RESULT)) {
setShareMenuItemAction();
} else {
Toast.makeText(mContext, R.string.toast_failed_to_retrieve_data,
Toast.LENGTH_SHORT).show();
}
if (mLoadingListener != null) {
mLoadingListener.onLoadingDisplay(true, false);
}
mIsFullyLoaded = true;
}
}
}
DetailsActivity.java
public class DetailsActivity extends AppCompatActivity implements OnLoadingFragmentListener {
private static final String LOG_TAG = DetailsActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
if (savedInstanceState == null) {
Intent intent = getIntent();
if (intent != null && intent.hasExtra(Constants.EXTRA_NEWS)) {
News news = intent
.getParcelableExtra(Constants.EXTRA_NEWS);
DetailsFragment detailsFragment = DetailsFragment.newInstance(news);
getSupportFragmentManager().beginTransaction()
.add(R.id.details_fragment_container, detailsFragment).commit();
} else {
Log.d(LOG_TAG, "Something went wrong. Intent doesn't have Constants.EXTRA_NEWS" +
" extra. Finishing DetailsActivity.");
finish();
}
}
}
#Override
public void onLoadingDisplay(boolean fromDetails, boolean display) {
Fragment loadingFragment = getSupportFragmentManager()
.findFragmentByTag(LoadingFragment.FRAGMENT_TAG);
if (display && loadingFragment == null) {
loadingFragment = LoadingFragment.newInstance();
if (fromDetails) {
getSupportFragmentManager().beginTransaction()
.add(R.id.details_fragment_container,
loadingFragment, LoadingFragment.FRAGMENT_TAG).commit();
} else {
getSupportFragmentManager().beginTransaction()
.add(R.id.news_fragment_container,
loadingFragment, LoadingFragment.FRAGMENT_TAG).commit();
}
} else if (!display && loadingFragment != null) {
getSupportFragmentManager().beginTransaction()
.remove(loadingFragment).commit();
}
}
}
LoadingFragment.xml
public class LoadingFragment extends Fragment {
public static final String FRAGMENT_TAG = LoadingFragment.class.getSimpleName();
private static final String LOG_TAG = LoadingFragment.class.getSimpleName();
public LoadingFragment() {
// Required empty public constructor
}
public static LoadingFragment newInstance() {
LoadingFragment fragment = new LoadingFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_loading, container, false);
return view;
}
}
fragment_loading.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/semiTransparentBlack"
android:clickable="true"
tools:context=".ui.LoadingFragment">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center" />
</FrameLayout>
Most likely you need to change the loading View (ProgressBar?) visibility to INVISIBLE or GONE at the appropriate time, probably when loading is complete.
If the loading View is contained in some kind of dialog, then you would need to dismiss it at the appropriate time.
use onDestroy
#Override
public void onDestroy() {
super.onDestroy();
mLoadingListener = null;
}
and also you should remove ResponseReceiver
if (mLoadingListener != null) {
mLoadingListener.onLoadingDisplay(true, false);
}
Related
In the below code, I would like to know the difference between instantiating a static fragment as shown in code_1 below.
I posted the code of the fragment as shown in code_2 section below.
please let me know the difference between the two types of instantiaition, and when to use each of them.
code_1:
StudentMVCView mStudentMVCViewInitializedInstance = (StudentMVCView) this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
Fragment mStudentMVCViewFragmentInitializedInstance = this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
code_2:
public class StudentMVCView extends Fragment implements View.OnClickListener{
private final static String TAG_LOG = StudentMVCView.class.getSimpleName();
private View mMainView = null;
private TextView mTextViewValue = null;
private EditText mEditTextValue = null;
private Button mBtn = null;
private TextView mTextViewBtnValue = null;
private StudentMVCModel mStudentMVCModel = null;
private int counter = 1;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG_LOG, "onCreateView");
this.mMainView = inflater.inflate(R.layout.mvc_view_layout, null);
this.mTextViewValue = this.mMainView.findViewById(R.id.mvc_view_textView_value);
this.mEditTextValue = this.mMainView.findViewById(R.id.mvc_view_editText_value);
this.mBtn = this.mMainView.findViewById(R.id.mvc_view_button);
this.mBtn.setOnClickListener(this);
this.mTextViewBtnValue = this.mMainView.findViewById(R.id.mvc_view_textView_btnValue);
return this.mMainView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.v(TAG_LOG, "onViewCreated");
view.findViewById(R.id.mvc_view_textView_value);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v(TAG_LOG, "onActivityCreated");
Bundle bundledArgs = this.getArguments();
StudentMVCModel studentMVCModel = (StudentMVCModel) this.getSerializedfromBundle(bundledArgs, "p");
Log.v(TAG_LOG, "studentMVCModel.getStudentId()" + studentMVCModel.getStudentId());
this.setStudentMVCModelObject(studentMVCModel);
}
private void setStudentMVCModelObject(StudentMVCModel studentMVCModel) {
this.mStudentMVCModel = studentMVCModel;
}
private StudentMVCModel getStudentMVCModelObject() {
return this.mStudentMVCModel;
}
private Bundle getBundledArguments() {
Log.d(TAG_LOG, "getBundledArguments");
if (this.getArguments() !=null) {
return this.getArguments();
} else {
Log.e(TAG_LOG, "this.getArguments() is NULL.");
throw new NullPointerException("getArguments is NULL");
}
}
private Object getSerializedfromBundle(Bundle bundle, String key) {
Log.d(TAG_LOG, "getSerializedfromBundle");
if (bundle != null) {
return bundle.get(key);
} else {
Log.e(TAG_LOG, "bundle is NULL.");
throw new NullPointerException("bundle is null");
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v(TAG_LOG, "onDestroy");
}
public void setStudentIdToView(int id) {
if (this.mMainView != null) {
TextView textView = this.mMainView.findViewById(R.id.mvc_view_textView_value);
Log.v(TAG_LOG, "TextView contains: " + textView.getText().toString());
}
}
public void setTextViewValueFor(int id) {
if (this.mTextViewValue != null) {
this.mTextViewValue.setText("" + id);
} else {
Log.e(TAG_LOG, "setTextViewValueFor is NULL.");
}
}
public void setEditTextValueFor(String str) {
if (this.mEditTextValue != null) {
this.mEditTextValue.setText(str);
} else {
Log.e(TAG_LOG, "mEditTextValue is NULL.");
}
}
public void clearEditText() {
if (this.mEditTextValue != null) {
this.mEditTextValue.setText("");
} else {
Log.e(TAG_LOG, "mEditTextValue is NULL.");
}
}
#Override
public void onClick(View v) {
int id = this.getStudentMVCModelObject().getStudentId();
Log.i(TAG_LOG, "onClick: id: " + id + " counter: " + counter++);
}
}
In the first line You're casting the fragment to StudentMVCView type, so you're able to access extra members added to it like setTextViewValueFor(int id), setEditTextValueFor(String str), ..etc
StudentMVCView mStudentMVCViewInitializedInstance = (StudentMVCView) this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
In the second line you're getting the fragment as it's super type which is the Android framework's Fragment type, in this case you can't access these extra members in StudentMVCView type
Fragment mStudentMVCViewFragmentInitializedInstance = this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
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 am trying to set a string to a textview but everytime i click the button Quiz the activity is just refreshing instead going to fragment activity.
This summarize the situation.
I have dynamic viewPager inside activity called Quiz_Container
Use only one fragment(Module_Topics_Content_Quiz) in public Fragment getItem(int position) or FragmentStatePagerAdapter.
I want to change text of a textview in the fragment from activity everytime i swipe.
I am passing the string using newInstance with parameter from activity to fragment
The string came from quizQuestion.get(position)
I'm getting the right value with the Log.d but when setting it to textview the activity is just refreshing.
this is my code.
Quiz_Container.java
public class Quiz_Container extends AppCompatActivity implements Module_Topics_Content_Quiz.OnFragmentInteractionListener {
android.support.v7.app.ActionBar actionBar;
ViewPager quizPager;
private int topicID;
private int moduleID;
private int subModuleID;
private ArrayList<Integer> quizID;
private ArrayList<String> quizQuestion;
private ArrayList<String> choiceA;
private ArrayList<String> choiceB;
private ArrayList<String> choiceC;
private ArrayList<String> choiceD;
private ArrayList<String> quizAnswer;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz__container);
actionBar = getSupportActionBar();
actionBar.setTitle("Quiz");
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f1ad1e")));
Bundle extras = getIntent().getExtras();
topicID = extras.getInt("topicID");
moduleID = extras.getInt("moduleID");
subModuleID = extras.getInt("subModuleID");
Log.d("quizTopicID", "" + topicID);
Log.d("quizModuleID", "" + moduleID);
Log.d("quizSubModuleID", "" + subModuleID);
new quizTask().execute();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
} // Check Internet Connection
class quizTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
try {
URL quizURL = new URL("http://192.168.1.110/science/index.php/users/get_quiz_items/" + topicID + "/" + moduleID + "/" + subModuleID + "" );
HttpURLConnection con = (HttpURLConnection)quizURL.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String quizResponse;
while ((quizResponse = reader.readLine()) != null) {
return quizResponse;
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#Override
protected void onPostExecute(String quizResponses) {
Log.d("quizResponse", "" + quizResponses);
try {
JSONObject quizObject = new JSONObject(quizResponses);
boolean result = quizObject.getBoolean("success");
if (result) {
JSONArray quizArray = quizObject.getJSONArray("data");
quizID = new ArrayList<>();
quizQuestion = new ArrayList<>();
choiceA = new ArrayList<>();
choiceB = new ArrayList<>();
choiceC = new ArrayList<>();
choiceD = new ArrayList<>();
quizAnswer = new ArrayList<>();
for (int i = 0; i < quizArray.length(); i ++) {
JSONObject dataQuiz = quizArray.getJSONObject(i);
quizID.add(dataQuiz.getInt("id"));
quizQuestion.add(dataQuiz.getString("question"));
choiceA.add(dataQuiz.getString("a"));
choiceB.add(dataQuiz.getString("b"));
choiceC.add(dataQuiz.getString("c"));
choiceD.add(dataQuiz.getString("d"));
quizAnswer.add(dataQuiz.getString("answer"));
}
Log.d("quizSize", "" + quizID.size());
quizPager = (ViewPager) findViewById(R.id.quizPager);
fragmentManager = Quiz_Container.this.getSupportFragmentManager();
quizPager.setAdapter(new quizAdapter(getSupportFragmentManager()));
quizPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
else {
Toast.makeText(getApplication(), "no quiz yet", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} // end of quizTask
class quizAdapter extends FragmentStatePagerAdapter {
public quizAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
for (int i = 0; i < quizID.size; i++) {
if (i == position) {
fragment = Module_Topics_Content_Quiz.newInstance(quizQuestion.get(position));
Log.d("testQuestion", "" + quizQuestion.get(position)); // this code is working
}
}
return fragment;
}
#Override
public int getCount() {
return quizID.size();
}
}
}
Module_Topics_Content_Quiz.java
public class Module_Topics_Content_Quiz extends Fragment {
TextView textQuizQuestion;
private String qQuestion;
public Module_Topics_Content_Quiz() {
// Required empty public constructor
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public static Module_Topics_Content_Quiz newInstance(String question) {
Module_Topics_Content_Quiz fragment = new Module_Topics_Content_Quiz();
Bundle args = new Bundle();
args.putString("question", question);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
qQuestion = getArguments().getString("question");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
textQuizQuestion = (TextView) getActivity().findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
// textQuizQuestion.setText(qQuestion); // error if enable
return rootView;
}
}
Please help. Thank you.
In your fragment, try inflating the TextView using the View returned rather than using getActivity()
You need to inflate the Fragment's view and call findViewById() on the View it returns.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
// inflate the View inside Fragment using the View returned
textQuizQuestion = (TextView) rootView.findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
textQuizQuestion.setText(qQuestion);
return rootView;
}
You can also use getView() from within the Fragment to get the root view.
If you wanna call from the enclosing Activity, use
getFragmentManager().findFragmentById(R.id.your_fragment_id).getView().findViewById(R.id.your_view);
How can I refresh the view of a fragment, when the back button is pressed?
I have tried this in the onResume method of the fragment but it doesn't work.
OK, here is the code
#SuppressWarnings("unused")
public class RestaurantMenuFragment extends Fragment {
private static final String TAG = "MenuItemsFragment";
private static final String CATEGORIES_KEY = "categories";
private static final String SELECTED_CATEGORY_ID_KEY = "category";
private static final String RESTAURANT_KEY = "restaurant123";
private static final String RESTAURANT_KCITY = "city";
private Spinner mCategoriesSpinner;
private ArrayAdapter<CategoriesResponse.Category> mCategoriesAdapter;
private ListView mListView;
private List<MenuItem> mItems;
private MenuItemsAdapter mItemsAdapter;
private EmptyLayout mEmptyLayout;
private Restaurant mRestaurant;
private int mCategoryId;
private List<CategoriesResponse.Category> mCategories;
private RestaurantActivity mActivity;
private MainApplication mApplication;
private CategoriesResponse mCategoriesResponse;
private ActionBar mActionBar;
private Gson mGson;
int categ;
private ObjectGetter mObjectGetter;
public static RestaurantMenuFragment newInstance(Restaurant restaurant) {
RestaurantMenuFragment fragment = new RestaurantMenuFragment();
Bundle args = new Bundle();
args.putString(RESTAURANT_KEY, new Gson().toJson(restaurant));
String dd=restaurant.city;
Log.i("dd12", dd);
fragment.setArguments(args);
return fragment;
}
public RestaurantMenuFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (RestaurantActivity) getActivity();
mApplication = (MainApplication) mActivity.getApplication();
mActionBar = mActivity.getSupportActionBar();
mGson = new Gson();
mObjectGetter = new ObjectGetter();
mCategories = new ArrayList<CategoriesResponse.Category>();
Log.i("mCategories",""+mCategories);
mItems = new ArrayList<MenuItem>();
Log.i("12345",""+mItems);
mItemsAdapter = new MenuItemsAdapter(getActivity(), mItems);
Bundle args = getArguments();
if (args != null) {
mRestaurant = mGson.fromJson(args.getString(RESTAURANT_KEY),
Restaurant.class);
}
if (savedInstanceState != null) {
mRestaurant = mGson.fromJson(
savedInstanceState.getString(RESTAURANT_KEY),
Restaurant.class);
mCategoryId = savedInstanceState.getInt(SELECTED_CATEGORY_ID_KEY);
mCategoriesResponse = mGson.fromJson(
savedInstanceState.getString(CATEGORIES_KEY),
CategoriesResponse.class);
}
assert mRestaurant != null;
updateCart();
}
public void updateCart() {
View view = mActionBar.getCustomView();
Button cartButton = (Button) view.findViewById(R.id.cartButton);
int nOfItems = 0;
if (mApplication.isCartCreated()) {
nOfItems = mApplication.getCart().getNOfAllItems();
}
cartButton.setText(String.format("%d", nOfItems));
if (nOfItems > 0) {
cartButton.setEnabled(true);
} else {
cartButton.setEnabled(false);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Gson gson = new Gson();
outState.putString(RESTAURANT_KEY, gson.toJson(mRestaurant));
outState.putInt(SELECTED_CATEGORY_ID_KEY, mCategoryId);
outState.putString(CATEGORIES_KEY, gson.toJson(mCategoriesResponse));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.spinner_list, container, false);
RestaurantActivity activity = (RestaurantActivity) getActivity();
String myDataFromActivity = activity.getMyData();
String myDataFromActivity1 = activity.getMyData1();
Log.i("myDataFromActivity",myDataFromActivity);
Log.i("myDataFromActivity1",myDataFromActivity1);
categ=Integer.parseInt(myDataFromActivity1);
mListView = (ListView) view.findViewById(R.id.list122334);
mListView.setAdapter(mItemsAdapter);
Log.d(TAG,"Querying items url "
+ Urls.menuItemsQuery(mRestaurant.id,categ));
mEmptyLayout = EmptyLayout.with(getActivity()).to(mListView)
.setEmptyMessage(R.string.categories_empty_message)
.showLoading();
loadItems();
return view;
}
private void loadItems() {
mEmptyLayout.showLoading();
mItems.clear();
mObjectGetter.getJsonObjectOrDialog(mActivity,
Urls.menuItemsQuery(mRestaurant.id, categ),
ItemsResponse.class,
new ObjectGetter.OnFinishedListener<ItemsResponse>() {
#Override
public void onFinishedLoadingObject(
ItemsResponse itemsResponse) {
mEmptyLayout.showEmpty();
if (itemsResponse != null
&& itemsResponse.items != null) {
mItems.addAll(itemsResponse.items);
}
mItemsAdapter.notifyDataSetChanged();
}
});
}
private class MenuItemsAdapter extends ArrayAdapter<MenuItem> {
private static final String TAG = "MenuItemsAdapter";
public MenuItemsAdapter(Context context, List<MenuItem> menuItems) {
super(context, 0, menuItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final MenuItem menuItem = getItem(position);
View view = convertView;
final ViewHolder viewHolder;
LayoutInflater inflater;
if (convertView == null) {
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.menu_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) view.findViewById(R.id.name);
viewHolder.description = (TextView) view.findViewById(R.id.description);
viewHolder.price = (TextView) view.findViewById(R.id.price);
viewHolder.add = (Button) view.findViewById(R.id.add);
viewHolder.selectedView = view.findViewById(R.id.selectedView);
viewHolder.remove = (Button) view.findViewById(R.id.remove);
viewHolder.total = (TextView) view.findViewById(R.id.itemTotal);
viewHolder.quantity = (TextView) view.findViewById(R.id.quantity);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try
{
viewHolder.name.setText(menuItem.name);
viewHolder.description.setText(menuItem.description);
viewHolder.price.setText(String.valueOf(menuItem.price));
}catch(NullPointerException e){
e.printStackTrace();
}
viewHolder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mApplication.createNewCartIfPossibleAndAskIfNot(
getActivity(), mRestaurant,
new MainApplication.OnCreateCartListener() {
#Override
public void onCreateCart(Cart cart) {
cart.addOne(menuItem);
updateItemFromCart(menuItem, viewHolder);
updateCart();
}
});
}
});
viewHolder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mApplication.isCartCreated()) {
return;
}
mApplication.getCart().removeOne(menuItem);
updateItemFromCart(menuItem, viewHolder);
updateCart();
}
});
return view;
}
private void updateItemFromCart(MenuItem menuItem, ViewHolder viewHolder) {
if (!mApplication.isCartCreated()) {
return;
}
int quantity = mApplication.getCart().getNOfItemsOfType(menuItem);
if (quantity > 0) {
viewHolder.selectedView.setVisibility(View.VISIBLE);
} else {
viewHolder.selectedView.setVisibility(View.GONE);
}
viewHolder.quantity.setText(String.valueOf(quantity));
viewHolder.total.setText(String.valueOf(quantity
* menuItem.price));
}
class ViewHolder {
TextView name;
TextView description;
TextView price;
Button add;
View selectedView;
Button remove;
TextView total;
TextView quantity;
}
}
#Override
public void onResume() {
super.onResume();
updateCart();
mItems.clear();
if (mItemsAdapter != null) {
mItemsAdapter.notifyDataSetChanged();
}
}
#Override
public void onDestroy() {
if (mObjectGetter != null) {
mObjectGetter.stopRequests();
}
super.onDestroy();
}
}
Now, i want to update the listvieww data when the user pressed the back button. I set the new loadItems() method in the onResume() Method of the Fragment. This Method is called but the old listview data appears and new data also appears...
Back button should be handled from Activity.
You can override onBackPressed in Activity and call a function on corresponding fragment to reloadItems().
Here are your 3 options I could think of.
Get reference to Fragment and call function to reLoadItems and its better to define an interface for this communication which fragment implements.
Better solution than first one. Add a LocalBroadcast which Activity broadcasts and your fragment listens and updates data on receiving broadcast.
Example for this :
http://luboganev.github.io/blog/messaging-with-localbroadcastmanager/
Otto event bus where both activity and fragment classes are connected to the event bus and they activity publishes event and fragment subscribes to it. This is what I am using for something similar in my application. (But I have pretty frequent asynchronous events that come along. SO I am using this. 2nd option might be sufficient in your case).
Example for this :
http://www.vogella.com/tutorials/JavaLibrary-EventBusOtto/article.html
As ramesh already mentioned, back button handling happens in your activity class that holds the fragments. Here is a simple example, how you can handle these back button events for your fragment.
Activity Code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean returnSuperKeyDown = true;
if(keyCode == KeyEvent.KEYCODE_BACK){
Fragment fragment = getYourCurrentFragment();
if (fragment instanceof YourFragment) {
returnSuperKeyDown = ((YourFragment) fragment).onFragmentKeyDown();
}
}
if (returnSuperKeyDown) {
return super.onKeyDown(keyCode, event);
} else {
return true;
}
}
YourFragment Method:
public boolean onFragmentKeyDown() {
updateYourFragment();
return false;
}
#Rithe, #sunder sharma
As per me there is simple to refresh the fragment when come back from other fragment,
We just have to override the onActivityCreated Method for refresh fragment.
Like as
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//your code which you want to refresh
loadItems();
}
You can also update/refresh the fragment using onStart() method.
public void onStart(){
super.onStart();
//update your fragment
}
This worked fine for me.
call your loadItem() method onHiddenChanged(boolean hidden)method.onHiddenChanged is overrided method
I'm trying to create a fragment that, when shown, changes it's content based on an extra item I pass on the show() method. The dialog fragment instance is kept for reusability, in other words, I just instantiate the fragment once and call show() with the new object it displays whenever I want it to be displayed. It works fine for the first time it is shown, but for subsequent calls to show, I just can't change the text of the edit texts. You'll see in my class below that I've actually explicitly made the text to be changed to "I was changed" after the show() code block, but this never reflects in the ui.
public class RegisterFragment extends DialogFragment implements View.OnClickListener, DialogInterface.OnClickListener
{
private static final String KEY_SOURCE = "source";
private static String source;
private static JSONObject listEntry;
private RegisterItem item;
private boolean spinnerMode;
private boolean viewsCreated;
private TextView label1, label2;
private EditText field1 = null, field2 = null;
private Spinner spinner;
private ArrayAdapter<String> adapter;
private Button send, cancel;
private OnClickSendCancelButtonListener sendListener;
public static RegisterFragment newInstance(String source)
{
RegisterFragment fragment = new RegisterFragment();
Bundle b = new Bundle();
b.putString(KEY_SOURCE, source);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = this.getArguments();
if (b != null)
{
source = b.getString(KEY_SOURCE);
load(source);
}
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
viewsCreated = false;
}
public RegisterItem getRegisterItem()
{
return this.item;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
this.sendListener = (OnClickSendCancelButtonListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException("Activity must implement RegisterFragment#OnClickSendCancelButtonListener");
}
}
private void load(String source)
{
if (item == null)
item = new RegisterItem();
item.loadData(source);
spinnerMode = item.hasChoices();
if (!viewsCreated)
return;
label1.setText(item.field1Label);
label2.setText(item.field2Label);
send.setText(item.sendButtonText);
cancel.setText(item.cancelButtonText);
Log.v("RegisterFragment", "FIELD1: " + item.defaultField1);
Log.v("RegisterFragment", "FIELD2: " + item.defaultField2);
if (spinnerMode)
{
field1.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
adapter.clear();
for(String choice: item.choices)
adapter.add(choice);
adapter.notifyDataSetChanged();
}
else
{
field1.setVisibility(View.VISIBLE);
spinner.setVisibility(View.GONE);
}
if (item.hasDefaults())
{
Log.v("RegisterFragment", "Setting text for field 2");
field2.setText(item.defaultField2);
Log.v("RegisterFragment", "FIELD2 TEXT: " + field2.getText().toString());
if (spinnerMode)
spinner.setSelection(adapter.getPosition(item.defaultField2));
else
field1.setText(item.defaultField1);
}
}
public void show(FragmentManager manager, String tag, String source, String listEntry)
{
Log.v("Register Fragment", "Showing fragment\nSOURCE STRING: " + source);
load(source);
RegisterFragment.source = source;
try {
RegisterFragment.listEntry = new JSONObject(listEntry);
} catch (JSONException e) {
e.printStackTrace();
}
super.show(manager, tag);
if (field2 != null)
field2.setText("I Have Been Changed");
}
#Override
public void dismiss()
{
if (field1 != null)
field1.setText("");
if (field2 != null)
field2.setText("");
super.dismiss();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.register_screen, null);
spinner = (Spinner) v.findViewById(R.id.register_spinner);
spinner.setAdapter(adapter);
label1 = (TextView) v.findViewById(R.id.register_label1);
label2 = (TextView) v.findViewById(R.id.register_label2);
field1 = (EditText) v.findViewById(R.id.register_field1);
field2 = (EditText) v.findViewById(R.id.register_field2);
send = (Button) v.findViewById(R.id.register_send);
cancel = (Button) v.findViewById(R.id.register_cancel);
send.setOnClickListener(this);
cancel.setOnClickListener(this);
viewsCreated = true;
load(source);
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
viewsCreated = false;
}
}
Your code should have worked . But do try this.
EditText text = (EditText)getDialog().findViewById(R.id.register_field2);
text.setText("I have been changed");