getSupportFragmentManager() error in view - java

Why I am getting an error message showing change
getSupportFragmentManager() in view
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.Random;
import activity.rama.navigationtaskbartraining.R;
import activity.rama.navigationtaskbartraining.flycodialog.IOSTaoBaoDialog;
import activity.rama.navigationtaskbartraining.tabbed.Tab1Contact;
import activity.rama.navigationtaskbartraining.tabbed.Tab2Chat;
import activity.rama.navigationtaskbartraining.tabbed.Tab3Online;
import activity.rama.navigationtaskbartraining.tabbed.TabbedActivity;
import butterknife.Bind;
import cn.pedant.SweetAlert.SweetAlertDialog;
import devlight.io.library.ntb.NavigationTabBar;
import static android.content.ContentValues.TAG;
/**
* Created by GIGAMOLE on 28.03.2016.
*/
public class HorizontalCoordinatorNtbAndTabbedActivity extends Activity implements View.OnClickListener {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private ExpandableListView.OnChildClickListener view2;
private TabbedActivity.SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private FragmentActivity myContext;
private FragmentManager FragManager;
#Bind(R.id.elv)
ExpandableListView mElv;
private Context mContext = this;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horizontal_coordinator_ntb);
initUI();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void initUI() {
final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
viewPager.setAdapter(new PagerAdapter() {
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(final View view, final Object object) {
return view.equals(object);
}
#Override
public void destroyItem(final View container, final int position, final Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0) {
try{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.tabbed_main, null, false);
container.addView(view);
final Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
toolbar.setOnClickListener(HorizontalCoordinatorNtbAndTabbedActivity.this);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new TabbedActivity.SectionsPagerAdapter(getActivity().getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) view.findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
return view;
} catch (ClassCastException e) {
Log.d(TAG, "Can't get the fragment manager with this");
return null;
}
}else if (position == 2) {
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp_list, null, false);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(
getBaseContext(), LinearLayoutManager.VERTICAL, false
)
);
recyclerView.setAdapter(new RecycleAdapter());
container.addView(view);
return view;
} else if (position == 4) {
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.test, null, false);
container.addView(view);
final TextView txt_test = (TextView) view.findViewById(R.id.txt_test);
txt_test.setOnClickListener(HorizontalCoordinatorNtbAndTabbedActivity.this);
return view;
} else {
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
}
});
final String[] colors = getResources().getStringArray(R.array.default_preview);
final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_first),
Color.parseColor(colors[0]))
.title("MyHeart")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_second),
Color.parseColor(colors[1]))
.title("Cup")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_third),
Color.parseColor(colors[2]))
.title("Diploma")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_fourth),
Color.parseColor(colors[3]))
.title("Flag")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_fifth),
Color.parseColor(colors[4]))
.title("Medal")
.build()
);
navigationTabBar.setModels(models);
navigationTabBar.setViewPager(viewPager, 2);
//IMPORTANT: ENABLE SCROLL BEHAVIOUR IN COORDINATOR LAYOUT
navigationTabBar.setBehaviorEnabled(true);
navigationTabBar.setOnTabBarSelectedIndexListener(new NavigationTabBar.OnTabBarSelectedIndexListener() {
#Override
public void onStartTabSelected(final NavigationTabBar.Model model, final int index) {
}
#Override
public void onEndTabSelected(final NavigationTabBar.Model model, final int index) {
model.hideBadge();
}
});
navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
}
#Override
public void onPageScrollStateChanged(final int state) {
}
});
final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.parent);
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
for (int i = 0; i < navigationTabBar.getModels().size(); i++) {
final NavigationTabBar.Model model = navigationTabBar.getModels().get(i);
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
final String title = String.valueOf(new Random().nextInt(15));
if (!model.isBadgeShowed()) {
model.setBadgeTitle(title);
model.showBadge();
} else model.updateBadgeTitle(title);
}
}, i * 100);
}
coordinatorLayout.postDelayed(new Runnable() {
#Override
public void run() {
final Snackbar snackbar = Snackbar.make(navigationTabBar, "Coordinator NTB", Snackbar.LENGTH_SHORT);
snackbar.getView().setBackgroundColor(Color.parseColor("#9b92b3"));
((TextView) snackbar.getView().findViewById(R.id.snackbar_text))
.setTextColor(Color.parseColor("#423752"));
snackbar.show();
}
}, 1000);
Toast.makeText(HorizontalCoordinatorNtbAndTabbedActivity.this, "fab Button Click Event", Toast.LENGTH_SHORT).show();
}
});
final CollapsingToolbarLayout collapsingToolbarLayout =
(CollapsingToolbarLayout) findViewById(R.id.toolbar);
collapsingToolbarLayout.setExpandedTitleColor(Color.parseColor("#009F90AF"));
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.parseColor("#9f90af"));
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("HorizontalCoordinatorNtb Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.item_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.txt.setText(String.format("Navigation Item #%d", position));
}
#Override
public int getItemCount() {
return 20;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txt;
public ViewHolder(final View itemView) {
super(itemView);
txt = (TextView) itemView.findViewById(R.id.txt_vp_item_list);
}
}
}
// #Override
public void onClick(final View v) {
ViewCompat.animate(v)
.setDuration(200)
.scaleX(0.9f)
.scaleY(0.9f)
.setInterpolator(new HorizontalCoordinatorNtbAndTabbedActivity.CycleInterpolator())
.setListener(new ViewPropertyAnimatorListener() {
#Override
public void onAnimationStart(final View view) {
// Toast.makeText(HorizontalNtbActivity.this, "function onAnimationStart()",
// Toast.LENGTH_LONG).show();
// Log.d("function onAnimationStart", "function");
}
#Override
public void onAnimationEnd(final View view) {
switch (v.getId()) {
case R.id.txt_test:
// startActivity(
// new Intent(HorizontalNtbActivity.this, SamplesNtbActivity.class)
// );
Toast.makeText(HorizontalCoordinatorNtbAndTabbedActivity.this, "Test Button Click Event",
Toast.LENGTH_LONG).show();
//Toast.m
new SweetAlertDialog(HorizontalCoordinatorNtbAndTabbedActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
.setTitleText("Sweet!")
.setContentText("Here's a custom image test.")
.setCustomImage(R.drawable.custom_img)
.show();
final IOSTaoBaoDialog dialog = new IOSTaoBaoDialog(HorizontalCoordinatorNtbAndTabbedActivity.this, (View) view2);
dialog.show();
break;
default:
break;
}
}
#Override
public void onAnimationCancel(final View view) {
}
})
.withLayer()
.start();
}
private class CycleInterpolator implements android.view.animation.Interpolator {
private final float mCycles = 0.5f;
#Override
public float getInterpolation(final float input) {
return (float) Math.sin(2.0f * mCycles * Math.PI * input);
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1Contact tab1Contact = new Tab1Contact();
return tab1Contact;
case 1:
Tab2Chat tab2Chat = new Tab2Chat();
return tab2Chat;
case 2:
Tab3Online tab3Online = new Tab3Online();
return tab3Online;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "CONTACT";
case 1:
return "CHAT";
case 2:
return "ONLINE";
}
return null;
}
}
}
Thank you very much

Your activity doesn't extend FragmentActivity from the support library, therefore you cannot call this method.
So you need something like that:
public class HorizontalCoordinatorNtbAndTabbedActivity extends FragmentActivity implements View.OnClickListener {
and then cast:
((HorizontalCoordinatorNtbAndTabbedActivity)getActivity()).getSupportFragmentManager()
Plus ViewPager inside ViewPager - it's not a good idea.

Try to use FragmentStatePagerAdapter instead of FragmentPagerAdapter. It could and possibly solve some possible problems.
Pass SupportFrogmentManager to FragmentStatePagerAdapter if inside it you are using fragments from support library. In other case - pass FragmentManager.
Depending on your view hierarchy you can try to get ChildFragmentManager.
Try to move ViewPager from fragment to activity.

Related

SetOnClickListener Not Working When Button Clicked in Fragment

I have a button inside a fragment that is inside an activity. The fragment contains Edittext for user to enter input then press a button and some action is processed. When I click the button I don't even see Log.v output on my logcat tab. That means android is not detecting the onClickListener event. I wonder if is because that event needs to happen in the activity thread and the fragment works in another thread. If someone could clarify how to get this working?
Activity
public class TracerouteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_traceroute);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
Fragment
package org.pctechtips.netdroid.traceroute;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
public class TraceRouteFragment extends Fragment {
public static final String tag = "TraceroutePing";
public static final String INTENT_TRACE = "INTENT_TRACE";
private Button buttonLaunch;
private EditText editTextPing;
private ProgressBar progressBarPing;
private ListView listViewTraceroute;
private TraceListAdapter traceListAdapter;
protected ProgressDialog scanProgressDialog;
private TracerouteWithPing tracerouteWithPing;
private final int maxTtl = 40;
private List<TracerouteContainer> traces;
/**
* onCreate, init main components from view
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.traceroute, container, false);
this.tracerouteWithPing = new TracerouteWithPing(this);
this.traces = new ArrayList<TracerouteContainer>();
this.buttonLaunch = (Button) view.findViewById(R.id.buttonLaunch);
this.editTextPing = (EditText) view.findViewById(R.id.editTextPing);
this.listViewTraceroute = (ListView) view.findViewById(R.id.listViewTraceroute);
this.progressBarPing = (ProgressBar) view.findViewById(R.id.progressBarPing);
traceListAdapter = new TraceListAdapter(getContext());
listViewTraceroute.setAdapter(traceListAdapter);
buttonLaunch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editTextPing.getText().length() == 0) {
Toast.makeText(getContext(), getString(R.string.no_text_trace), Toast.LENGTH_SHORT).show();
} else {
traces.clear();
traceListAdapter.notifyDataSetChanged();
startProgressBar();
hideSoftwareKeyboard(editTextPing);
tracerouteWithPing.executeTraceroute(editTextPing.getText().toString(), maxTtl);
}
Log.v(tag, "traceroute to " + editTextPing.getText().toString());
}
});
return view;
}
/**
* initView, init the main view components (action, adapter...)
*/
private void initView() {
}
/**
* Allows to refresh the listview of traces
*/
/*public void refreshList(TracerouteContainer trace) {
final TracerouteContainer fTrace = trace;
runOnUiThread(new Runnable() {
#Override
public void run() {
traces.add(fTrace);
traceListAdapter.notifyDataSetChanged();
}
});
}*/
/**
* The adapter of the listview (build the views)
*/
public class TraceListAdapter extends BaseAdapter {
private Context context;
public TraceListAdapter(Context c) {
context = c;
}
public int getCount() {
return traces.size();
}
public TracerouteContainer getItem(int position) {
return traces.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// first init
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.item_list_trace, null);
TextView textViewNumber = (TextView) convertView.findViewById(R.id.textViewNumber);
TextView textViewIp = (TextView) convertView.findViewById(R.id.textViewIp);
TextView textViewTime = (TextView) convertView.findViewById(R.id.textViewTime);
ImageView imageViewStatusPing = (ImageView) convertView.findViewById(R.id.imageViewStatusPing);
// Set up the ViewHolder.
holder = new ViewHolder();
holder.textViewNumber = textViewNumber;
holder.textViewIp = textViewIp;
holder.textViewTime = textViewTime;
holder.imageViewStatusPing = imageViewStatusPing;
// Store the holder with the view.
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
TracerouteContainer currentTrace = getItem(position);
if (position % 2 == 1) {
convertView.setBackgroundResource(R.drawable.table_odd_lines);
} else {
convertView.setBackgroundResource(R.drawable.table_pair_lines);
}
if (currentTrace.isSuccessful()) {
holder.imageViewStatusPing.setImageResource(R.drawable.ic_check_green_24dp);
} else {
holder.imageViewStatusPing.setImageResource(R.drawable.ic_close_red_24dp);
}
holder.textViewNumber.setText(position + "");
holder.textViewIp.setText(currentTrace.getHostname() + " (" + currentTrace.getIp() + ")");
holder.textViewTime.setText(currentTrace.getMs() + "ms");
return convertView;
}
// ViewHolder pattern
class ViewHolder {
TextView textViewNumber;
TextView textViewIp;
TextView textViewTime;
ImageView imageViewStatusPing;
}
}
/**
* Hides the keyboard
*
* #param currentEditText The current selected edittext
*/
public void hideSoftwareKeyboard(EditText currentEditText) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(currentEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
public void startProgressBar() {
progressBarPing.setVisibility(View.VISIBLE);
getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
scanProgressDialog = new ProgressDialog(getContext(), R.style.NewDialog);
scanProgressDialog.setCancelable(false);
scanProgressDialog.getWindow().setGravity(Gravity.CENTER);
scanProgressDialog.setTitle("Tracing.... Please wait");
scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
scanProgressDialog.show();
}
public void stopProgressBar() {
// progressBarPing.setVisibility(View.GONE);
// getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
scanProgressDialog.dismiss();
}
#Override
public void onPause() {
super.onPause();
}
}
In your buttonLaunch.setOnClickListener() method parameter, you have used ' new View.onClickListener(){}', you have to change this to 'new OnClickListener(){}', everything else inside it will be same.
Check out this post for more:
Android Fragment onClick button Method
It should work. Check your adapter to be sure it works fine. Also it best you show us your logs.
try using
buttonLunch = (ImageButton) getActivity().findViewById(R.id.buttonLaunch);

Retrofit RecyclerView not working in tab layout

I've been trying to implement a recycler view inside a fragment which displays parsed data using the retrofit library. Whenever I run the project the lists don't show and the monitor says "E/RecyclerView: No adapter attached; skipping layout". Here is my code:
MainActivity:
package com.example.ahmed.newsapp
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.design.widget.TabLayout;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int ACTIVITY_NUM = 0;
// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "<API KEY CENSORED>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager
());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout ob=(TabLayout) findViewById(R.id.sliding_tabs);
ob.setupWithViewPager(viewPager);
}
}
FragmentAdapter:
package com.example.ahmed.newsapp;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by ahmed on 3/22/2017.
*/
public class FragmentAdapter extends FragmentPagerAdapter {
private String tabs[]=new String[]{"Home","Family Members","Colors"};
public FragmentAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new HomeActivity();
case 1:
return new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 2;
}
}
NewsAdapter:
package com.example.ahmed.newsapp;
/**
* Created by ahmed on 27-08-17.
*/
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.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private List<News> news;
private int rowLayout;
private Context context;
public static class NewsViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
public NewsViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
movieTitle = (TextView) v.findViewById(R.id.title);
data = (TextView) v.findViewById(R.id.subtitle);
movieDescription = (TextView) v.findViewById(R.id.description);
rating = (TextView) v.findViewById(R.id.rating);
}
}
public NewsAdapter(List<News> news, Context context) {
this.news = news;
// this.rowLayout = rowLayout;
this.context = context;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_news, parent, false);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder(NewsViewHolder holder, final int position) {
holder.movieTitle.setText(news.get(position).getTitle());
holder.data.setText(news.get(position).getReleaseDate());
holder.movieDescription.setText(news.get(position).getOverview());
holder.rating.setText(news.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return news.size();
}
}
HomeActivity:
package com.example.ahmed.newsapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
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.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.ContentValues.TAG;
public class HomeActivity extends Fragment {
RecyclerView recyclerView;
private final static String API_KEY = "<API KEY CENSORED>";
NewsAdapter adapter;
List<News> news,dummy;
View rootview;
public HomeActivity() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.activity_home, container, false);
if (API_KEY.isEmpty()) {
Toast.makeText(getContext(), "Please obtain your API KEY first from themoviedb.org", Toast.LENGTH_LONG).show();
return rootview;
}
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.notifyDataSetChanged();
adapter=new NewsAdapter(news,getContext());
recyclerView.setAdapter(adapter);
// adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
#Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
return rootview;
}
}
i think the problem is in your FragmentAdapter class
just remove return null; statement from your FragmentAdapter like below code
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch(position){
case 0:
fragment= new HomeActivity();
case 1:
fragment= new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return fragment;
}
change this
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
You don't need to recreate your adapter when you receive response.
It may looks like:
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new NewsAdapter(null, getActivity());
recyclerView.setAdapter(adapter);
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
...
And in NewsAdapter:
...
public void setData(Collection<News> newData) {
news.clear();
news.addAll(newData);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return news == null ? 0 : news.size();
}
...

RecyclerView not updating when database changes

I am using Sugar ORM to implement Data Persistence in my app. I am displaying my database contents in a RecyclerView. The problem is SugarORM doesn't have loaders so there is no way to refresh the RecyclerView with fresh data after adding/deleting an entry to the database. I have worked around the issue for phones by reinitializing my Adapter in OnResume() and displaying it in the Recycler View. But for Tablets, the logic isn't working because the Fragment never goes to OnPause.
I need to update my the RecyclerView in my FavouritesFragment when I remove an entry in my DetailsFragment
Here's the Github link https://github.com/Hackertronix/Project-Motion/tree/Stage_2
Here's the code for both fragments
FavoritesFragment.java
package com.execube.genesis.views.fragments;
import android.app.ActivityOptions;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
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.ImageView;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.utils.API;
import com.orm.SugarRecord;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Prateek Phoenix on 6/7/2016.
*/
public class FavouritesFragment extends Fragment {
public static final String TAG= "FAVOURITES";
private static final String FAVOURITE_MOVIES_ARRAY = "favourite_movies";
private List<Movie> mMovies=new ArrayList<>();
private RecyclerView mFavouritesRecyclerView;
ArrayList<Movie> moviesArrayList;
private FavouritesAdapter mAdapter;
private TabLayout mTabLayout;
public FavouritesFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
Log.v(TAG,"In OnCreate()");
super.onCreate(savedInstanceState);
}
#Override
public void onPause() {
Log.v(TAG,"OnPause() Called");
super.onPause();
}
#Override
public void onResume() {
/* Sugar ORM does not have a Loader
so to refresh the recyclerview adapter I am reinitializing it*/
Log.v(TAG,"OnResume() Called");
mMovies=Movie.listAll(Movie.class);
mAdapter=new FavouritesAdapter();
mFavouritesRecyclerView.setAdapter(mAdapter);
mFavouritesRecyclerView.invalidate();
super.onResume();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG,"In OnCreateView()");
View view = inflater.inflate(R.layout.fragment_favourites,container,false);
mFavouritesRecyclerView=(RecyclerView)view.findViewById(R.id.favourites_recyclerview);
if(savedInstanceState!=null&&savedInstanceState.containsKey(FAVOURITE_MOVIES_ARRAY))
{
Log.v(TAG,"Restoring State");
mMovies=savedInstanceState.getParcelableArrayList(FAVOURITE_MOVIES_ARRAY);
}
else {
mMovies= Movie.listAll(Movie.class);
}
if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mFavouritesRecyclerView.setLayoutManager(new
GridLayoutManager(getActivity(), 2));
}
else{
mFavouritesRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
}
mAdapter= new FavouritesAdapter();
mFavouritesRecyclerView.setAdapter(mAdapter);
mFavouritesRecyclerView.invalidate();
return view;
}
private class FavouritesHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private ImageView mPosterImageView;
private Movie mMovie;
public FavouritesHolder(View itemView) {
super(itemView);
mPosterImageView=(ImageView)itemView.findViewById(R.id.poster);
itemView.setOnClickListener(this);
}
public void bind(Movie movie)
{
mMovie=movie;
Picasso mPicasso= Picasso.with(getActivity());
mPicasso.setIndicatorsEnabled(true);
mPicasso.load(API.IMAGE_URL+API.IMAGE_SIZE_500+mMovie.getPosterPath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(mPosterImageView);
}
#Override
public void onClick(View v) {
ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(getActivity(),mPosterImageView,"posterImage");
((openDetailsListener)getActivity()).openDetails(mMovie,options);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
moviesArrayList=new ArrayList<>(mMovies);
Log.v(TAG,"Saving State");
outState.putParcelableArrayList(FAVOURITE_MOVIES_ARRAY,moviesArrayList);
super.onSaveInstanceState(outState);
}
private class FavouritesAdapter extends RecyclerView.Adapter<FavouritesHolder>
{
#Override
public FavouritesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.movie_item,parent,false);
return new FavouritesHolder(view);
}
#Override
public void onBindViewHolder(FavouritesHolder holder, int position) {
Movie movie= mMovies.get(position);
holder.bind(movie);
}
#Override
public int getItemCount() {
return mMovies.size();
}
}
public interface openDetailsListener{
void openDetails(Movie movie,ActivityOptions options);
}
}
DetailsFragment.java
package com.execube.genesis.views.fragments;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.model.Review;
import com.execube.genesis.model.Trailer;
import com.execube.genesis.utils.API;
import com.execube.genesis.utils.JSONParser;
import com.execube.genesis.utils.OkHttpHandler;
import com.orm.SugarRecord;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
import static com.execube.genesis.R.drawable.ic_favorite_black_24dp;
/**
* Created by Prateek Phoenix on 4/30/2016.
*/
public class DetailsFragment extends Fragment {
private static final String TAG = "DETAILS";
private static final int DEFAULT_NUM_COLORS = 5;
private Movie mMovie;
private Movie entry,tempMovie;
private List<Movie> movie;
public Intent intent;
private TextView mDetailTitle;
private TextView mReleaseDate;
private TextView mOverview;
private TextView mOverviewHeader;
private TextView mReviesHeader;
private TextView mTrailersHeader;
private ImageView mBackdrop;
private Toolbar mToolbar;
private RatingBar mRatingBar;
private ArrayList<Review> mReviews=new ArrayList<>();
private ArrayList<Trailer> mTrailers=new ArrayList<>();
public static final String MOVIE_REVIEWS_ARRAY ="movie_details";
private static final String MOVIE_TRAILERS_ARRAY = "movie_reviews";
private Typeface fontBold;
private Typeface fontMediumLight;
private Typeface fontMedium;
private RecyclerView mReviewRecyclerView;
private RecyclerView mTrailerRecyclerView;
private ProgressBar mReviewsProgressbar;
private ProgressBar mTrailersProgressbar;
private CoordinatorLayout mCoordinatorLayout;
private CardView mReviewsCardView;
private FloatingActionButton mFloatingActionButton;
private ReviewsAdapter mReviewAdapter;
private int NumOfReviews;
private TrailersAdapter mTrailerAdapter;
private String id;
private boolean isFav;
public DetailsFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.v(TAG,"Saving state in onSaveInstanceState");
outState.putParcelableArrayList(MOVIE_REVIEWS_ARRAY,mReviews);
outState.putParcelableArrayList(MOVIE_TRAILERS_ARRAY,mTrailers);
super.onSaveInstanceState(outState);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
mBackdrop = (ImageView) view.findViewById(R.id.details_poster);
mDetailTitle = (TextView) view.findViewById(R.id.detail_title_text);
mReleaseDate = (TextView) view.findViewById(R.id.release_date);
mOverview = (TextView) view.findViewById(R.id.overview);
mOverviewHeader = (TextView) view.findViewById(R.id.overview_header);
mReviesHeader=(TextView)view.findViewById(R.id.review_header);
mTrailersHeader=(TextView)view.findViewById(R.id.trailer_header);
mRatingBar = (RatingBar) view.findViewById(R.id.movie_rating);
mCoordinatorLayout=(CoordinatorLayout)view.findViewById(R.id.coordinator_layout);
mReviewRecyclerView= (RecyclerView)view.findViewById(R.id.review_recycler_view);
mTrailerRecyclerView=(RecyclerView)view.findViewById(R.id.trailer_recycler_view);
mReviewsProgressbar=(ProgressBar)view.findViewById(R.id.reviews_progressbar);
mTrailersProgressbar=(ProgressBar)view.findViewById(R.id.trailers_progressbar);
mFloatingActionButton=(FloatingActionButton)view.findViewById(R.id.fab);
mReviewsCardView= (CardView) view.findViewById(R.id.reviews_card);
intent = getActivity().getIntent();
Bundle bundle=getArguments();
mMovie=bundle.getParcelable("PARCEL");
tempMovie=mMovie;
id = String.valueOf(mMovie.getMovieId());
checkFav();
mFloatingActionButton.show();
assert mMovie != null;
//PREPPING THE URL FOR QUERY
String reviewQueryUrl = API.MOVIES_BASE_URL + id + "/reviews" + API.API_KEY;
String trailerQueryUrl = API.MOVIES_BASE_URL + id + "/videos" + API.API_KEY;
mDetailTitle.setText(mMovie.getTitle());
mReleaseDate.setText(mMovie.getReleaseDate());
mRatingBar.setProgress((int) mMovie.getVoteAverage());
mOverview.setText(mMovie.getOverview());
if (Build.VERSION.SDK_INT != 21) {
fontBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Bold.ttf");
fontMedium = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Medium.ttf");
fontMediumLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Book_.ttf");
mDetailTitle.setTypeface(fontBold);
mReleaseDate.setTypeface(fontMedium);
mOverview.setTypeface(fontMediumLight);
mOverviewHeader.setTypeface(fontBold);
mReviesHeader.setTypeface(fontBold);
mTrailersHeader.setTypeface(fontBold);
}
//FETCHING JSON HERE
if(savedInstanceState!=null&&savedInstanceState.containsKey(MOVIE_REVIEWS_ARRAY))
{
Log.v(TAG,"Restoring from bundle");
mReviews=savedInstanceState.getParcelableArrayList(MOVIE_REVIEWS_ARRAY);
mTrailers=savedInstanceState.getParcelableArrayList(MOVIE_TRAILERS_ARRAY);
mReviewsProgressbar.setVisibility(View.GONE);
mTrailersProgressbar.setVisibility(View.GONE);
}
else {
OkHttpHandler reviewsHandler = new OkHttpHandler(reviewQueryUrl, reviewsCallback);
reviewsHandler.fetchData();
OkHttpHandler trailersHandler= new OkHttpHandler(trailerQueryUrl, trailersCallback);
trailersHandler.fetchData();
}
Picasso.with(getActivity()).load(API.IMAGE_URL + API.IMAGE_SIZE_500 + mMovie.getPosterPath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(mBackdrop);
getActivity().startPostponedEnterTransition();
mReviewRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mReviewAdapter= new ReviewsAdapter();
mReviewRecyclerView.setAdapter(mReviewAdapter);
LinearLayoutManager layoutmanager= new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
mTrailerRecyclerView.setLayoutManager(layoutmanager);
mTrailerAdapter= new TrailersAdapter();
mTrailerRecyclerView.setAdapter(mTrailerAdapter);
return view;
}
private void checkFav() {
movie=new ArrayList<>();
movie=SugarRecord.find(Movie.class,"m_id=?",id);
if(movie.size()==0)
{
Log.v(TAG,"Null");
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
}
else {
Log.v(TAG,"NOT Null");
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_black_24dp);
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movie=SugarRecord.find(Movie.class,"m_id=?",id);
if(movie.size()>0)
{
entry = movie.get(0);
entry.delete();
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
Snackbar snackbar = Snackbar.make(mCoordinatorLayout,"Movie removed from Favourites!!",Snackbar.LENGTH_SHORT);
View view= snackbar.getView();
TextView textView = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
else
{
entry = tempMovie;
entry.save();
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_black_24dp);
Snackbar snackbar = Snackbar.make(mCoordinatorLayout,"Movie added to Favourites!!",Snackbar.LENGTH_SHORT);
View view= snackbar.getView();
TextView textView = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
});
}
//OKHTTP CALLBACK FOR NETWORK CALL
private okhttp3.Callback reviewsCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String JSONData= response.body().string();
JSONObject jsonObject = new JSONObject(JSONData);
NumOfReviews = jsonObject.getInt("total_results");
JSONParser parser = new JSONParser();
Log.v(TAG,JSONData);
mReviews=parser.parseReviews(JSONData);
} catch (JSONException e) {}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(mReviewAdapter!=null)
{
mReviewsProgressbar.setVisibility(View.GONE);
mReviewAdapter.notifyDataSetChanged();
}
}
});
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (NumOfReviews==0)
{
mReviewsCardView.setVisibility(View.INVISIBLE);
}
}
});
}
};
private okhttp3.Callback trailersCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String json1= response.body().string();
JSONParser parser= new JSONParser();
Log.v(TAG, json1);
mTrailers = parser.parseTrailers(json1);
} catch (JSONException e) {}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(mTrailerAdapter!=null)
{
mTrailersProgressbar.setVisibility(View.GONE);
mTrailerAdapter.notifyDataSetChanged();
}
}
});
}
};
private class ReviewViewHolder extends RecyclerView.ViewHolder{
private TextView mAuthorText;
private TextView mReviewText;
private Review mReview;
public ReviewViewHolder(View itemView) {
super(itemView);
mAuthorText= (TextView) itemView.findViewById(R.id.author_textview);
mReviewText= (TextView) itemView.findViewById(R.id.review_textview);
}
public void bind(Review review)
{
mReview= review;
mAuthorText.setText(mReview.getAuthor());
mReviewText.setText(mReview.getContent());
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
{
mAuthorText.setTypeface(fontBold);
mReviewText.setTypeface(fontMediumLight);
}
}
}
private class ReviewsAdapter extends RecyclerView.Adapter<ReviewViewHolder>{
#Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.review_item,parent,false);
return new ReviewViewHolder(view);
}
#Override
public void onBindViewHolder(ReviewViewHolder holder, int position) {
Review review= mReviews.get(position);
holder.bind(review);
}
#Override
public int getItemCount() {
if(mReviews==null)
{ return 0;}
else
{return mReviews.size();}
}
}
private class TrailerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mTrailerThumbnail;
private Trailer mTrailer;
public TrailerViewHolder(View itemView) {
super(itemView);
mTrailerThumbnail=(ImageView)itemView.findViewById(R.id.trailer_thumbnail);
itemView.setOnClickListener(this);
}
public void bind(Trailer trailer)
{
mTrailer=trailer;
Picasso picasso =Picasso.with(getActivity());
picasso.setIndicatorsEnabled(true);
picasso.load(API.YOUTUBE_THUMBNAIL_URL+mTrailer.getKey()+API.THUMBNAIL_QUALITY)
.into(mTrailerThumbnail);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(API.YOUTUBE_TRAILER_URL+mTrailer.getKey()));
startActivity(intent);
}
}
private class TrailersAdapter extends RecyclerView.Adapter<TrailerViewHolder>
{
#Override
public TrailerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.trailer_item,parent,false);
return new TrailerViewHolder(view);
}
#Override
public void onBindViewHolder(TrailerViewHolder holder, int position) {
Trailer trailer= mTrailers.get(position);
holder.bind(trailer);
}
#Override
public int getItemCount() {
return mTrailers.size();
}
}
}
You can use an Interface to communicate between Fragments (Here's a question I asked an year ago and the accepted answer was really easy to understand).
Then, you need to call mAdapter.notifyDataSetChanged() in your callBack method.
I propose one way to solve this.
class TabletActivity extends Activity implements DetailFragment.Callback {
public void onCreate(Bundle savedInstanceState){
//Initialise fragments
}
void onItemDelete(){
// find the Master Fragment using FragmentManager;
MasterFragment f = (MasterFragment) getFragmentManager().findFragmentById();
if (f != null){
f.somethingHasChanged();
}
}
}
class DetailFragment extends Fragment {
private Callback callback;
public onAttach(Context context){
this.callback = (Context) context;
}
public void onViewCreated(View v, Bundle b){
Button b;
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
callback.onItemDelete();
}
)
}
public interface Callback {
void onItemDelete();
}
}
class MasterFragment extends Fragment {
public void somethingHasChanged(){
adapter.notifyDatasetChanged();
}
}
DetailFragment is where we initiate the changes, MasterFragment is consuming the changes. That communication is don't via the Activity. I personally don't recommend notifyAdapterChanges in OnResume() as you proposed because there is no guarantee that onResume will be call right after the changes in you data has been made.
Read more at:
https://developer.android.com/training/basics/fragments/communicating.html

SwipeView change the content of 2 pages

I've created a new activity with swipe views, and added some code.
I have now two swipeable pages, but with the same content, how can i change the content of the second swipe page.
Do I have to create a new activity or just to redirect it to another xml?
import java.util.Locale;
import android.graphics.Bitmap;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
public class ListItemClicked extends ActionBarActivity {
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_clicked);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText( extras.getString("pdate") );
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText( extras.getString("pText"));
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
// i/ndicator.setVisibility(View.INVISIBLE);
// iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
imageLoader.displayImage( extras.getString("pImage"), iconImg, options, listener);
return rootView;
}
}
}
thanks!
based on the page number you get from Placeholder Fragment you can set the new content
on your PlaceholderFragment class you can get current page position passed from newInstance method.after that, you can change your fragment content according page section number
There are many ways to do this. You don't have to create another Activity.
Below is a simple way, it rewrites your PlaceholderFragment and make it return different view in different position on onCreateView.
public static class PlaceholderFragment extends Fragment {
private int position;
public static PlaceholderFragment newInstance(int sectionNumber) {
return new PlaceholderFragment(sectionNumber);
}
public PlaceholderFragment(int sectionNumber) {
this.position = sectionNumber;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView;
switch(position){
case 1:
rootView = inflater.inflate(..);
//init view widget.
break;
case 2:
rootView = inflater.inflate(..);
//init view widget.
break;
}
return rootView;
}
}

set activities with ViewPager

I'm tring to make an app like google+ desing, with titlepager and switch between activities horizontally. I've implemnted this library for pager (https://github.com/JakeWharton/Android-ViewPagerIndicator) and it works fine. But now, I dont know how to set diferent activities.
This is my main class
package com.rbrlnx.controles;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.TitlePageIndicator;
public class ControlesDeAlcoholemiaActivity extends Activity {
static final int NUMERO_DE_PAGINAS = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Gestion del Pagindor
ViewPagerAdapter adapter = new ViewPagerAdapter( this );
ViewPager pager = (ViewPager)findViewById( R.id.viewpager );
TitlePageIndicator indicator = (TitlePageIndicator)findViewById( R.id.indicator );
pager.setAdapter( adapter );
indicator.setViewPager(pager,2);
//Gestion del ActionBar
ActionBar ab;
}
}
and this is the pageradapter
package com.rbrlnx.controles;
import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import com.viewpagerindicator.TitleProvider;
public class ViewPagerAdapter extends PagerAdapter implements TitleProvider
{
private static String[] titles = new String[]
{
"Comunes",
"Listado",
"Mapa"
};
private final Context context;
public ViewPagerAdapter( Context context )
{
this.context = context;
}
#Override
public String getTitle( int position )
{
return titles[ position ];
}
#Override
public int getCount()
{
return titles.length;
}
#Override
public Object instantiateItem( View pager, int position )
{
LinearLayout v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.comunes, null);
if (position == 0) {
v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.comunes, null);
} else if (position == 1) {
v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.listado, null);
} else {
v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.mapa, null);
}
((ViewPager) pager).addView(v, 0);
return v;
}
#Override
public void destroyItem( View pager, int position, Object view )
{
}
#Override
public boolean isViewFromObject( View view, Object object )
{
return view.equals( object );
}
#Override
public void finishUpdate( View view ) {}
#Override
public void restoreState( Parcelable p, ClassLoader c ) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate( View view ) {}
}
I can set the XML layout, but I don't know how to set the acitivy class. I think I must work with fragments but am not sure.

Categories