I have a fragment that loads data everytime you click on it, I want its behavior to be in a way that if I clicked on it once and moved to another fragment when I go back to it, it does not reload the data and it does not show the "Loading spinner" anymore. How do I do that? This is my fragment code:
public ConsultantFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);//Make sure you have this line of code.
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View consultantView = inflater.inflate(R.layout.fragment_consultant, container, false);
//consultantList = new ArrayList<>();
//consultantLisView = (ListView) consultantView.findViewById(R.id.consultant_listview);
swipeRefreshLayout = (SwipeRefreshLayout) consultantView.findViewById(R.id.consultant_list_swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
retrieveConsultantList();
consultantRecyclerView.setAdapter(consultantRecylerViewAdapter);
}
});
consultantRecyclerView = (RecyclerView) consultantView.findViewById(R.id.consultant_recyclerview);
setUpDialog();
FloatingActionButton createConsultantFab = (FloatingActionButton) consultantView.findViewById(R.id.add_consultant);
createConsultantFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent createConsultantIntent = new Intent(getContext(), CreateConsultantActivity.class);
startActivity(createConsultantIntent);
}
});
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.consultant_list_title);
retrieveConsultantList();
return consultantView;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
searchMenuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
/// searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
consultantRecylerViewAdapter.getFilter().filter(newText);
consultantRecylerViewAdapter.notifyDataSetChanged();
return false;
}
private void setUpConsultantRecyclerView(List<Consultant> consultantList) {
consultantRecylerViewAdapter = new ConsultantRecylerViewAdapter(getContext(), consultantList);
consultantRecyclerView.setAdapter(consultantRecylerViewAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
consultantRecyclerView.setLayoutManager(linearLayoutManager);
consultantRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
public void setUpDialog() {
consultantListLoadingDialog = ProgressDialog.show(getContext(),
"Loading consultant",
"Please wait");
}
private void retrieveConsultantList() {
final StringRequest consultantStringRequest = new StringRequest(Request.Method.GET,
Constants.BASE_URL.concat(Constants.CONSULTANT_KEY_WORD),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//eventList = new ArrayList<>();
JsonDataParser parseJSON = new JsonDataParser();
setUpConsultantRecyclerView(parseJSON.jsonArrayToConsultantList(response));
consultantListLoadingDialog.dismiss();
//consultantListAdapter.addAll();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleyRequestQueue.getInstance(getContext()).addToRequestQueue(consultantStringRequest);
}
}
Remove your method which is getting results from the server from onCreateView. onCreateView called all time when you replace fragments. Instead do one time work in onCreate.
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
retrieveConsultantList();
}
Related
I've implemented a bottom navigation in my application and it's working fine, but today I've tried to press the back button of the phone when I'm inside some activity, while doing so, I've noticed that it pretty much takes me out of the app , is there a way to solve this? for example instead of it taking me to the outside of app i want it to take me to home activity, is there some method i'm supposed to be using to handle these changes? if so please let me know, my code for the bottom navigation in the(for example exercice acitvity since i use the bottom navigation in 3 different activities)is :
public class Exercice extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Deal> list;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercice);
ref = FirebaseDatabase.getInstance().getReference().child("medicines");
recyclerView = findViewById(R.id.rv);
searchView = findViewById(R.id.searchview);
/* RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
*/
//initialize and assign variables
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//set home selected
bottomNavigationView.setSelectedItemId(R.id.exercice);
//preform itemsselectedlistener
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.exercice:
finish();
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext()
, MainActivity.class));
overridePendingTransition(0, 0);
finish();
return true;
case R.id.home:
startActivity(new Intent(getApplicationContext()
, Home.class));
overridePendingTransition(0, 0);
finish();
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
if(ref != null){
ref.addValueEventListener(new ValueEventListener() {
#NonNull
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
list = new ArrayList<>();
for(DataSnapshot ds : snapshot.getChildren()){
list.add(ds.getValue(Deal.class));
}
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Exercice.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if (searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str) {
if (!str.equals("")){
ArrayList<Deal> myList = new ArrayList<>();
for (Deal object : list){
if(object.getDisease().toLowerCase().contains(str.toLowerCase())){
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(myList);
recyclerView.setAdapter(adapterClass);
}
}
}
I am a begineer in Android programming. I am getting trouble with this problem from 3 days. Any suggestion plz.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener,
View.OnLongClickListener, BeneficiaryRecyclerAdapter.ListItemClickListener {
private AppCompatActivity activity = MainActivity.this;
public boolean is_in_action_mode = false;
private RecyclerView recyclerViewBeneficiary;
private Beneficiary beneficiary;
private ArrayList<Beneficiary> listBeneficiary;
ArrayList<Beneficiary> selection_list = new ArrayList<>();
private BeneficiaryRecyclerAdapter beneficiaryRecyclerAdapter;
private DatabaseHelper databaseHelper;
Toolbar toolbar;
TextView counter_text_view;
int counter = 0, id;
private SQLiteDatabase mDb;
private final static String TAG = "check";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//toolbar.inflateMenu(R.menu.menu_activity_main);
counter_text_view = (TextView) findViewById(R.id.counter_text);
counter_text_view.setText(getString(R.string.app_name));
recyclerViewBeneficiary = (RecyclerView) findViewById(R.id.listRecyclerView);
initObjects();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.addAccountFab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
AccountDetailActivity.class);
startActivity(intent);
}
});
}
private void initObjects() {
listBeneficiary = new ArrayList<>();
beneficiaryRecyclerAdapter = new BeneficiaryRecyclerAdapter(listBeneficiary, MainActivity.this,MainActivity.this);
Log.d(TAG,"listBeneficiary size[initObject()] = "+ listBeneficiary.size());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewBeneficiary.setLayoutManager(mLayoutManager);
recyclerViewBeneficiary.setItemAnimator(new DefaultItemAnimator());
//recyclerViewBeneficiary.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); // For Vertical line separation
recyclerViewBeneficiary.setHasFixedSize(true);
recyclerViewBeneficiary.setAdapter(beneficiaryRecyclerAdapter);
databaseHelper = new DatabaseHelper(activity);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listBeneficiary.clear();
listBeneficiary.addAll(databaseHelper. getAllBeneficiary());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
ArrayList<Beneficiary> newList = new ArrayList<>();
Log.d(TAG,"listBeneficiary size[onQuery] = "+ listBeneficiary.size());
for (Beneficiary beneficiary: listBeneficiary) {
String name = beneficiary.getTitle().toLowerCase();
if (name.contains(newText))
newList.add(beneficiary);
}
beneficiaryRecyclerAdapter.setFilter(newList);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main,menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search by title");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
#Override
public boolean onLongClick(View v) {
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.menu_action_mode);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorActionMode));
counter_text_view.setVisibility(View.VISIBLE);
counter_text_view.setText("0 items selected");
is_in_action_mode = true;
beneficiaryRecyclerAdapter.notifyDataSetChanged();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
return true;
}
public void clearActionMode(){
is_in_action_mode = false;
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.menu_activity_main);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
getSupportActionBar().setDisplayHomeAsUpEnabled(false); // old = true
counter_text_view.setText(getString(R.string.app_name)); // New,good
counter = 0;
selection_list.clear();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.item_delete){
for (Beneficiary contact : selection_list) { //New
listBeneficiary.remove(contact); //New
databaseHelper.deleteSelectedItems(contact.getId());
}
beneficiaryRecyclerAdapter.notifyDataSetChanged(); //new
clearActionMode()
}
else if(item.getItemId()== android.R.id.home){
clearActionMode();
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
return true;
}
Intent intent = new Intent(this, AccountDetailActivity.class);
Uri currentUri =
ContentUris.withAppendedId(BeneficiaryEntry.CONTENT_URI, id);
intent.setData(currentUri);
startActivity(intent);
}
}
Inside BeneficiaryRecyclerAdapter
public void setFilter(ArrayList<Beneficiary> newList) {
listBeneficiary = new ArrayList<>();
listBeneficiary.addAll(newList);
notifyDataSetChanged();
}
At first the searchView works great many times but after I delete some row it doesn't respond. I have checked using Log.d, the problem is onQueryTextChange(String newText) is not getting any value but works after the mainActivity is resumed. So please let find my mistake.
Try to add
MenuItem menuItem = toolbar.getMenu().findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search by title");
searchView.setOnQueryTextListener(this);
to clearActionMode().
I am trying to implement tab functionality in an Android browser. I tried to save the webpage in a cache, but I can't figure out how to save multiple of them and load them when the user switches tabs. How could I implement this?
I would like to save the current webpage in a cache when the user wants to add a new tab and open Main_activity, and then next time when the user switches tabs, the current webpage should get saved in a cache, and the intended webpage of the intended tab gets loaded in the webview. Now the issue is, I don't know how to handle multiple webpages in a cache, and select which one to load when.
My code consists of two activities, main_activity with some icons and webView_activity with a simple webview. I am using a custom dialog box with a ListView in it, so I will need to add new rows for new tabs and edit them when tabs are switched.
Here is my main_activity
public class MainActivity extends AppCompatActivity {
ImageView yt,google,gm,twitter;
SearchView g_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
g_search = (SearchView) findViewById(R.id.g_search);
g_search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
yt = (ImageView) findViewById(R.id.yt);
google = (ImageView) findViewById(R.id.google);
gm = (ImageView) findViewById(R.id.gm);
twitter = (ImageView) findViewById(R.id.twitter);
yt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.youtube.com");
startActivity(i);
}
});
google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.google.com");
startActivity(i);
}
});
gm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.gmail.com");
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.twitter.com");
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m1, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_new_tab){
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(MainActivity.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Here is my web_view activity
public class webview1 extends AppCompatActivity {
CustomWebView web1;
String search_q,shortcut;
FloatingActionButton fab;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview1);
web1 = (CustomWebView) findViewById(R.id.web1);
web1.setGestureDetector(new GestureDetector(new CustomGestureDetector()));
web1.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(final WebView view, int errorCode, String description,
final String failingUrl) {
fragmentManager.beginTransaction()
.replace(R.id.container, new blankState())
.commit();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
registerForContextMenu(web1);
// web1.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setBuiltInZoomControls(true);
web1.getSettings().setDisplayZoomControls(false);
web1.getSettings().setLoadWithOverviewMode(true);
web1.getSettings().setUseWideViewPort(true);
search_q=getIntent().getStringExtra("query");
shortcut=getIntent().getStringExtra("shortcut");
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_toolbar);
ImageView action_back = (ImageView) findViewById(R.id.action_back);
action_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setVisibility(GONE);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code for launching new tab here
}
});
web1.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress ){
frame_layout.setVisibility(View.VISIBLE);
progress_bar.setProgress(progress);
if(progress==100){
frame_layout.setVisibility(GONE);
srl.setRefreshing(false);
}
super.onProgressChanged(view, progress);
}
});
progress_bar.setProgress(0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_url){
ShowUrlDialog();
return true;
}
if(item.getItemId()==R.id.action_home){
Intent i = new Intent(webview1.this,MainActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_new_tab){
// code to launch new tab here
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(webview1.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(webview1.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m2, menu);
// Associate searchable configuration with the SearchView
return true;
}
#Override
public void onBackPressed() {
if (web1.canGoBack()) {
web1.goBack();
} else {
super.onBackPressed();
}
}
}
I was converting my UserListing Activity to a fragment when i received this error in myOnCreateOptionsMenu.
This is my Fragment Activity.
public class UserListingActivity extends Fragment implements LogoutContract.View {
private Toolbar mToolbar;
private TabLayout mTabLayoutUserListing;
private ViewPager mViewPagerUserListing;
private LogoutPresenter mLogoutPresenter;
public static void startActivity(Context context) {
Intent intent = new Intent(context, UserListingActivity.class);
context.startActivity(intent);
}
public static void startActivity(Context context, int flags) {
Intent intent = new Intent(context, UserListingActivity.class);
intent.setFlags(flags);
context.startActivity(intent);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
bindViews();
init();
setHasOptionsMenu(true);
return super.onCreateView(inflater, container, savedInstanceState);
}
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_user_listing);
// bindViews();
// init();
// }
private void bindViews() {
mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
mTabLayoutUserListing = (TabLayout) getActivity().findViewById(R.id.tab_layout_user_listing);
mViewPagerUserListing = (ViewPager) getActivity().findViewById(R.id.view_pager_user_listing);
}
private void init() {
// set the toolbar
setSupportActionBar(mToolbar);
// set the view pager adapter
UserListingPagerAdapter userListingPagerAdapter = new UserListingPagerAdapter(getFragmentManager());
mViewPagerUserListing.setAdapter(userListingPagerAdapter);
// attach tab layout with view pager
mTabLayoutUserListing.setupWithViewPager(mViewPagerUserListing);
mLogoutPresenter = new LogoutPresenter(this);
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getActivity().getMenuInflater().inflate(R.menu.menu_user_listing, menu);
// return super.onCreateOptionsMenu(menu);
// }
#Override
public boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.menu_user_listing, menu);
return super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
logout();
break;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
new AlertDialog.Builder(this)
.setTitle(R.string.logout)
.setMessage(R.string.are_you_sure)
.setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mLogoutPresenter.logout();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
#Override
public void onLogoutSuccess(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
LoginActivity.startIntent(this,
Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
}
#Override
public void onLogoutFailure(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(this, MainActivity.class));
}
}
What has to be changed to solve this and what more has to be changed to covert it into a Fragment. I am beginner so detailed help would be appreciated.
Thanks
Method signature in fragment should be as below
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
The problem is with the return type of the method, make it void and error will be gone as the super-type returns void.
hi friends i am trying to pass array data from activity to the tab fragment but its gives me the null pointer exception i am using the json to store data into getter and setter method and trying to pass that list into the frgament method
Display.class
public static void toast(Context context, String display) { Toast.makeText(context, display, Toast.LENGTH_LONG).show(); }
MyError
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
Here is my main activity
public class HotelDetails extends AppCompatActivity {
#BindView(R.id.hoteldetailedtoolbar)
Toolbar hoteldetailedtoolbar;
#BindView(R.id.hotelamentiestab)
TabLayout hotelamentiestab;
#BindView(R.id.hotelpager)
ViewPager hotelpager;
ArrayList<Hotel_image> hotelimg = new ArrayList<Hotel_image>();
#BindView(R.id.hotelname)
TextView hotelname;
#BindView(R.id.hotelprice)
TextView hotelprice;
#BindView(R.id.roomtype)
TextView roomtype;
#BindView(R.id.whatsmakes)
TextView whatsmakes;
#BindView(R.id.needtoknow)
TextView needtoknow;
HotelImages hoteladapter;
#BindView(R.id.indicator)
InkPageIndicator indicator;
#BindView(R.id.bannerpager)
ViewPager bannerpager;
#BindView(R.id.roomtypes)
Spinner roomtypes;
List<Hotel_TabBeans> listhotelbeans=new ArrayList<Hotel_TabBeans>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotel_detail);
ButterKnife.bind(this);
setSupportActionBar(hoteldetailedtoolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
hoteldetailedmethod();
setupviewpager(hotelpager);
hotelpager.setOffscreenPageLimit(1);
hotelamentiestab.setupWithViewPager(hotelpager);
hoteladapter = new HotelImages(getApplicationContext(), hotelimg);
bannerpager.setAdapter(hoteladapter);
ArrayList<String> roomlist = new ArrayList<>();
roomlist.add("Rooms Types");
roomlist.add("Standard");
roomlist.add("Deluxe");
roomlist.add("Luxury");
ArrayAdapter<String> roomadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_detailed, R.id.spinnertext, roomlist);
roomadapter.setDropDownViewResource(R.layout.spinner_dropdown);
roomtypes.setAdapter(roomadapter);
}
#OnClick(R.id.spinnerbutton)
public void spinnerbuttonclick() {
roomtypes.performClick();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.hoteldetailed_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.call:
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
return true;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "CYStay");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Here live url will come");
startActivity(Intent.createChooser(shareIntent,
"Share The Post"));
return true;
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupviewpager(ViewPager pager) {
TabsFragments tabsFragments = new TabsFragments(getSupportFragmentManager());
tabsFragments.addfragment(new Hotel_tab(), "Hotel");
tabsFragments.addfragment(new Hotel_tab(), "Room");
pager.setAdapter(tabsFragments);
}
private void hoteldetailedmethod() {
Display.showLoadingDialog(HotelDetails.this, "Loading...");
final String hoteldetaildurl = Jsonurl.url + "hotel_details.php?rid=" + getIntent().getStringExtra("Roomid");
Display.log(hoteldetaildurl);
JsonObjectRequest hoteldetailedreq = new JsonObjectRequest(Request.Method.GET, hoteldetaildurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hotelimagesarray = response.getJSONArray("hotel_images");
for (int i = 0; i < hotelimagesarray.length(); i++) {
JSONObject hotelimagearrayobj = hotelimagesarray.getJSONObject(i);
Hotel_image hotelimage = new Hotel_image();
hotelimage.setHotelimages(hotelimagearrayobj.getString("image"));
hotelimg.add(hotelimage);
}
int number = bannerpager.getChildCount();
if (number != -1) {
indicator.setViewPager(bannerpager);
}
JSONObject hoteldtails = response.getJSONObject("hotel_details");
getSupportActionBar().setTitle(hoteldtails.getString("hotel_name"));
hotelname.setText(hoteldtails.getString("hotel_name"));
hotelprice.setText(hoteldtails.getString("room_price"));
roomtype.setText(hoteldtails.getString("room_name"));
whatsmakes.setText(hoteldtails.getString("what_makes_special"));
needtoknow.setText(hoteldtails.getString("need_to_know"));
JSONArray ammarray=hoteldtails.getJSONArray("amenities");
for (int i = 0; i <ammarray.length() ; i++) {
JSONObject arrayobj=ammarray.getJSONObject(i);
Hotel_TabBeans tabeans=new Hotel_TabBeans();
tabeans.setAmenitimage(arrayobj.getString("img"));
tabeans.setAmenitiname(arrayobj.getString("name"));
listhotelbeans.add(tabeans);
Hotel_tab hotelTab=new Hotel_tab();
hotelTab.hoteltablist(listhotelbeans);
}
// hoteldatas.hoteldatamethod(listhotelbeans);
// Bundle listbundle=new Bundle();
// listbundle.putStringArrayList("hotelist",listhotelbeans);
// listbundle.putSerializable("hoye", (Serializable) listhotelbeans);
// Hotel_tab hoteltab=new Hotel_tab();
// hoteltab.setArguments(listbundle);
} catch (JSONException e) {
e.printStackTrace();
}
hoteladapter.notifyDataSetChanged();
Display.hideLoadingDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Display.log(error.toString());
Display.hideLoadingDialog();
}
});
hoteldetailedreq.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(hoteldetailedreq);
}
}
Here is my fragment activity:
public class Hotel_tab extends Fragment {
public Hotel_tab() {
}
#BindView(R.id.hotel_tab_list)
RecyclerView hotel_tab_list;
Hotel_Tab_Layout hotel_tab_layout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.hotel_tab,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this,view);
LinearLayoutManager hotelmanager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
hotel_tab_list.setLayoutManager(hotelmanager);
}
public void hoteltablist(List<Hotel_TabBeans> msg){
Display.toast(getActivity(),msg);//here is the null pointer exeception i am getting
}
}
The problem is clear:
You would like to get the Context without attaching a Fragment to the activity.
Inside parsing a successful response from a server, you code look like:
Hotel_tab hotelTab=new Hotel_tab();
hotelTab.hoteltablist(listhotelbeans);
That means, that you're creating a new Fragment and invoke a method getActivity() on a fragment that is not attached to it.
You have 3 choices:
If you just want to show toast, show it inside Activity, not inside Fragment.
If you really need to do this inside Framgent, attach it first to the activity with FragmentManager
Or pass Context as one of Fragment's function hoteltablist(...) parameters, if you want to show toast inside fragment.