FragmentPagerAdapter always starts from the first page - java

I have a Fragment pager adapter with five fragments and inside the third fragment I want to call an other activity which sends a selected picture to the container. It works fine but, every time the picture is selected from the other activity and the pager adapter starts from the first fragment in the fragment-activity instead of third fragment-activity. Do I have to force the pager adapter from the other activity or should I change something in the fragment-activity?
Code:
Fragment-activity:
package com.example.android.womb_the_game;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
public class Circulation extends FragmentActivity {
ViewPager vp;
public static FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_circulation);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
vp = findViewById(R.id.view_pager);
adapterViewPager=new Adapter_Circulation(getSupportFragmentManager(), this);
vp.setAdapter(adapterViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(vp);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
FragmentPagerAdapter:
package com.example.android.womb_the_game;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import android.content.Context;
public class Adapter_Circulation extends FragmentPagerAdapter {
private static int NUM_ITEMS = 5;
Context context;
public Adapter_Circulation(FragmentManager fm, Context c) {
super(fm);
this.context = c;
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return Frg0.newInstance ();
case 1:
return Frg1.newInstance();
case 2:
return Frg2.newInstance();
case 3:
return Frg3.newInstance();
case 4:
return Frg4.newInstance();
}
return null; //does not happen
}
#Override
public int getCount() {
return NUM_ITEMS; //three fragments
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "RULES";
case 1:
return "EVENTS";
case 2:
return "PLAN";
case 3:
return "SHOOT";
case 4:
return "JUMP";
}
return null;
}
}
Fragment3:
package com.example.android.womb_the_game;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class Frg3 extends Fragment{
private ImageButton shoot;
private ImageButton snipe;
private ImageButton aim;
public static Frg3 newInstance() {
Bundle args = new Bundle();
Frg3 fragment = new Frg3();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_frg3, container, false);
shoot = (ImageButton) rootView.findViewById(R.id.shoot);
snipe = (ImageButton) rootView.findViewById(R.id.snipe);
aim = (ImageButton) rootView.findViewById(R.id.aim);
final View.OnClickListener mListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.shoot:
FragmentManager FM0 = getFragmentManager();
FragmentTransaction FT0 = FM0.beginTransaction();
frg_shoot F10 = new frg_shoot();
FT0.add(R.id.fragment_container1, F10);
FT0.replace(R.id.fragment_container1, F10);
FT0.commit();
break;
case R.id.snipe:
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
frg_snipe F1 = new frg_snipe();
FT.add(R.id.fragment_container1, F1);
FT.replace(R.id.fragment_container1, F1);
FT.commit();
break;
case R.id.aim:
FragmentManager FM1 = getFragmentManager();
FragmentTransaction FT1 = FM1.beginTransaction();
frg_aim F11 = new frg_aim();
FT1.add(R.id.fragment_container1, F11);
FT1.replace(R.id.fragment_container1, F11);
FT1.commit();
break;
}
}
};
rootView.findViewById(R.id.shoot).setOnClickListener(mListener);
rootView.findViewById(R.id.snipe).setOnClickListener(mListener);
rootView.findViewById(R.id.aim).setOnClickListener(mListener);
return rootView;
}
}
Other Activity:
package com.example.android.womb_the_game;
import androidx.fragment.app.FragmentActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
public class choose_dice_column extends FragmentActivity {
private ImageButton b1;
private ImageView im1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_choose_dice_column);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
b1 = (ImageButton) findViewById(R.id.b1);
im1 = findViewById(R.id.im1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(choose_dice_column.this, Circulation.class);
i.putExtra("resid1",R.drawable.n1);
startActivity(i);
}
});
}
}

The problem is, whenever you get back to your activity, you are creating a new adapter. So add the following to your Circulation-Activity to keep the state of the adapter:
if(adapterViewPager == null)
{
adapterViewPager = new Adapter_Circulation(getSupportFragmentManager(), this);
}

Related

Pass the data from activity to Page Adapter

I need to pass the String data to tab layout. i'm already pass the data from adapter to fragments in Tab layout. But my problem is I cannot to pass that data from activity to Adapter java class. I need to pass the data to more than one fragment. how can i do this?
Main Activity Code
package com.example.tablay;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import com.google.android.material.tabs.TabLayout;
import java.util.List;
import java.util.Stack;
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private TabLayout tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager=(ViewPager) findViewById(R.id.pager);
tabs=(TabLayout) findViewById(R.id.tabs);
pager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager()));
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
}
}
Page Adapter Code :
package com.example.tablay;
import android.os.Bundle;
import android.provider.ContactsContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.Date;
import java.util.List;
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
String[] title = new String[]{
"Tab 1", "Tab 2", "Tab 3"
};
public TabFragmentPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position){
case 0:
tab1Fragment tab1Fragment=new tab1Fragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
tab1Fragment.setArguments(bundle);
return tab1Fragment;
case 1:
tab2Fragment tab2Fragment=new tab2Fragment();
bundle = new Bundle();
bundle.putString("edttext1", "data From Activity1");
tab2Fragment.setArguments(bundle);
return tab2Fragment;
case 2:
tab3Fragment tab3Fragment=new tab3Fragment();
return tab3Fragment;
default:
fragment=null;
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
#Override
public int getCount() {
return title.length;
}
}
Fragment Code:
package com.example.tablay;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class tab1Fragment extends Fragment {
public tab1Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab1, container, false);
TextView tes=(TextView) view.findViewById(R.id.testtab1);
String strtext = getArguments().getString("edttext");
tes.setText(strtext);
return view;
}
}
I need to pass the String data to tab layout. i'm already pass the data from adapter to fragments in Tab layout. But my problem is I cannot to pass that data from activity to Adapter java class. I need to pass the data to more than one fragment. how can i do this?
You can pass data from activity to the adapter by constructor like this :
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private TabLayout tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager=(ViewPager) findViewById(R.id.pager);
tabs=(TabLayout) findViewById(R.id.tabs);
pager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager(),ActivityStringData));
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
}
to
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
String[] title = new String[]{
"Tab 1", "Tab 2", "Tab 3"
};
String data=null;
public TabFragmentPagerAdapter(#NonNull FragmentManager fm,String activityData) {
super(fm);
this.data=activityData
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position){
case 0:
tab1Fragment tab1Fragment=new tab1Fragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
tab1Fragment.setArguments(bundle);
return tab1Fragment;
case 1:
tab2Fragment tab2Fragment=new tab2Fragment();
bundle = new Bundle();
bundle.putString("edttext1", "data From Activity1");
tab2Fragment.setArguments(bundle);
return tab2Fragment;
case 2:
tab3Fragment tab3Fragment=new tab3Fragment();
return tab3Fragment;
default:
fragment=null;
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
#Override
public int getCount() {
return title.length;
}
}

incompatible types: RecViewFragment cannot be converted to Fragment

Earlier, my code was working fine but after some update in android studio gradle build, there is an error - "error: incompatible types: RecViewFragment cannot be converted to Fragment
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new RecViewFragment()).commit();"
I tried import androidx.fragment.app.Fragment
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
public class MainActivityBuses extends AppCompatActivity {
NavigationView nav;
ActionBarDrawerToggle toggle;
DrawerLayout drawerLayout;
Toolbar toolbar;
BottomNavigationView btmNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_buses);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nav = findViewById(R.id.drawernav);
drawerLayout = findViewById(R.id.drawerlayout);
toggle = new ActionBarDrawerToggle(this,drawerLayout, toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
nav.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectdnav = null;
switch (item.getItemId()){
case R.id.dnavprofile:
selectdnav = new MyProfileFragment();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.dnavmap:
selectdnav = new MapFragment();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.dnavmybus:
selectdnav = new BusFragment();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.dnavinfo:
selectdnav = new InfoFragment();
drawerLayout.closeDrawer(GravityCompat.START);
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,selectdnav).commit();
return true;
}
});
btmNav = (BottomNavigationView) findViewById(R.id.btmnav);
btmNav.setOnNavigationItemSelectedListener((navListner));
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new RecViewFragment()).commit();
btmNav.getMenu().findItem(R.id.navhome).setChecked(true);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListner = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.navprofile:
selectedFragment = new MyProfileFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new MyProfileFragment()).commit();
break;
case R.id.navmap:
Intent intent = new Intent(MainActivityBuses.this, MapActivity.class);
startActivity(intent);
finish();
break;
case R.id.navhome:
selectedFragment = new RecViewFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new RecViewFragment()).commit();
break;
case R.id.navmybus:
selectedFragment = new BusFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new BusFragment()).commit();
break;
case R.id.navinfo:
selectedFragment = new InfoFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InfoFragment()).commit();
break;
}
return true;
}
};
}
RecViewFragment class
package com.example.trackmybusstudent;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Use the {#link RecViewFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class RecViewFragment extends Fragment {
RecyclerView recyclerView;
ArrayList datalist;
FirebaseFirestore db;
myadapter myadap;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public RecViewFragment() {
}
public static RecViewFragment newInstance(String param1, String param2) {
RecViewFragment fragment = new RecViewFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_rec_view, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycleview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
db = FirebaseFirestore.getInstance();
datalist = new ArrayList<>();
myadap = new myadapter(datalist);
recyclerView.setAdapter(myadap);
db.collection("Bus_Database").orderBy("Route_Number", Query.Direction.ASCENDING).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for(DocumentSnapshot d:list){
model obj = d.toObject(model.class);
datalist.add(obj);
myadap.notifyDataSetChanged();
}
}
});
return v;
}
}
In your switch there's no default case, maybe you didn't set your ids correctly in the menu file, therefore selectdnav remains null.
I suggest you add a breakpoint to quickly analyze this.

How to send an object (an arraylist in this situation) from one fragment to another fragment in java (Android)

The title says it all. I am attempting to send an ArrayList that has data inside from one fragment to another and then switch and show the second fragment (the one that just received the ArrayList).
here is my MainActivity.java:
package;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_display)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
}
}
here is my HomeFragment.java (the sending fragment):
package;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.Navigation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import com.mvsolutions.snap.R;
import com.mvsolutions.snap.ui.display.DisplayFragment;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import static android.app.Activity.RESULT_OK;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private ImageView imageView;
private Button captureImageButton, detectButton, pickButton;
private Bitmap imageBitmap;
private TextView capturedTextView;
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int RESULT_LOAD_IMAGE = 101;
public View onCreateView(#NonNull final LayoutInflater inflater,
final ViewGroup container, Bundle savedInstanceState) {
//View view = inflater.inflate(R.layout.fragment_home, container, false);
View root = inflater.inflate(R.layout.fragment_home, container, false);
detectButton = root.findViewById(R.id.action_homeFragment_to_displayFragment2);
//detectButton.setOnClickListener((View.OnClickListener) this);
//return view;
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
//View v = inflater.inflate(R.layout.fragment_display, container, false);
imageView = root.findViewById(R.id.home_image_view_img);
capturedTextView = root.findViewById(R.id.home_text_view_txt);
captureImageButton = root.findViewById(R.id.capture_image_btn);
detectButton = root.findViewById(R.id.detect_text_btn);
//pickButton = root.findViewById(R.id.pick_image_btn);
captureImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
// pickButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// pickImage();
// }
// });
detectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.action_homeFragment_to_displayFragment2);
// DisplayFragment displayFragment = new DisplayFragment();
// FragmentManager fragmentManager = getFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.DisplayFragment, displayFragment, displayFragment.getTag())
// .commit();
//detectTextFromImage();
}
});
return root;
}
private void detectTextFromImage() {
capturedTextView.setText("");
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
FirebaseVisionTextDetector visionTextDetector = FirebaseVision.getInstance().getVisionTextDetector();
visionTextDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
List<FirebaseVisionText.Block> textBlocks = firebaseVisionText.getBlocks();
if (textBlocks.size() == 0) {
Toast.makeText(getContext(), "No Text Found", Toast.LENGTH_SHORT).show();
} else {
for (FirebaseVisionText.Block block : textBlocks) {
String text = block.getText();
ArrayList textBlobs = new ArrayList();
textBlobs.add(text);
for(int i = 0; i < textBlobs.size(); i++) {
capturedTextView.setText(capturedTextView.getText() + ", " + textBlobs.get(i));
}
// capturedTextView.setText(capturedTextView.getText() + " " + text);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
Log.d("Error", e.getMessage());
}
});
}
private void pickImage() {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
private void captureImage() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
// else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
// Uri imageUri = data.getData();
// imageBitmap = MediaStore.Images.Media.decodeBitmap(this.);
// imageView.setImageBitmap(imageBitmap);
// }
}
}
here is my DisplayFragment.java (the receiving fragment):
package com.mvsolutions.snap.ui.display;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.mvsolutions.snap.R;
public class DisplayFragment extends Fragment {
private DisplayViewModel DisplayViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
DisplayViewModel =
ViewModelProviders.of(this).get(DisplayViewModel.class);
View root = inflater.inflate(R.layout.fragment_display, container, false);
// final TextView textView = root.findViewById(R.id.text_gallery);
DisplayViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
}
});
return root;
}
}
I am currently using a navigation fragment xml file to make the button switch from the first fragment to the second, but I want it to send the data to the second fragment as well.
My two questions are:
Is it possible to both send the data to the second fragment and switch to the second fragment with one button press? or do I have to split it into two?
How do I send the data from the first fragment to the second?
You are using ViewModel so I think the easiest way is to use the same ViewModel for both fragments. In android docs, You can find an example Share data between fragments
It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of split-view (master-detail) fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item.
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
}
}
Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.

Recyclerview with cards in a fragment shows nothing

I am trying to make an activity which has a fragment inside with a recyclerView and cards on it. Right now, it only shows the activity, the fragment is empty, and I don't know what is going on here.
This is the code of the activity, the fragment, and the adapter
Activity:
package com.laorden.goodreasons.habits;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.NavigationView;
import android.support.test.espresso.IdlingResource;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.Injection;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.statistics.StatisticsActivity;
import com.laorden.goodreasons.util.ActivityUtils;
import com.laorden.goodreasons.util.EspressoIdlingResource;
public class HabitsActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private HabitsPresenter mHabitsPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.habits_act);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// Set up the toolbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
// Set up the navigation drawer.
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
HabitsFragment habitsFragment =
(HabitsFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
if (habitsFragment == null) {
// Create the fragment
habitsFragment = HabitsFragment.newInstance();
ActivityUtils.addFragmentToActivity(
getSupportFragmentManager(), habitsFragment, R.id.contentFrame);
}
// Create the presenter
mHabitsPresenter = new HabitsPresenter(habitsFragment,
Injection.provideUseCaseHandler());
}
/* // Load previously saved state, if available.
if (savedInstanceState != null) {
TasksFilterType currentFiltering =
(TasksFilterType) savedInstanceState.getSerializable(CURRENT_FILTERING_KEY);
mTasksPresenter.setFiltering(currentFiltering);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(CURRENT_FILTERING_KEY, mTasksPresenter.getFiltering());
super.onSaveInstanceState(outState);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Open the navigation drawer when the home icon is selected from the toolbar.
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.list_navigation_menu_item:
// Do nothing, we're already on that screen
break;
case R.id.statistics_navigation_menu_item:
Intent intent =
new Intent(HabitsActivity.this, StatisticsActivity.class);
startActivity(intent);
break;
default:
break;
}
// Close the navigation drawer when an item is selected.
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#VisibleForTesting
public IdlingResource getCountingIdlingResource() {
return EspressoIdlingResource.getIdlingResource();
}
}
Fragment:
package com.laorden.goodreasons.habits;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.ArrayList;
import java.util.List;
public class HabitsFragment extends android.support.v4.app.Fragment implements HabitsContract.View {
private HabitsContract.Presenter mPresenter;
private HabitsAdapter mListAdapter;
private RecyclerView recyclerView;
public HabitsFragment() {
// Requires empty public constructor
}
public static HabitsFragment newInstance() {
return new HabitsFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Habit> habitsList = new ArrayList<>();
habitsList.add(new Habit(R.drawable.smoke,"Quit smoking",300));
habitsList.add(new Habit(R.drawable.books,"Read more",600));
habitsList.add(new Habit(R.drawable.sleep,"Get more sleep",600));
mListAdapter = new HabitsAdapter(getContext(),habitsList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setAdapter(mListAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return root;
}
#Override
public void onResume() {
super.onResume();
mPresenter.start();
}
#Override
public void setLoadingIndicator(boolean active) {
}
#Override
public void showHabits(List<Habit> habits) {
}
#Override
public void showHabitDetailsUi(String habitId) {
}
#Override
public boolean isActive() {
return false;
}
#Override
public void setPresenter(HabitsContract.Presenter presenter) {
mPresenter = presenter;
}
}
Adapter:
package com.laorden.goodreasons.habits;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.List;
public class HabitsAdapter extends RecyclerView.Adapter<HabitsAdapter.myViewHolder> {
Context mContext;
List<Habit> mData;
public HabitsAdapter(Context mContext, List<Habit> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.card_item,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
holder.background_image.setImageResource(mData.get(position).getBackground());
holder.tv_title.setText(mData.get(position).getHabitName());
holder.tv_nbSubscribers.setText(mData.get(position).getNumSubscribers() + " Joined");
}
#Override
public int getItemCount() {
return 0;
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView background_image;
TextView tv_title,tv_nbSubscribers;
public myViewHolder(View itemView) {
super(itemView);
background_image = itemView.findViewById(R.id.card_background);
tv_title = itemView.findViewById(R.id.card_title);
tv_nbSubscribers = itemView.findViewById(R.id.card_numberUsers);
}
}
}
If you need any other code snippets, please tell me (maybe the xml
layouts)
Thanks
That is because you are returning 0 in the getItemCount method
Change this :
#Override
public int getItemCount() {
return 0;
}
To this:
#Override
public int getItemCount() {
return (mData != null ? mData.size():0);
}
you should set layout manager first
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mListAdapter);
return root;
}
also you need to change the getItemCount into
#Override
public int getItemCount() {
if(mData!=null){return mData.size();}else return 0;
}
The reason you are getting empty list because your method getItemCount returns 0.
Here is the modified method.
#Override
public int getItemCount() {
return mData!=null ? mData.size():0;
}

When I move from fragment b to fragment A after adding my new listitem, my new listitem is not showing in recyclerview

I am making note taking app.i have two fragments in my app first fragment A (ListFragment) contains the recycler adapter .
while when I press adding floating button first fragment A (ListFragment) is replaced with next fragment B(AddingFragment) in which I type new data and then again press adding floating button on fragment B(AddingFragment) to add that new data in data set and then press backfloating button on my fragment B to move back to Fragment A(with recycler adapter) .
This new data item is added to data list every time but never becomes visible in recycler adapter in Fragment A.
package com.example.anonymous.note_taking_app;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class AddingFragment extends Fragment {
public AddingFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_adding, container, false);
return view;
}
#Override
public void onResume()
{
super.onResume();
FloatingActionButton floating = (FloatingActionButton) getActivity().findViewById(R.id.addingfloatingbutton);
floating.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("floating_button", "floating button 2 clicked");
EditText title = (EditText) getActivity().findViewById(R.id.firsttextview);
EditText detial = (EditText) getActivity().findViewById(R.id.secondtextview);
DatabaseHelper db = new DatabaseHelper(getActivity().getApplication());
boolean insert = db.insert(title.getText()+"",detial.getText()+"");
if(insert==true)
{
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter();
ListFragment.it.add(new ListItem(title.getText()+"",detial.getText()+""));
l.notifyItemInserted(ListFragment.it.size()-1);//DataSetChanged();
l.notifyDataSetChanged();
for(int i=0;i<ListFragment.it.size();i++)
{
Log.i("List item"+i+"", ListFragment.it.get(i).getNoteTitle());
}
Log.i("insertion", "is added");
}
else
{
Log.i("insertion", "is not added");
}
}
});
FloatingActionButton floatings = (FloatingActionButton) getActivity().findViewById(R.id.addcancelfloatingbutton);
floatings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStackImmediate();
}
});
}
}
//
package com.example.anonymous.note_taking_app;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Fragment;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.holderclas> implements EditDilogue.EditDilougeinterface
{
static ArrayList<ListItem> i;
Context context;
View view;
ImageButton share;
ImageButton edit;
static int lastposition;
android.app.FragmentManager fm;
public ListAdapter(ArrayList<ListItem> i,android.app.FragmentManager fm)
{
this.i=i;
this.fm=fm;
}
public ListAdapter()
{
}
#Override
public ListAdapter.holderclas onCreateViewHolder(ViewGroup parent, int viewType)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
holderclas h = new holderclas(view);
share = (ImageButton) view.findViewById(R.id.share);
edit = (ImageButton) view.findViewById(R.id.edit);
return h;
}
#Override
public void onBindViewHolder(ListAdapter.holderclas holder, final int position)
{
final int y= position;
lastposition = position;
final ListItem it = i.get(position);
holder.title.setText(it.getNoteTitle());
holder.details.setText(it.getNoteDetail());
ImageButton b =(ImageButton) view.findViewById(R.id.delete);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("size", i.size()+"");
i.remove(y);
notifyDataSetChanged();
}
});
share.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("share", "share");
}
});
edit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("edit", i.size()+"edit");
EditDilogue ed = new EditDilogue();
Bundle args = new Bundle();
args.putString("title", it.getNoteTitle());
args.putString("detail", it.getNoteDetail());
ed.setArguments(args);
ed.setTargetFragment(new ListFragment(),1);
ed.show(fm,"fragment");
}
});
}
#Override
public int getItemCount()
{
return i.size();
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = i.get(lastposition).getNoteTitle();
String olddetail = i.get(lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
public class holderclas extends RecyclerView.ViewHolder
{
TextView title;
TextView details;
public holderclas(View itemView)
{
super(itemView);
title=(TextView) itemView.findViewById(R.id.title);
details=(TextView) itemView.findViewById(R.id.detail);
}
}
}
//
package com.example.anonymous.note_taking_app;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListFragment extends Fragment implements EditDilogue.EditDilougeinterface
{
RecyclerView recyClerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
public static ArrayList<ListItem> it;
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
it = new ArrayList<>();
View view = inflater.inflate(R.layout.fragment_list, parent, false);
FloatingActionButton floating = (FloatingActionButton) view.findViewById(R.id.listfloatingbutton);
floating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Fragment frg = new AddingFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.replace(R.id.placeholder,frg);
trans.addToBackStack("addingfragment");
trans.commit();
AddingFragment()).addToBackStack("addingfragment").commit();
}
});
for(int i=0;i<5;i++)
{
ListItem t = new ListItem("Time Bank",
"Bank should contain atleast $2000 rupees then i will leave this matter") ;
it.add(t);
}
recyClerView=(RecyclerView) view.findViewById(R.id.recycle);
FragmentManager fm = getFragmentManager();
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter(it,fm);
recyClerView.setAdapter(l);
layoutManager = new LinearLayoutManager(getActivity());
recyClerView.setLayoutManager(layoutManager);
return view;
}
#Override
public void onResume()
{
super.onResume();
if(adapter!=null)
{
adapter.notifyDataSetChanged();
adapter.notifyItemInserted(ListFragment.it.size()-1);
}
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteTitle();
String olddetail = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
}

Categories