VideoView starts playing in a wrong fragment using viewpager - android

Problem: I have a viewPager with 3 fragments, the first one has a videoView. When I change to the second fragment, the video stops and when I change to the third, the same. But when I change from the third fragment to the second one, the video starts playing in the background.
I want the video to play only in the first fragment. How can i solve this problem? Thanks
Here is my code:
Activity Adapter:
import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ActivitySwipe extends AppCompatActivity implements
HomeFragment.OnFragmentInteractionListener ,
CamaraFragment.OnFragmentInteractionListener
, SearchFragment.OnFragmentInteractionListener{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
/* Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);*/
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
final HomeFragment homeFragment = new HomeFragment();
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
}
#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_activity_swipe, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Fragment newInstance(int sectionNumber) {
Fragment fragment = null;
switch (sectionNumber){
case 1 : fragment=new HomeFragment();
break;
case 2 : fragment=new CamaraFragment();
break;
case 3 : fragment=new SearchFragment();
break;
}
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activity_swipe, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* 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) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
Here is my 1st fragment:
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link HomeFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link HomeFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class HomeFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
VideoView videoview;
MediaPlayer mediap;
int position;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUserVisibleHint(false);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_home, container, false);
videoview = (VideoView) v.findViewById(R.id.video1);
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared( MediaPlayer mp) {
mp.setLooping(true);
mediap=mp;
}
});
Uri uri = Uri.parse("android.resource://" + getActivity().getPackageName() + "/" + R.raw.vid5);
videoview.setVideoURI(uri);
videoview.requestFocus();
videoview.start();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
resume();
}
else {
pause();
}
}
#Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible&&isResumed()) {
resume();
}else{
pause();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public void pause(){
//NOT videoview.pause(); Needn't save Stop position
if (mediap != null){
mediap.pause();
}
}
public void resume(){
//NOT videoview.resume();
if (mediap != null){
mediap.start(); //Video will begin where it stopped
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
And my 2nd fragment:
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CamaraFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CamaraFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CamaraFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CamaraFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CamaraFragment.
*/
// TODO: Rename and change types and number of parameters
public static CamaraFragment newInstance(String param1, String param2) {
CamaraFragment fragment = new CamaraFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_camara, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}

When you use an FragmentPagerAdapter, it pre-loads your fragments to left and right of your fragment in focus. So when you scroll from position 0 to 1 to 2, the fragment in position 0 is removed. When you then scroll back to position 1, the fragment in position 0 is re-loaded, which triggers creating the view. If you look at your HomeFragment, you trigger playing video when in OnCreateView().
To resolve this, you need to change how you trigger playing the video from when the Fragment is created to instead be activated when it scrolls into view. You are already halfway there with your empty OnPageChangeListener. You should check the position in onPageSelected() and start the video there instead of in the Fragment's OnCreateView

You have to override setUserVisibleHint method in a fragment where you play video.
public void setUserVisibleHint
#Override
public void setUserVisibleHint(boolean isVisibleToUser)
{
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible())
{
if (!isVisibleToUser)
{
//pause or stop video
} else {
//play your video
}
}
}

Related

Invoke Virtual Method on null object reference

I am trying to implement fragments for a project in Android Studio. The point of the project is to select a color from a spinner in one fragment then pass it to the parent activity and then pass it from the parent activity to the second fragment to change the background color of the second fragment. The problem I am having is my listener in the palette activity is set to null despite the fact I invoke it in the onAttach function.
This is my code for the Fragment that causes the app to crash
package edu.temple.palettecolorapp;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link PaletteFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link PaletteFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PaletteFragment extends Fragment {
private String colorArr[];
private String translationArr[];
Context parent;
private final String mParam1 = "colors";
private final String mParam2 = "translation";
public OnFragmentInteractionListener mListener;
public PaletteFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
*
* #return A new instance of fragment PaletteFragment.
*/
// TODO: Rename and change types and number of parameters
public static PaletteFragment newInstance(String colors[], String translation[]) {
PaletteFragment fragment = new PaletteFragment();
Bundle args = new Bundle();
args.putStringArray("colors", colors);
args.putStringArray("translation", translation);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.colorArr = getArguments().getStringArray(mParam1);
this.translationArr = getArguments().getStringArray(mParam2);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.parent = context;
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) parent;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
// this.parent = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_palette, container, false);
Spinner spinner = v.findViewById(R.id.spinner);
PaletteAdapter pa = new PaletteAdapter(parent,colorArr,translationArr);
spinner.setAdapter(pa);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = colorArr[position];
mListener.onColorSelection(c);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return v;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onColorSelection(String color);
}
}
This is in the main activity
package edu.temple.palettecolorapp;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
public class PaletteActivity extends AppCompatActivity implements PaletteFragment.OnFragmentInteractionListener {
PaletteFragment master;
ColorFragment subject;
FragmentTransaction ft;
private final String colors[] = {"blue", "green", "purple", "red", "gray", "cyan", "magenta", "yellow", "lime"};
private boolean isSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
Resources res = context.getResources();
String title = res.getString(R.string.palette_title);
setTitle(title);
setContentView(R.layout.activity_palette);
String translation[] = res.getStringArray(R.array.colors);
PaletteFragment master = PaletteFragment.newInstance(colors,translation);
ColorFragment subject = ColorFragment.newInstance("magenta");
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment1,master);
ft.replace(R.id.fragment2,subject);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onColorSelection(String color) {
subject.updateBackgroundColor(color);
}
}
I am having trouble in this portion of the fragment in the 'onCreateView' method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_palette, container, false);
Spinner spinner = v.findViewById(R.id.spinner);
PaletteAdapter pa = new PaletteAdapter(parent,colorArr,translationArr);
spinner.setAdapter(pa);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = colorArr[position];
mListener.onColorSelection(c);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return v;
}
The 'mListener.onColorSelection' call causes the error and this is what the output is
E/AndroidRuntime: FATAL EXCEPTION: main
Process: edu.temple.palettecolorapp, PID: 14867
java.lang.NullPointerException: Attempt to invoke virtual method 'void edu.temple.palettecolorapp.ColorFragment.updateBackgroundColor(java.lang.String)' on a null object reference
at edu.temple.palettecolorapp.PaletteActivity.onColorSelection(PaletteActivity.java:45)
at edu.temple.palettecolorapp.PaletteFragment$1.onItemSelected(PaletteFragment.java:87)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:944)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:933)
at android.widget.AdapterView.access$300(AdapterView.java:53)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:898)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Edit2: added ColorFragment 'updateBackgroundColor' method
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
* Use the {#link ColorFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ColorFragment extends Fragment {
private View v;
TextView t;
String color;
private final String KEY = "color";
public ColorFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters
* #return A new instance of fragment ColorFragment.
*/
// TODO: Rename and change types and number of parameters
public static ColorFragment newInstance() {
ColorFragment fragment = new ColorFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.color = getArguments().getString(KEY);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_color, container, false);
t = v.findViewById(R.id.textView);
t.setBackgroundColor(Color.BLACK);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
public void updateBackgroundColor(String c){ // causing problems
t.setBackgroundColor(Color.parseColor(c));
}
}
Apparently ColorFragment subject in PaletteActivity is null when calling #onColorSelection().
Please check the assignment of value for the variable and make sure it is not null.
#Override
public void onColorSelection(String color) {
subject.updateBackgroundColor(color);
}
EDIT:
change the line:
ColorFragment subject = ColorFragment.newInstance("magenta");
TO:
subject = ColorFragment.newInstance("magenta");

How use onBackPressed() inside fragment to back a webview?

#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
This code is not working inside my fragment to back the webpage in webview
Use setOnKeyListener() on your WebView to listen to any event because onBackPreesed() is not the member of a Fragment
myWebView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()==KeyEvent.ACTION_DOWN &&keyCode==KeyEvent.KEYCODE_BACK&&myWebView.canGoBack()) {
myWebView.goBack();
}
return true;
}
});
You need to attach the fragment in the corresponding activity.
after you can implement onBackPressed method from your activty
package com.cornicore.dream11statistics;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Tab1.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Tab1#newInstance} factory method to
* create an instance of this fragment.
*/
public class Tab1 extends Fragment {
AdView adView_Banner;
WebView myWebView;
ProgressBar progressBar;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Tab1() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Tab1.
*/
// TODO: Rename and change types and number of parameters
public static Tab1 newInstance(String param1, String param2) {
Tab1 fragment = new Tab1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab1, container, false);
myWebView = (WebView) v.findViewById(R.id.webViewHome);
progressBar = (ProgressBar) v.findViewById(R.id.progressBarFragment);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(false);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setDomStorageEnabled(true);
myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
myWebView.setScrollbarFadingEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
myWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
myWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
myWebView.loadUrl("https://cornicore.com/cricket-news/");
myWebView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
myWebView.loadUrl("file:///android_asset/internet.html");
}
});
myWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if (progress == 100) {
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.OnNavFragmentInteractionListener(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void OnNavFragmentInteractionListener(Uri uri);
}
public interface OnNavFragmentInteractionListener {
}
public void setInteractionListener(OnFragmentInteractionListener mListener){
this.mListener = mListener;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
}

How to create fragment interaction?

These are the imports I have for the fragment class.
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
Class being initialized
public class FragmentDemo extends Fragment {
Public constructor is empty and must stay that way
public FragmentDemo() {
}
It must be attached to an activity, the interface depends on said activity
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Inflating layout for fragment
View result = inflater.inflate(R.layout.fragment_fragment_demo, container, false);
TextView textView = (TextView)result.findViewById(R.id.textView2);
Button button = (Button)result.findViewById(R.id.button2);
textView.setText("HEY, THIS IS A TEST!");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.e("FRAGMENT", "BUTTON IS WORKING!");
// why no toast?
}
});
return result;
}
}
You must create two classes to make it more clear, one for the interaction of fragments, and a main class.
The first one should look like this:
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link InteractionFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link InteractionFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class InteractionFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_NAME = "name";
private static final String ARG_LAST_NAME = "lastName";
// TODO: Rename and change types of parameters
private String name;
private String lastName;
private OnFragmentInteractionListener mListener;
public InteractionFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment InteractionFragment.
*/
// TODO: Rename and change types and number of parameters
// Factory method
public static InteractionFragment newInstance(String param1, String param2) {
InteractionFragment fragment = new InteractionFragment();
Bundle args = new Bundle();
args.putString(ARG_NAME, param1);
args.putString(ARG_LAST_NAME, param2);
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
name = getArguments().getString(ARG_NAME);
lastName = getArguments().getString(ARG_LAST_NAME);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_interaction, container, false);
TextView nameText = (TextView)v.findViewById(R.id.name);
TextView lastNameText = (TextView)v.findViewById(R.id.last_name);
nameText.setText(name);
lastNameText.setText(lastName);
Button button = (Button)v.findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.somethingHappened("THE BUTTON WAS PRESSED, HOW EXCITING!");
}
});
return v;
}
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public void onDetach() {
super.onDetach();
mListener = null;
}
public void printALog(){
Log.wtf("PRINTING", "ITS WORKING!");
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void somethingHappened(String message);
}
}
While the second one should look like this:
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.TransactionTooLargeException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements InteractionFragment.OnFragmentInteractionListener {
InteractionFragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void addFragment(Fragment f){
// add a fragment through code
// fragment manager - the guy in charge of any fragment related logic
FragmentManager manager = getFragmentManager();
// transactions
FragmentTransaction transaction = manager.beginTransaction();
// actually do the thing
//fragment = InteractionFragment.newInstance("Juan","Perez");
// 3rd parameter - fragment
transaction.add(R.id.container, f, "dude");
transaction.commit();
}
#Override
public void somethingHappened(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public void doSomethingOnFragment(View v){
fragment.printALog();
}
public void swapFragments(View v){
FragmentManager manager = getFragmentManager();
Fragment f = manager.findFragmentByTag("dude");
if(f != null){
Toast.makeText(this, "FRAGMENT BEING REMOVED", Toast.LENGTH_SHORT).show();
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(f);
transaction.commit();
} else {
Toast.makeText(this, "NO FRAGMENT TO REMOVE", Toast.LENGTH_SHORT).show();
}
}
public void addFragment1(View v){
fragment = InteractionFragment.newInstance("Juan","Perez");
addFragment(fragment);
}
public void addFragment2(View v){
FragmentDemo fd = new FragmentDemo();
addFragment(fd);
}
}
I'm not sure to understand what is your question exactly, so I will assume first that your problem is related to your "Why no toast?" comment.
The thing is you are using the log function, this prints in logcat console, not through toasts.
If you want to display a toast, use
Toast.makeText(context, text, durationInMs).show();
More info here
I'm not sure to understand what is your question exactly, so I will assume first that your problem is related to your "Why no toast?" comment.
The thing is you are using the log function, this prints in logcat console, not through toasts.
If you want to display a toast, use
Toast.makeText(context, text, durationInMs).show();
And because you are in a Fragment the Context used is the activity which has this fragment so to get context we use getActivity(). Hence the Toast will be:
Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();

SharedPreferences STRANGE BEHAVIOUR

I am beginner at android developing and i am making very simple app that has a content inside and you can edit the font type and size of the content using settings fragment .
a problem is facing me which when i set my fonts settings it saved well. i close the app and get back to the content activity and it works very well but when i get back to the settings fragment it returns the font type JUST . to its default value.the font size stays at user determinded value .
This is settings fragment code
package com.example.ali.azkarv10;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.SwitchPreference;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link SettingsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link SettingsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SettingsFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private static final String fonts[]={"fonts/blacksugar.ttf","fonts/baghdad.ttf","fonts/bdavat.ttf","fonts/fsmetal.ttf","fonts/kufi.ttf","fonts/tachkili.ttf","fonts/yassin.ttf"};
private String mParam1;
private String mParam2;
SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
Switch switchWidget;
TextView textView;
SeekBar seekBar;
TextView tester;
Spinner spinner;
SpinnerAdapter spinnerAdapter;
private OnFragmentInteractionListener mListener;
public SettingsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment SettingsFragment.
*/
// TODO: Rename and change types and number of parameters
public static SettingsFragment newInstance(String param1, String param2) {
SettingsFragment fragment = new SettingsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
sharedPreferences=getActivity().getSharedPreferences("data",Context.MODE_PRIVATE);
edit=sharedPreferences.edit();
View v= inflater.inflate(R.layout.fragment_settings, container, false);
switchWidget=(Switch)v.findViewById(R.id.switch1);
switchWidget.setChecked(sharedPreferences.getBoolean("buzzer",false));
switchWidget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
edit.putBoolean("buzzer",true);
// Toast.makeText(getActivity(),"true",Toast.LENGTH_LONG).show();
edit.commit();
}else {
edit.putBoolean("buzzer",false).commit();
//Toast.makeText(getActivity(),"false",Toast.LENGTH_LONG).show();
}
}
});
tester=(TextView)v.findViewById(R.id.textSizeTester);
seekBar=(SeekBar)v.findViewById(R.id.seekBar);
seekBar.setProgress(sharedPreferences.getInt("fontSize",20)-10);
tester.setTextSize(seekBar.getProgress()+10);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress_Value;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress_Value=progress;
edit.putInt("fontSize",10+progress).commit();
tester.setTextSize(((float)10+progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
edit.putInt("fontSize",10+progress_Value).commit();
tester.setTextSize(((float)10+progress_Value));
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
edit.putInt("fontSize",10+progress_Value).commit();
tester.setTextSize(((float)10+progress_Value));
}
});
Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(),"fonts/blacksugar.ttf");
textView=(TextView)v.findViewById(R.id.textsets);
textView.setTypeface(typeface);
spinner=(Spinner)v.findViewById(R.id.spinner);
spinnerAdapter=new SpinnerAdapter(getActivity(),fonts);
spinner.setAdapter(spinnerAdapter);
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","fonts/fsmetal.ttf")));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:edit.putString("fontType",fonts[0]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 1:edit.putString("fontType",fonts[1]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 2:edit.putString("fontType",fonts[2]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 3:edit.putString("fontType",fonts[3]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 4:edit.putString("fontType",fonts[4]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 5:edit.putString("fontType",fonts[5]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 6:edit.putString("fontType",fonts[6]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// textView.setText(sharedPreferences.getString("fontType",""));
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
please help
onItemSelectedListener is called the first time with position = 0.
So you are overriding the preference with "fonts/blacksugar.ttf" when SettingsFragment is created.
You should get "fontType" preference and select it in the Spinner:
Spinner spinner = (Spinner) v.findViewById(R.id.spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_layout, fonts);
spinner.setAdapter(spinnerAdapter);
spinner.setSelection(spinnerAdapter.getPosition(sharedPreferences.getString("fontType","fonts/blacksugar.ttf")));
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
edit.putString("fontType",fonts[position]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(),"fonts/blacksugar.ttf");
textView=(TextView)v.findViewById(R.id.textsets);
textView.setTypeface(typeface);
I think your problem could be here. You are setting the typeface of the textview yourself and not reading from the file.
Also,
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:edit.putString("fontType",fonts[0]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 1:edit.putString("fontType",fonts[1]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 2:edit.putString("fontType",fonts[2]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 3:edit.putString("fontType",fonts[3]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 4:edit.putString("fontType",fonts[4]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 5:edit.putString("fontType",fonts[5]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 6:edit.putString("fontType",fonts[6]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
}
}
The switch statement is redundant. Just do,
edit.putString("fontType",fonts[position]).commit();

ViewPager doesn't update ImageView even when i finish its activity and start it again with different values

I'm using a Viewpager to make a scrollable photos gallery which take the photos URLs
from SQLite database depending on intent value passed from the previous activity.
My problem is : When i start this photo gallery for first time , it works correctly
but when i close it and start again with different URLs for images ,ViewPager doesn't update ImageView and page title.
This is my code :
import java.util.ArrayList;
import java.util.Locale;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
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.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
public class PhotoGalleryActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
String pid;
int photosCount;
Intent context;
SQLiteDatabase db;
static ArrayList<PlacePhoto> photos = new ArrayList<PlacePhoto>();
PlacePhoto ph;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
context = getIntent();
//if (context.getExtras().getString("pid") != null )
pid = context.getExtras().getString("pid");
//else pid="0";
photosCount = context.getExtras().getInt("photos_count");
try {
db = SQLiteDatabase.openDatabase(
"/data/data/"+getPackageName()+"/itartus.db3", null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery("select * from photos where place_id="+pid,null);
while(c.moveToNext()) {
ph = new PlacePhoto(c.getInt(0),c.getInt(1),c.getString(3),c.getString(2));
photos.add(ph);
}
}
catch(SQLiteException e){
Toast.makeText(getApplicationContext(),"حدث خطأ ما",Toast.LENGTH_LONG).show();
}
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.photo_gallery, menu);
return true;
}
/**
* 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) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return photosCount;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
return photos.get(position).photoName;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_photo_gallery_dummy, container, false);
ImageView img = (ImageView) rootView.findViewById(R.id.photo_result);
Bundle args = getArguments();
int position = args.getInt("position");
img.setTag(photos.get(position));
ImageDownloader i = new ImageDownloader(img,this.getActivity());
i.execute(photos.get(position).url);
return rootView;
}
}
}
Solved by myself
Solution is : initialize the static ArrayList photos inside onCreate() .

Categories

Resources