hi i am begineer on android ,i have an app that contains a history fragment I am trying to convert my Fragment Code to Activity code !(i want to start this activity after button click) but i don't know how to do that so please help me
here's my fragment :
public class HistoryFragment extends Fragment implements MainActivity.FragmentRefresh {
ImageView ivSettings;
private FragmentActivity mContext;
private RecyclerView rvInsta;
//DB
private DBController dbcon;
private ImageRecyclerAdaptor imageRecyclerAdaptor;
public static HistoryFragment newInstance() {
//Bundle args = new Bundle();
//args.putString(ARG_PAGE, title);
HistoryFragment fragment = new HistoryFragment();
//fragment.setRetainInstance(true);
//fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Tag1","MoviesFrag");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_history, container, false);
mContext =getActivity();
//DB
dbcon = new DBController(mContext);
rvInsta= (RecyclerView) rootView.findViewById(R.id.rvInstaImages);
imageRecyclerAdaptor = new ImageRecyclerAdaptor(mContext);
rvInsta.setAdapter(imageRecyclerAdaptor);
rvInsta.setLayoutManager(new LinearLayoutManager(mContext));
rvInsta.setHasFixedSize(true);
rvInsta.setItemViewCacheSize(20);
rvInsta.setDrawingCacheEnabled(true);
rvInsta.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
//rvInsta.s/
imageRecyclerAdaptor.notifyDataSetChanged();
return rootView;
}
#Override public void refresh() {
if (imageRecyclerAdaptor!=null) {
imageRecyclerAdaptor.onRefreshh();
}
}
}
public class MainActivity extends AppCompatActivity implements FragmentRefresh{
ImageView ivSettings;
private RecyclerView rvInsta;
//DB
private DBController dbcon;
private ImageRecyclerAdaptor imageRecyclerAdaptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_history);
dbcon = new DBController(this);
rvInsta= (RecyclerView) findViewById(R.id.rvInstaImages);
imageRecyclerAdaptor = new ImageRecyclerAdaptor(this);
rvInsta.setLayoutManager(new LinearLayoutManager(this));
rvInsta.setAdapter(imageRecyclerAdaptor);
rvInsta.setHasFixedSize(true);
rvInsta.setItemViewCacheSize(20);
rvInsta.setDrawingCacheEnabled(true);
rvInsta.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
imageRecyclerAdaptor.notifyDataSetChanged();
}
#Override public void refresh() {
if (imageRecyclerAdaptor!= null) {
imageRecyclerAdaptor.onRefreshh();
}
}
}
Related
how can i implement a onRefreshListener in fragments if i am using ViewPager (ViewPager 2) with FragmentStateAdapter.
I found only examples with FragmentPageAdapter.
the other code works so far, i mean swiping between fragments an displaying a list of strings.
Just the refresh (pull from top to bottom) don't work.
I just see the refresh symbol short and then it dissapears.
In the debugger the onRefresh functions will not be called, after a refresh action.
This is my Code:
main activity
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
viewPager.setAdapter(new ViewPagerAdapter(this, dataManager));
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
viewpager
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 3;
private DataManager dataManager;
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, DataManager dataManager) {
super(fragmentActivity);
this.dataManager = dataManager;
}
#NonNull #Override public Fragment createFragment(int position) {
Fragment fragment = null;
if (position == 0)
{
fragment = new FragmentA();
Bundle bundle = new Bundle(2);
bundle.putString("TOKEN", dataManager.getToken());
bundle.putString("SERVER_URL", dataManager.getServerURL());
fragment.setArguments(bundle);
}
else if (position == 1)
{
fragment = new FragmentB();
}
else if (position == 2)
{
fragment = new FragmentC();
}
return fragment;
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
fragment
public class FragmentA extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeLayout;
private Bundle bundle;
private ListView mainListView;
private LibrariesAdapter listAdapter;
private LibraryDataManager libraryDataManager;
private RecyclerViewAdapter adapter;
private GetLibrariesTask getLibrariesTask;
private String token;
private String serverUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = getArguments();
if (bundle != null) {
token = bundle.getString("TOKEN");
serverUrl = bundle.getString("SERVER_URL");
libraryDataManager = new LibraryDataManager(token, serverUrl);
} else {
// ToDo show error or something else
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment, container, false);
swipeLayout = rootView.findViewById(R.id.swiperefresh);
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mainListView = view.findViewById(android.R.id.list);
ArrayList<Library> librariesList = new ArrayList<>();
listAdapter = new LibrariesAdapter(getActivity(), librariesList);
mainListView.setAdapter(listAdapter);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
}
});
}
private class GetLibrariesTask extends AsyncTask<Void, Void, List<Library>> {
#Override
protected List<Library> doInBackground(Void... args) {
List<Library> libraries = libraryDataManager.getLibraries();
return libraries;
}
#Override
protected void onPostExecute(List<Library> libraries) {
listAdapter.clear();
listAdapter.addAll(libraries);
listAdapter.notifyDataSetChanged();
Logger.debug("on refresh2");
// swipeLayout.setRefreshing(false);
}
}
}
I want to get value from my actvity ControlAccountPassword.java to my FragmentEditoreProfile.java, I am using view pager and tab layout, what can I use for transfer data from my activity to view pager fragment like Intent or etc.
Here is my code
ControlAccountPassword.java
public class ControlAccountPassword extends AppCompatActivity {
private TabLayout tab_Layout;
private AppBarLayout appBarLayout;
private ViewPager view_Pager;
private ImageView img1;
private String temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_p_change_p);
//Get Intent Data
Intent intent=getIntent();
temp=intent.getStringExtra("email");
tab_Layout=(TabLayout)findViewById(R.id.tabLayout);
appBarLayout=(AppBarLayout)findViewById(R.id.appBar);
view_Pager=(ViewPager)findViewById(R.id.viewPager);
img1=(ImageView)findViewById(R.id.imgBack);
//adding fragment
ViewPagerAdapter adapter=new ViewPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new FragmentEditProfile(),"Edit Profile");
adapter.AddFragment(new FragmentChangePassword(),"Change Password");
//adapter setting
view_Pager.setAdapter(adapter);
tab_Layout.setupWithViewPager(view_Pager);
//onClickListener
onClickBack(this);
}
public void onClickBack(ControlAccountPassword view){
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ControlAccountPassword.super.onBackPressed();
System.exit(1);
}
});
}
}
FragmentEditorProfile.java
public class FragmentEditProfile extends Fragment {
View view;
private ProgressDialog progress;
private String URL;
private String name,phone,email;
private GetURL getURL=new GetURL(URL);
public FragmentEditProfile() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.edit_profile,container,false);
return view;
}
public void getDataPelanggan(){
progress = new ProgressDialog(getActivity());
progress.setCancelable(false);
progress.setMessage("Loading. . .");
progress.show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getURL.GetMyURL())
.addConverterFactory(GsonConverterFactory.create())
.build();
PelangganAPI api = retrofit.create(PelangganAPI.class);
//Call<PelangganList> call = api.getPelanggan();
}}
create new class and extends Application:
public class YourClassName extends Application {
public Context context;
public static int iID;
public static String sDeviceID;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
you can change public static var's value everywhere or using vars everywhere you want:
in other class:
YourClassName.sDeviceID = "EB67";
and in another class:
int iVar;
String sVar;
iVar = YourClassName.iID;
sVar = YourClassName.sDeviceID;
I have a recyclerview in a fragment which displays a list of movies. i want to when user clicks item, it opens a new fragment which will be detailed page of that item.
I have tried bundles and intent putExtra but does not work, keeps coming up with null pointer error.
i have tried with Hardcoded strings as a test and works fine but trying to get item POJO data does not.
Anyone have an idea how to parse data between fragments from recyclerview onclick function?
1st Fragment which displays recyclerview data:
public class HomeFragment extends Fragment {
private static final String TAG = HomeFragment.class.getSimpleName();
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private MovieAdapter mAdapter;
private List<Movie> movieList;
private TextView title;
private final static String API_KEY = "670d03a721dd007862c0181bfd097e5d";
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// Inflate the layout for this fragment
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.movies_recycler_view);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
FragmentTransaction fragTrans = getFragmentManager().beginTransaction();
MovieDetail movieDetail = new MovieDetail();
//Bundle Send Data
Bundle bundle = new Bundle();
bundle.putString("title", movieList.get(position).getTitle());
movieDetail.setArguments(bundle);
fragTrans.replace(R.id.container_body, movieDetail);
fragTrans.isAddToBackStackAllowed();
fragTrans.addToBackStack(null);
fragTrans.commit();
}
}));
return rootView;
}
private void initData() {
ApiInterface api = ApiClient.getClient().create(ApiInterface.class);
Call<MovieResponse> call = api.getMostPopularMovies(API_KEY);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
int statusCode = response.code();
List<Movie> movies = response.body().getResults();
mRecyclerView.setAdapter(new MovieAdapter(movies, R.layout.list_item_movie, getContext()));
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d(TAG, t.toString());
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
Detail Fragment:
public class MovieDetail extends Fragment {
private TextView titleTv;
public MovieDetail() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// // Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movie_detail, container, false);
titleTv = (TextView) view.findViewById(R.id.detailTitleTV);
Bundle bundle = getArguments();
titleTv.setText(String.valueOf(bundle.getString("title")));
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
/**
* .
*/
}
i have looked at other questions similar but they deal with hardcoded Strings not POJO data for item click. Any help appreciated
You should create a class which extends parcelable and then pass the object in the bundle, then access each field with get methods.
i have written code for image slider but i use drawable images..
Actually i want to know, How to use online images in slideshow instead of
drawables...please help me with complete code as i am new to android..
public class DealsFragment extends Fragment {
private PagerAdapter mPagerAdapter;
public static DealsFragment newInstance() {
DealsFragment fragment = new DealsFragment();
return fragment;
}
public DealsFragment() {
// 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_deals, container, false);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(getActivity(), ImageOneDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageTwoDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageThreeDeals.class.getName()));
mPagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), fragments);
pager.setAdapter(mPagerAdapter);
return view;
}
}
ImageOneDeals.java
public class ImageOneDeals extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
if(container==null){
return null;
}
return (LinearLayout) inflater.inflate(R.layout.image1_deals,container,false);
}
}
ImagePagerAdapter.java
public class ImagePagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public ImagePagerAdapter(FragmentManager fragmentManager, List<Fragment> fragments){
super(fragmentManager);
this.fragments=fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Your Deal Fragment:-
public class DealFragment extends Fragment {
private View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(R.layout.slide_view_pager, container, false);
new GetUserImage().execute(); //run your webservices here
}
return rootView;
}
public class GetUserImage extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getActivity());
pd.setCancelable(true);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
#Override
protected String doInBackground(String... params) {
postUserImageData();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//save your data in a list
// set Adapter after you get data from webservices
mPager = (ViewPager) rootView.findViewById(R.id.slidePager);
ImagePagerAdapter viewImagePagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), TotalCount, imagearr);
mPager.setAdapter(viewImagePagerAdapter);
mPager.getCurrentItem();
}
public void postUserImageData() {
}
}
}
your Adapter:-
public class ImagePagerAdapter extends FragmentPagerAdapter {
private int numOfItemSize;
List<UserImage> arr1;
public ImagePagerAdapter (FragmentManager childFragmentManager, int num_pages, List<UserImage> customMessageListView) {
super(childFragmentManager);
this.numOfItemSize = num_pages;
this.arr1 = customMessageListView;
}
#Override
public Fragment getItem(int position) {
ImageOneDeals userImageDetailFragment = new ImageOneDeals ();
UserImage sc = arr1.get(position);
Bundle bundle = new Bundle();
bundle.putString("ProfilePic", sc.ProfilePic);
bundle.putString("Work", sc.Work);
bundle.putString("BirthTime", sc.BirthTime);
bundle.putString("Message", sc.Message);
userImageDetailFragment.setArguments(bundle);
return userImageDetailFragment;
}
#Override
public int getCount() {
return numOfItemSize;
}
}
your ImageOneDeals :-
public class ImageOneDeals extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Title = getArguments().getString("ProfilePic");
BirthTime = getArguments().getString("BirthTime");
Work = getArguments().getString("Work");
Message = getArguments().getString("Message");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = (View) inflater.inflate(R.layout.slide_user_image, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialiseViews();
}
public void initialiseViews() {
ImageView imgDetails = (ImageView) getView().findViewById(R.id.UserimageView);
TextView usrname = (TextView) getView().findViewById(R.id.userName);
TextView usrwork = (TextView) getView().findViewById(R.id.userWork);
// imgLoader.DisplayImage(Title,imgDetails);
Picasso.with(getActivity())
.load(Title)
.placeholder( R.mipmap.add_photo)
.error( R.mipmap.add_photo)
.into(imgDetails);
usrname.setText(Message);
usrwork.setText(Work);
}
}
I have a problem with comuunicating between fragments that are chnged dynamicaly, i mannaged to use the interface system to cimmunicate if the fragments are all viewble but when i am viewing them sepretly i can't use a their actions since they dont have a tag yet, any thoughts?
main activty
public class MainActivity extends FragmentActivity implements OnClickListener, Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (isSingleFragment()) {
Button btn_color = (Button) findViewById(R.id.button_color);
Button btn_text = (Button) findViewById(R.id.button_text);
Button btn_list = (Button) findViewById(R.id.button_list);
btn_color.setOnClickListener(this);
btn_list.setOnClickListener(this);
btn_text.setOnClickListener(this);
singleFragActions();
} else {
doubleFragActions();
}
// some more stuff happens
#Override
public void apply(String data) {
Log.d("data", data+"");
FragmentManager fm = getSupportFragmentManager();
Frag_list frag_list = (Frag_list) fm.findFragmentByTag("list");
//i cannot use id because the fragment in
//MainActivity are in a layout and are enterd dynamicaly
frag_list.addItem(data);
}
three fragments here, when on small screen, on is shown and three button on the top change them arrounf, if on tablet, all three are displyed, this is the interface
public interface Communicator {
public void apply(String data);
}
frag_text (first fragment)
public class Frag_text extends Fragment implements OnClickListener{
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// stuff
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
comm = (Communicator) getActivity();
}
#Override
public void onClick(View v) {
EditText input = (EditText) getView().findViewById(R.id.frag_text_edit);
TextView output = (TextView) getView().findViewById(R.id.frag_text_show);
String text_get = input.getText().toString();
output.setText("hello "+text_get+" how are you today?");
comm.apply(text_get);
}
}
frag_list (other fragment)
public class Frag_list extends Fragment{
ArrayList<String> list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_list, container, false);
list = new ArrayList<String>();
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list);
ListView lv = (ListView) view.findViewById(R.id.list_frag);
lv.setAdapter(adapter);
return view;
}
public void addItem(String data){
list.add(data);
}
}
how to i access the other fragment if it doesnt have a tag yet?
If you happen to know what fragment you will be calling then FragmentActivity could act as a mediator in this case, as it is a mere "host". You already have this Communicator interface. Have it communicate to a given fragment:
public interface Communicator {
public void apply(String data, String tag);
}
And the override:
#Override
public void apply(String data, String tag) {
FragmentManager fm = getSupportFragmentManager();
Frag_list frag_list = (Frag_list) fm.findFragmentByTag(tag);
//Fallback plan in case the fragment has not been created.
if(frag_list == null) {
frag_list = new Frag_list();
//Include the fragment for future reference.
//This fragment has no view
fm.beginTransaction().add(frag_list, tag);
}
frag_list.addItem(data);
}
And modify the fragment to always have the list available:
public class Frag_list extends Fragment{
ArrayList<String> list = new ArrayList<String>();
//...
public void addItem(String data){
//Add check to avoid problems
if(list != null) {
list.add(data);
}
}
}