Reloading RecyclerView doesn’t update items - java

I am using the following code:
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
The activity contains a recycler view, I want the activity to reload when I click on refresh but the Recyclerview doesn't fill again, it has the same information than before reloading. If I go to another activity and come back to this one, then it does change.
What I am doing wrong?
Here is the complete activity code:
public class SyncActivity extends Activity {
private static String TAG = "SynActivity";
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private TextView textView;
private ImageView backArrow;
private ImageView refresh;
// Sesión actual
private Usuario usuario;
private String sessionid;
List<TrafficSign> tsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync);
tsList = new ArrayList<TrafficSign>();
// Sesión actual
sessionid = getIntent().getExtras().getString("sessionid");
usuario = (Usuario) getIntent().getExtras().get("usuario");
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
textView = (TextView) findViewById(R.id.texto);
backArrow = (ImageView) findViewById(R.id.backarrow);
refresh = (ImageView) findViewById(R.id.refresh);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// specify an adapter with the list to show
ConexionSQLiteHelper conexionSQLiteHelper = new ConexionSQLiteHelper(this, NOMBRE_BD, null, 1);
SQLiteDatabase dbread = conexionSQLiteHelper.getReadableDatabase();
Cursor c = dbread.rawQuery(COMRPUEBA_SYNC, new String[]{usuario.getUsername()});
// Si hay conexión a internet y hay datos en SQLite, sincronizamos.
if (c.getCount() > 0) {
textView.setVisibility(View.INVISIBLE);
if (c.moveToFirst()) {
while (!c.isAfterLast()) {
tsList.add(new TrafficSign(c.getDouble(c.getColumnIndex(CAMPO_LONGITUD)),
c.getDouble(c.getColumnIndex(CAMPO_LATITUD)),
c.getDouble(c.getColumnIndex(CAMPO_ANCHO)),
c.getDouble(c.getColumnIndex(CAMPO_ALTO)),
c.getString(c.getColumnIndex(CAMPO_CLASE)),
c.getString(c.getColumnIndex(CAMPO_USERNAME))));
c.moveToNext();
}
}
c.close();
dbread.close();
mAdapter = new SyncAdapter(tsList);
mRecyclerView.setAdapter(mAdapter);
}else{
textView.setVisibility(View.VISIBLE);
}
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncActivity.this, MainActivity.class);
intent.putExtra("sessionid", sessionid);
intent.putExtra("usuario", usuario);
startActivity(intent);
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
}
}

You can Simply use
finish();
startActivity(getIntent());
to refresh an Activity from within itself.

Related

getting error when i try to use switch button is differen class

So I defined a switch button in ProfileSettingsfragment but i am using that button in Explanation.class. What I am really trying to do is when switch button is checked i want start service else i don't want to star service from Explanation.class
SO I tried Some code and it showing me this error " java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.appcompat.widget.SwitchCompat.isChecked()' on a null object reference
at com.harsh.preacher.ui.Home.Explaination$1.onClick(Explaination.java:43)"
P.S I have designed switch button in ProfileSettingsfragment.xml
Here is ProfileSettingsfragment class code
public class ProfileSettingsFragment extends Fragment {
private GoogleSignInClient mGoogleSignInClient;
public SwitchCompat notePopUp;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_profilesettings, container, false);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(requireContext(), gso);
final ProfileSettingsFragment profileSettingsFragment =new ProfileSettingsFragment();
Button signOut1 = root.findViewById(R.id.signOut);
signOut1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO Custom Alert Dialog Bar
// signOut();
Intent intent = new Intent(getContext(), AndarAwoo.class);
startActivity(intent);
// Animation(signOut1);
}
});
notePopUp = (SwitchCompat) root.findViewById(R.id.notePopUp);
RelativeLayout EditName = root.findViewById(R.id.EditName);
RelativeLayout ProfileSettingsLayout= root.findViewById(R.id.profileSettingsCardView);
TextView EditNameText = root.findViewById(R.id.EditNameText);
EditNameText.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
if(EditName.getVisibility() == View.GONE){
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.VISIBLE);
}else {
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.GONE);
}
}
});
return root;
}
Here is my explanation class code
public class Explaination extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explaination);
Intent intent = getIntent();
String about = intent.getStringExtra("about");
TextView about1 = findViewById(R.id.about);
about1.setText(about);
Button resource = findViewById(R.id.Resource);
resource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
String url = intent.getStringExtra("button");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
ProfileSettingsFragment checkNotePopUp = new ProfileSettingsFragment();
checkNotePopUp.notePopUp = findViewById(R.id.notePopUp);
if(checkNotePopUp.notePopUp.isChecked()){
startService(new Intent(Explaination.this, NotePopUpHead.class));
}
else{
stopService(new Intent(Explaination.this,NotePopUpHead.class));
}
finish();
startActivity(i);
}
});
}
}

How to add AdMob Banner AD in RecyclarView after 5 or 10 CardView using FirebaseRecyclerAdapter

I am working on an android app where I am showing some text coming through the firebase database, now I want to show AdMob Banner AD after 5 CardView in the RecyclarView but I am not understand how to do that because I am beginner in Java and Android Programming language. Can anyone help me to do this implementation.
MY JAVA CODE
POJO CLASS
private String shaData;
public Model(){
}
public Model(String sha) {
this.shaData = sha;
}
public String getShaData() {
return shaData;
}
public void setShaData(String shaData) {
this.shaData = shaData;
}
}
MY VIEW HOLDER CLASS
public class Holder extends RecyclerView.ViewHolder{
public TextView txtShayari;
public Button copyButton, shareButton, whatsappButton;
public Holder(#NonNull View itemView) {
super(itemView);
txtShayari = (TextView)itemView.findViewById(R.id.textView);
copyButton = (Button) itemView.findViewById(R.id.copyBtn);
shareButton = (Button) itemView.findViewById(R.id.shBtn);
whatsappButton = (Button) itemView.findViewById(R.id.waBtn);
}
}
MY MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ProgressBar progressBar;
ImageView imageView;
FirebaseRecyclerAdapter<Model, Holder> recyclerAdapter;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("MyQuotes");
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
progressBar = findViewById(R.id.progress);
loadData();
}
private void loadData()
{
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(databaseReference,Model.class)
.build();
recyclerAdapter = new FirebaseRecyclerAdapter<Model, Holder>(options) {
int AD_TYPE = 0;
int CONTENT_TYPE = 1;
#Override
protected void onBindViewHolder(#NonNull final Holder holder, int position, #NonNull final Model model) {
holder.txtShayari.setText(model.getShaData());
progressBar.setVisibility(View.GONE);
holder.copyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager)holder.itemView.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(Intent.EXTRA_TEXT, model.getShaData());
clipboard.setPrimaryClip(clip);
Toast.makeText(holder.itemView.getContext(), "Shayari Copied", Toast.LENGTH_SHORT).show();
}
});
holder.whatsappButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, model.getShaData());
try {
holder.itemView.getContext().startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(holder.itemView.getContext(), "Whatsapp have not been installed", Toast.LENGTH_SHORT).show();
}
}
});
holder.shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent .setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, model.getShaData());
intent.setType("text/plain");
intent = Intent.createChooser(intent, "Share With");
holder.itemView.getContext().startActivity(intent);
}
});
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_view,viewGroup,false);
return new Holder(view);
}
};
recyclerAdapter.notifyDataSetChanged();
recyclerAdapter.startListening();
recyclerView.setAdapter(recyclerAdapter);
}
}
This is my whole code too fetch text data from the Firebase server and it is working very well, Simply now I am want too show AdMob banner ads after 5 cardviews on the recyclarview, So please anyone guide me.

How can I stop the 'jumping effect' when opening an activity?

I have more than three activities and these other activities transition so well but one activity which I have included the code for below appear to be jumping every time I navigate to it.
I have overridden the animation class but the jump still persists.How can I go about it? Is my Ui thread overloaded?
public class ListActivity extends AppCompatActivity implements
RecyclerViewAdapter.OnItemClickListener {
RecyclerViewAdapter recyclerViewAdapter;
RecyclerView recyclerView;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference dbRef = db.collection("Archives");
Context context;
FloatingActionButton fab;
Item clickedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
recyclerView = findViewById(R.id.recyclerView);
fab = findViewById(R.id.fab);
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ListActivity.this,
EnterDataActivity.class);
startActivity(intent);
}
});
setUpAdapter();
}
private void setUpAdapter() {
Query query = dbRef.orderBy("fname", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Item> options = new
FirestoreRecyclerOptions.Builder<Item>()
.setQuery(query, Item.class)
.build();
recyclerViewAdapter = new RecyclerViewAdapter(options,
ListActivity.this);
recyclerViewAdapter.notifyDataSetChanged();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.setOnItemClickListener(ListActivity.this);
}
#Override
public void onStart() {
super.onStart();
recyclerViewAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
recyclerViewAdapter.stopListening();
}
#Override public void onItemClick(DocumentSnapshot documentSnapshot, int
position) {
clickedItem = documentSnapshot.toObject(Item.class);
clickedItem.setId((documentSnapshot.getId()));
Intent intent = new Intent(ListActivity.this, DetailActivity.class);
intent.putExtra(First_Name, clickedItem.getFname());
intent.putExtra(Middle_Name, clickedItem.getMname());
intent.putExtra(Sur_Name, clickedItem.getSname());
intent.putExtra(Email, clickedItem.getEmail());
intent.putExtra(phone, clickedItem.getPhone());
intent.putExtra(city, clickedItem.getCity());
intent.putExtra(parents_Name, clickedItem.getParentsName());
intent.putExtra(parents_Phone, clickedItem.getParentsContact());
intent.putExtra(dob, clickedItem.getDob());
intent.putExtra(emergency, clickedItem.getEmergency());
intent.putExtra(profile_Picture, clickedItem.getProfilePicture());
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
startActivityForResult(intent, 45);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == 45 && resultCode == RESULT_OK && data != null)) {
String fname = data.getStringExtra(First_Name);
String mname = data.getStringExtra(Middle_Name);
String sname = data.getStringExtra(Sur_Name);
String email = data.getStringExtra(Email);
String Phone = data.getStringExtra(phone);
String City = data.getStringExtra(city);
String pname = data.getStringExtra(parents_Name);
String pphone = data.getStringExtra(parents_Phone);
String Dob = data.getStringExtra(dob);
String Emergency = data.getStringExtra(emergency);
String profile = data.getStringExtra(profile_Picture);
Item items = new Item(fname, mname, sname, email, Phone, City,
pname, pphone, Dob, Emergency, profile);
db.collection("Archives").document(clickedItem.getId())
.set(items).addOnSuccessListener(new
OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(ListActivity.this, "Updated Successfully",
Toast.LENGTH_LONG).show();
}
});
}
}
}
Activity documentation of overridePendingTransition says:
Call immediately after one of the flavors of startActivity(android.content.Intent) or finish() to specify an explicit transition animation to perform next.
So calling overridePendingTransition in any other places at least does nothing. Remove such calls like in ListActivity#onCreate after setContentView and place them next line to startActivity or startActivityForResult.

How to pass/get value checkbox from adapter recycleview to another activity

There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing
If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});

Go To Existing Fragment from Opened Child Activity

I have an app that has two tabs with fragments. One tab is called map and the other restaurantList. When I click on map marker or a card in the list it opens a restaurantDetailsActivity that has info about restaurant - lat, lang, name, rating, etc. There I have a floating action button that the user should click and it should close the current activity and go to maps tab fragment, to the location that I passed from the activity. I have tried a lot of stuff without any success: 1 2 3 4 5 6 7 8 9 ...
This is what I would want - when the user clicks the FAB, it should pass lat and lon from the restaurantDetailsActivity, to my map fragment and zoom in into that location (based on the lat and lon), regardless whether it was opened from the list fragment or the map fragment.
My restaurantDetailsActivity:
final String lat = restaurant.getLat();
final String lon = restaurant.getLon();
FloatingActionButton fabGoToMap = findViewById(R.id.fabGoToMap);
fabGoToMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// MapsFragment fragment = new MapsFragment();
// Bundle bundle = new Bundle();
// bundle.putString("lat", lat);
// bundle.putString("lon", lon);
// MapsFragment mapsFragment = new MapsFragment();
// mapsFragment.setArguments(bundle);
// Intent restaurantDescriptionIntent = new Intent(this, MapsFragment.class);
Bundle bundle = new Bundle();
bundle.putString("lat", lat);
bundle.putString("lon", lon);
MapsFragment fragInfo = new MapsFragment();
fragInfo.setArguments(bundle);
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// transaction.add(R.id.map, mapsFragment, "tag").commit();
finish();
}
});
UPDATED CODE:
Calling the activity from list fragment:
public void fetchRestaurant(String restaurantId) {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<RestaurantResponse> call = apiService.getRestaurantById(restaurantId);
call.enqueue(new Callback<RestaurantResponse>() {
#Override
public void onResponse(Call<RestaurantResponse> call, retrofit2.Response<RestaurantResponse> response) {
final Restaurant restaurant= response.body().getResults();
Intent intent = new Intent(getActivity().getApplicationContext(), AvailableRestaurantActivity.class);
intent.putExtra("estaurant", estaurant);
startActivity(intent);
}
#Override
public void onFailure(Call<RestaurantResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
Toast.makeText(getActivity().getApplicationContext(), R.string.failed_connectivity, Toast.LENGTH_LONG).show();
}
});
}
My main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tutorialUsed = false;
tutorialPage = 1;
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
} else {
List<restaurant> restaurants = new ArrayList<>();
TabLayout tabLayout = findViewById(R.id.sliding_tabs);
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_one)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_two)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
final ViewPager viewPager = findViewById(R.id.viewpager);
PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(3);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
});
....
myUserName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent accountIntent = new Intent(MainActivity.this, MyProfileActivity.class);
startActivity(accountIntent);
}
});
}
}
Start restaurantDetailactivity from your MainActivity using startActivityForResult like this
startActivityForResult(intent, SHOW_DETAILS_REQUEST);
Click on FAB should be like this
final String lat = restaurant.getLat();
final String lon = restaurant.getLon();
FloatingActionButton fabGoToMap = findViewById(R.id.fabGoToMap);
fabGoToMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("lat", lat);
bundle.putString("lon", lon);
intent.putExtras(bundle);
setResult(Activity.RESULT_OK,intent);
}
});
in your MainActivity handle activity result like below
#Override
protected void onActivityResult(final int requestCode,
final int resultCode,
final Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SHOW_DETAILS_REQUEST: {
//select mapfragment as current, assuming it is at index 0
viewpager.setCurrentItem(0);
//add your zoom logic here in zoomToCenter method
mapfragment.zoomToCenter(data.getStringExtra("lat"),data.getStringExtra("lon"));
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Kemo, You have an event that takes place in a fragment and as a result of the event you want the activity to swap one fragment for a second fragment. So your problem is how to communicate from fragment to activity. The fragment's on attach will give you the context for the activity. The activity should have a method to swap fragments in and out and using the context you got in the on attach you can use in the fragments oncreateview and run the activity's method.here Good luck professor

Categories

Resources