how to pass data from activity to fragment..? - android

Hello everyone i need help in passing data from activity to fragment.
im using the this way but getting error of null pointer .
In main Activity
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.leftfeedback:
handleChanges();
break;
}
}
private void handleChanges() {
FeedBackFragment feedBackFragment =new FeedBackFragment();
if (feedBackFragment != null) {
feedBackFragment.fragmentCommunication(ExtraData);
} else {
Log.i(TAG, "Fragment 2 is not initialized");
}
}
in fragment side
all given data is coming i checked with log before to set on
public class FeedBackFragment extends Fragment{
private static final String TAG ="FeedBackFragment" ;
View view;
TextView feedbackEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.feedback_fragemnt, container, false);
feedbackEditText = (TextView) view.findViewById(R.id.feedbackEditText);
return view;
}
public void fragmentCommunication(String feedBackData) {
log.i(TAG,feedBackData);
try {
JSONObject jsonObject = new JSONObject(feedBackData);
String message = jsonObject.getString("message");
if(message.trim()!=null){
feedbackEditText.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

This could happen if you haven't created the fragment in the right way.
If you dynamically add the fragment with:
getSupportFragmentManager().beginTransaction().
replace(R.id.container, new FeedBackFragment(), YOUR_FRAGMENT_TAG).
commit();
You can use the following code to communicate with the fragment.
private void handleChanges() {
FeedBackFragment feedBackFragment =new FeedBackFragment();
// you need to use id if you add the fragment via layout.
//FeedBackFragment feedBackFragment = (FeedBackFragment)
getSupportFragmentManager().findFragmentById(R.id.your_feed_back_fragment_id);
// If you dynamically add the fragment, use tag to find the fragment.
FeedBackFragment feedBackFragment = (FeedBackFragment)
getSupportFragmentManager().findFragmentByTag(YOUR_FRAGMENT_TAG);
if (feedBackFragment != null) {
feedBackFragment.fragmentCommunication(ExtraData);
} else {
Log.i(TAG, "Fragment 2 is not initialized");
}
}
Read more at Creating and Using Fragments.

Because of feedBackFragment not create, so Edittext is null
you should attach your feedBackFragment to MainActivity.
FeedBackFragment feedBackFragment;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.leftfeedback:
handleChanges();
break;
}
}
private void handleChanges() {
if (null == feedBackFragment) {
feedBackFragment = new FeedBackFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(contentId, feedBackFragment);
transaction.commit();
}
feedBackFragment.fragmentCommunication(ExtraData);
}

http://www.androhub.com/android-pass-data-from-activity-to-fragment/
check this link here you find exact what you want with better clearification

I have changed some of your code try this. It works for you.
private void handleChanges() {
FeedBackFragment feedBackFragment =new FeedBackFragment();
if (feedBackFragment != null) {
Bundle bundle = new Bundle();
bundle.putString("edttext", "ExtraData");
// set Fragmentclass Arguments
feedBackFragment.setArguments(bundle);
} else {
Log.i(TAG, "Fragment 2 is not initialized");
}
}
And in Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
view = inflater.inflate(R.layout.feedback_fragemnt, container, false);
feedbackEditText = (TextView) view.findViewById(R.id.feedbackEditText);
feedbackEditText.setText(strtext);
return view;
}

try this :
private void handleChanges() {
Bundle bundle = new Bundle();
bundle.putString("KEY", "string");
FeedBackFragment fragment = new FeedBackFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
on your fragment : to get the data :
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("KEY");
}

Related

Show snackbar in fragment from another fragment (IllegalArgumentException: No suitable parent found from the given view)

I check out similar question but no one helped me
I have 1 activity and 2 fragments inside it
1st fragment contains list of movies, 2nd - qr-scanner
if I scan the QR-code, fragment changed by themself and list-fragment returns foreground
if QR-code containes new movie - it will be add to list(it works ok)
if QR-code containes already exist movie - I need to show snackbar
my issue - while I try to show snackbar app crashes with
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.appolinary.msapphometask, PID: 20992
java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
at com.google.android.material.snackbar.Snackbar.make(Snackbar.java:181)
at com.appolinary.msapphometask.presentation.view.AllMoviesFragment.showSnackbar(AllMoviesFragment.java:113)
QR scanner fragment
public class QRReaderFragment extends Fragment {
private final String TAG = "MSApp";
private BarcodeView barcodeView;
private final int PERMISSIONS_REQUEST_ACCESS_CAMERA = 0;
private View view;
private OnQRReaderListener qrReaderListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_qrreader, container, false);
if (Objects.requireNonNull(getActivity()).checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
PERMISSIONS_REQUEST_ACCESS_CAMERA);
} else {
barcodeView = view.findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
}
qrReaderListener = (OnQRReaderListener) getActivity();
return view;
}
private BarcodeCallback callback = new BarcodeCallback() {
#Override//TODO need to check bar-code for validity and prevent crash of application
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
barcodeView.pause();
String tag_string = result.getText();
MovieDetails movie = new Gson().fromJson(tag_string, MovieDetails.class);
returnToMovieList(movie);
Log.d(TAG,"resuming scanner, data needed was not found");
barcodeView.resume();
}
}
}
};
private void returnToMovieList(MovieDetails movie) {
qrReaderListener.dataReceived(movie);
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.popBackStack();
}
public interface OnQRReaderListener{
void dataReceived(MovieDetails movie);
}
}
list-fragment
public class AllMoviesFragment extends Fragment implements RecyclerViewAdapter.OnRecyclerViewItemClickListener,
MovieListActivity.SnackbarLauncher {
private static final String CURR_MOVIE = "Current Movie";
private static final String TAG = "MSApp";
View resultView;
RecyclerView recyclerView;
Button qrButton;// will lead us to QR Scanner
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
resultView = inflater.inflate(R.layout.fragment_all_movies, container, false);
recyclerView = resultView.findViewById(R.id.recycler_view);
qrButton = resultView.findViewById(R.id.button_qr);
qrButton.setOnClickListener(v -> {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
Fragment qrScannerFragment = new QRReaderFragment();
String tag = "QRScanner";
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, qrScannerFragment, tag);
transaction.addToBackStack(tag);
transaction.commit();
});
#Override
public void showSnackbar() {
Log.d(TAG, "showSnackbar: this.getView() == null ? " + (this.getView()));
Log.d(TAG, "showSnackbar: resultView == null ? " + (resultView == null));
final LinearLayout linearLayout = resultView.findViewById(R.id.fragment_all_movies);
View view = resultView.findViewById(android.R.id.content);
Snackbar.make(view, getResources().getString(R.string.movie_exists), Snackbar.LENGTH_LONG);
}
}
activity
public class MovieListActivity extends AppCompatActivity implements QRReaderFragment.OnQRReaderListener {
String tag = "MovieList";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment allMoviesFragment = new AllMoviesFragment();
transaction.replace(R.id.main_container, allMoviesFragment, tag);
transaction.commit();
}
#Override
public void dataReceived(MovieDetails movie) {
Toast.makeText(this, movie.toString(), Toast.LENGTH_LONG).show();
DatabaseHelper db = App.getAppInstance().getDatabaseInstance();
MovieDetails tempMovie = db.getMovieDao().getMovieByName(movie.getTitle());
if (tempMovie == null) {
Log.d(TAG, "dataReceived: point1");
db.getMovieDao().insert(movie);
} else {//comparing only by title here!!!
FragmentManager fragmentManager = getSupportFragmentManager();
AllMoviesFragment allMoviesFragment = (AllMoviesFragment) fragmentManager.findFragmentByTag(tag);
allMoviesFragment.showSnackbar();
}
}
}
it crashes in the line
Snackbar.make(view, getResources().getString(R.string.movie_exists), Snackbar.LENGTH_LONG);
I tried to use resultView(from onCreateView method), I tried to use findViewById(android.R.id.content) - all of them are not null but no success
my fault
I forgot about Coordinator Layout :-(

How to get value from childfragment to parentfragment?

I am frustrated.
i want to get value from child fragment to parent fragment
i had tries many method.
interface, viewModel, sharedpreferences but no one work.
I had follow this method
but it doesn't work for me.
here my code parent fragment:
public class Chart_Fragment extends Fragment
implements Product_Fragment.pf_interface {
String dt;
TextView tv;
public Chart_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.chart_fragment, container, false);
// create product_fragment as childfragment
FragmentManager fm = getChildFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Product_Fragment product_fragment = new Product_Fragment();
ft.replace(R.id.fl_two, new Product_Fragment());
ft.commit();
return v;
}
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
tv = (TextView)v.findViewById(R.id.rcv);
}
#Override
public void data(String d) {
FragmentManager fragmentManager = getChildFragmentManager();
Product_Fragment product_fragment =
(Product_Fragment)fragmentManager.findFragmentByTag("data");
if(product_fragment != null){
String dt = d;
tv.setText(dt);
}
}
}
and my childfragment is :
public class Product_Fragment extends Fragment {
private pf_interface pf;
public Product_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.product_fragment, container, false);
Button b = (Button)v.findViewById(R.id.btn_sender);
b.setOnClickListener(new btnClick());
return v;
}
public void onAttachToParentFragment(Fragment fragment){
try {
pf = (pf_interface)fragment;
}catch (ClassCastException e){
throw new ClassCastException(
fragment.toString()+ "must implement pf_interface"
);
}
}
public void onCreate(Bundle savedInstanceState){
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
onAttachToParentFragment(getParentFragment());
}
private class btnClick implements View.OnClickListener{
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_sender:
if(pf != null){
pf.data("button click interface");
}break;
}
}
}
public interface pf_interface{
void data(String d);
}
}
textview on parent fragment didn't show the string d ("button click interface")from child fragment
Why you're checking for child fragment in callback on your parent fragment ?
#Override
public void data(String d) {
FragmentManager fragmentManager = getChildFragmentManager();
Product_Fragment product_fragment =
(Product_Fragment)fragmentManager.findFragmentByTag("data");
if(product_fragment != null){ // Why to check for child fragment nullability?
String dt = d;
tv.setText(dt);
}
}
You can directly use like this:
#Override
public void data(String d) {
tv.setText(d);
}
Note: on any certain scenario if any of object is null, your callback won't be executed. You've already check for null reference.

Send value from activity to its fragment

i'm trying to send data from my activity class to its tab fragment, but in the fragment adapter it received no data and produced error nullPointerException.
here is my code
from activity
Intent receivedIntent = getIntent();
String tenant = null;
if ((bundle = receivedIntent.getExtras()) != null) {
tenant = (String) bundle.get("tenant");
}
TabFragment tabFragment = new TabFragment();
bundle.putString("tenant", tenant);
tabFragment.setArguments(bundle);
to fragment
Bundle getTenant = this.getArguments();
if(getTenant != null) {
tenant = getTenant.getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
pager adapter
case 0:
TabFragment tabFragment = new TabFragment();
tabFragment.setArguments(bundle);
return tabFragment;
In your fragment do this
if(getArguments() != null) {
tenant = getArguments().getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
instead of
Bundle getTenant = this.getArguments();
if(getTenant != null) {
tenant = getTenant.getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
Use below code:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Another way You are able to pass data using Interface like Below:
1 step: I created public interface in my Activity and setter for it:
Private OnAboutDataReceivedListener mAboutDataListener;
public interface OnAboutDataReceivedListener {
void onDataReceived(YourModelClass model);
}
public void setAboutDataListener(OnAboutDataReceivedListener listener) {
this.mAboutDataListener = listener;
}
2 step: I implemented this interface in my Fragment and set listener:
public class YourActivity extends BaseFragment implements YourBaseActivity.OnAboutDataReceivedListener
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (YourActivity) getActivity();
mActivity.setAboutDataListener(this);
}
3 step: I overrided interface's method:
#Override
public void onDataReceived(YourClassModel model) {
}

How to Access String In Another Fragment in Android

I am trying to access a String from an EditText on my login page to use in my other fragments. I found some information on using Bundle to achieve this, but I am having some difficulty implementing this function. I have a temporary TextView I am assigning the String to so I can tell when it is working, so ignore this object(tvGetTest).
Login Class:
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
etAccountNumber = (EditText) rootView.findViewById(R.id.etAccountNumber);
rbGroup = (RadioGroup) rootView.findViewById(R.id.rbGroup);
rbUsa = (RadioButton) rootView.findViewById(R.id.rbUsa);
rbCanada = (RadioButton) rootView.findViewById(R.id.rbCanada);
btnLogin = (Button) rootView.findViewById(R.id.btnLogin);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(accountNumber, accountNumber);
bundle.putString(countryCode, countryCode);
fragment.setArguments(bundle);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLogin();
}
});
return rootView;
}
public void doLogin() {
accountNumber = etAccountNumber.getText().toString();
if (rbUsa.isChecked()) {
countryCode = "USA";
}
else if (rbCanada.isChecked()) {
countryCode = "CAN";
}
}
onCreate of Other Fragment Class:
tvGetTest = (TextView) rootView.findViewById(R.id.tvGetTest);
Bundle bundle = this.getArguments();
if (bundle != null) {
String aNo = bundle.getString("accountNumber");
tvGetTest.setText(aNo);
}
Edit:
public void doBundle() {
Fragment fragment = new AvailabilityFragment();
Bundle bundle = new Bundle();
bundle.putString(accountNumber, accountNumber);
bundle.putString(countryCode, countryCode);
fragment.getFragmentManager().putFragment(bundle, accountNumber, fragment);
fragment.getFragmentManager().putFragment(bundle, countryCode, fragment);
}
It's preferable to manage all your fragments from their host activity, avoid nesting fragments.
In your use case, you should define a method in your HostActivity called launchOtherFragment:
public void launchOtherFragment(String accountNumber, String countryCode)
{
Bundle bundle = new Bundle();
bundle.putString("accountNumber", accountNumber);
bundel.putString("countryCode", countryCode);
OtherFragment fragment = new OtherFragment();
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
Now you can access this method in your first fragment, so in doLogin:
private void doLogin() {
accountNumber = etAccountNumber.getText().toString();
if (rbUsa.isChecked()) {
countryCode = "USA";
}
else if (rbCanada.isChecked()) {
countryCode = "CAN";
}
((HostActivity)getActivity()).launchOtherFragment(accountNumber, countryCode);
}

Same Fragment with listviews on different tabs

I would like to create an activity which shows 3 tabs. The first tab should show a user's uploaded photos the 2nd all the images a user liked, and 3rd the user's favorite images. All these data comes from a webservice.I would like to use the same fragment with it's layout file and call different URLs. The fragment implements a StringReader and populates a listview inside.
My problem is that I managed to load the Fragment in the first tab, but the second and third tabs remains empty. If I navigate to the last tab and started to navigate back, then the first tab remains empty and the second gets populated. I watched so many tutorials and red what I could reached but It seems that nothing has helped.
The Fragment instantiation in my Activity looks like this :
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return UsersSpheresFragment.newInstance();
case 1:
return UsersSpheresFragment.newInstance();
case 2:
return UsersSpheresFragment.newInstance();
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
my fragment is :
public class UsersSpheresFragment extends Fragment {
CircleImageView userImageFragment;
TextView userNameTextFragment;
TextView nrOfSpheresFragment;
LinearLayout loadingLayoutFragment;
ListView listview_spheresFragment;
public PhotosphereListAdapter adapter;
TextView nrOfLikes;
TextView nrOfSeens;
String userId="";
String userName = "";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_spheres_fragment,container,false);
return view;
}
// newInstance constructor for creating fragment with arguments
public static UsersSpheresFragment newInstance() {
UsersSpheresFragment fragmentFirst = new UsersSpheresFragment();
return fragmentFirst;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
userImageFragment = (CircleImageView) getActivity().findViewById(R.id.userImageFragment);
userNameTextFragment = (TextView) getActivity().findViewById(R.id.userNameTextFragment);
nrOfSpheresFragment = (TextView) getActivity().findViewById(R.id.nrOfSpheresFragment);
loadingLayoutFragment = (LinearLayout) getActivity().findViewById(R.id.loadingLayoutFragment);
listview_spheresFragment = (ListView) getActivity().findViewById(R.id.listview_spheresFragment);
nrOfLikes = (TextView)getActivity().findViewById(R.id.nrOfLikes);
nrOfSeens = (TextView)getActivity().findViewById(R.id.nrOfSeens);
GlobalUserData userData = (GlobalUserData)getActivity().getApplication();
Bundle bundle = this.getArguments();
if (bundle != null) {
userId = bundle.getString("userId","");
userName = bundle.getString("userName","");
userNameTextFragment.setText(userName);
}
else{
if (userData.getUserImageLink().length() > 0) {
LoadUserImage(userData.getName(), userData.getUserImageLink());
}
userNameTextFragment.setText(userData.getName());
}
//Log.i("TAG",userData.GetAllData());
if (userId.length() > 0)
loadImagesFromAPI(MainActivity.URL_DATA+"typ=mysphere&id="+userId);
else
loadImagesFromAPI(MainActivity.URL_DATA+"typ=mysphere&id="+userData.getUserId());
listview_spheresFragment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//send the photosphereId to the Panoviewer fragment
Bundle bundle = new Bundle();
bundle.putString("Id", view.getTag().toString());
bundle.putString("Title", ((Photosphere) adapter.getItem(position)).getTitle());
bundle.putString("Description", ((Photosphere) adapter.getItem(position)).getDescription());
bundle.putString("ThumbUrl", ((Photosphere) adapter.getItem(position)).getImageUrl());
bundle.putBoolean("ShowUserLink", userId.length() > 0 ? false : true);
//create the fragment
SimpleFragment fragment = new SimpleFragment();
fragment.setArguments(bundle);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
public void LoadUserImage(String userName, String imageUrl){
ImageLoader imageLoader = CustomVolleyRequest.getInstance(getActivity()).getImageLoader();
Bitmap bm = imageLoader.get(imageUrl, ImageLoader.getImageListener(userImageFragment, android.R.color.white, android.R.color.white)).getBitmap();
userImageFragment.setImageBitmap(bm);
userNameTextFragment.setText(userName);
}
public void loadImagesFromAPI(final String Url) {
loadingLayoutFragment.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, Url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
ArrayList<Photosphere> photospheres = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.isNull("userModel") || jsonObject.getJSONObject("userModel").isNull("OtherImages")){
loadingLayoutFragment.setVisibility(View.GONE);
nrOfSpheresFragment.setText("No images");
}
else {
if (userId.length() >0){
LoadUserImage((jsonObject.getJSONObject("userModel")).getString("UserName"),(jsonObject.getJSONObject("userModel")).getString("ImgPath"));
}
photospheres = new WebServiceReader().processSpheresModelJsonData(jsonObject.getJSONObject("userModel"),"OtherImages");
loadingLayoutFragment.setVisibility(View.GONE);
//init adapter
adapter = new PhotosphereListAdapter(getActivity(), photospheres, (userId.length() > 0 ? false : true),true);
listview_spheresFragment.setAdapter(adapter);
nrOfSpheresFragment.setText(nrOfSpheresFragment.getText()+"("+listview_spheresFragment.getCount()+")");
nrOfLikes.setText((jsonObject.getJSONObject("userModel")).getString("TotalLikes"));
nrOfSeens.setText((jsonObject.getJSONObject("userModel")).getString("TotalViews"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
nrOfSpheresFragment.setText("An error occurred. Please try again!");
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Update!
It seems that all of the fragments are loaded and overwritten in the first tab.
nrOfSpheresFragment.setText(nrOfSpheresFragment.getText()+"("+listview_spheresFragment.getCount()+")");
this line of code updates a textview and I can see that the textview is updated 3 times (25)(10)(5) which means the number of results. Only the last result's listview is visible
I figured out what was the problem.
When I used the fragment, (the fragment was created before, and used in other way) I didn't notice that when I initialize the controls in the page, I use getactivity() instead of rootview. So in order to make it work I changed those two as shown
userImageFragment = (CircleImageView) view.findViewById(R.id.userImageFragment);
userNameTextFragment = (TextView) view.findViewById(R.id.userNameTextFragment);
nrOfSpheresFragment = (TextView) view.findViewById(R.id.nrOfSpheresFragment);
loadingLayoutFragment = (LinearLayout) view.findViewById(R.id.loadingLayoutFragment);
listview_spheresFragment = (ListView) view.findViewById(R.id.listview_spheresFragment);
nrOfLikes = (TextView)view.findViewById(R.id.nrOfLikes);
nrOfSeens = (TextView)view.findViewById(R.id.nrOfSeens);
You can set variable to fragment, witch helps you to choose content you need
private String mUrl; //url of content
//set url of content via newInstanse() method
public static UsersSpheresFragment newInstance(String dataUrl) {
UsersSpheresFragment fragment = new UsersSpheresFragment();
Bundle arguments = new Bundle();
arguments.putInt(EXTRA_KEY_ULR, dataUrl);
fragment.setArguments(arguments);
return fragment;
}
//get url in onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getArguments();
if (extras == null || !extras.containsKey(EXTRA_KEY_URL))
throw new IllegalArgumentException("missing authorId argument");
mUrl = extras.getInt(EXTRA_KEY_URL);
//load your data
webService.loadData(mUrl);
}
another variant is set type of content via newIntanse(int type) method and choose data match it type in fragment#onCreate()

Categories

Resources