I'm fairly new to Android development so I ran into a problem with the onResume() method.
My code crashes when I try to write Name.setText() from within the onResume() method.
Writing the TextView from within the onPause() method works surprisingly without any problem.
How can I access this TextView from within the onResume() method?
public class Main extends Activity {
private ViewPager awesomePager;
private static int NUM_AWESOME_VIEWS = 2;
private Context cxt;
private AwesomePagerAdapter awesomeAdapter;
View v;
TextView Name;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cxt = this;
awesomeAdapter = new AwesomePagerAdapter();
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
}
#Override
protected void onResume() {
super.onResume();
Name.setText("1");
}
#Override
protected void onPause() {
super.onPause();
}
private class AwesomePagerAdapter extends PagerAdapter{
#Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
#Override
public Object instantiateItem(View collection, int position) {
View v = new View(cxt.getApplicationContext());
final LayoutInflater inflater = (LayoutInflater) cxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (position) {
case 0:
v = inflater.inflate(R.layout.subpage1, null, false);
Name = (TextView) v.findViewById(R.id.name);
break;
case 1:
v = inflater.inflate(R.layout.subpage2, null, false);
break;
default:
break;
}
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView(v);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void finishUpdate(View arg0) {}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View arg0) {}
}
}
Name must be set to null...Your app must have paused before it ever got initialized. Just check to make sure it's initialized before trying to do anything with it. You're onResume() should look like this then:
#Override
protected void onResume() {
super.onResume();
if(Name != null){
Name.setText("1");
}
}
P.S. Standard java convention is to have all variable names begin with a lower case letter. You should probably rename Name to name.
First of all, in your code you don't acquire a reference to the Name text view, so you must be getting NullPointerException.
If you fix that, it should work IMO. If it does not, tell us the exception name you get.
Related
I am writing a simple view pager test app that loads a bunch of data from a website and creates pages to display them.
For the most part the displaying is pretty much all works. However, it falls apart when I load a new set of data to display. When I get a new set, it loads all the data perfectly well however, instead of starting from view 0 it starts at a random location. It could start at the end or somewhere in the middle.
I want all the data to load from page 1, like a book. If you load a new book the book should start from page 1 not a random page.
Reloading calls
I've tried using GotCampDetails() which sets the local variable in the class.
viewPager.setCurrentItem(0);
in my fragment but it doesn't work. Also called notifydatasetchanged() on my adapter, still didn't work.
What am I missing?
public class ViewPagerFragment extends Fragment implements WebReadResultsListener {
private ArrayList<HashMap<String, String>> campDetails;
CustomPagerAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.camp_viewpager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (campDetails != null && ! campDetails.isEmpty()) {
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new CustomPagerAdapter(getActivity(), campDetails, viewPager);
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
}
}
#Override
public boolean GotCampDetails(ArrayList<HashMap<String, String>> campDetails) {
this.campDetails = campDetails;
return true;
}
#Override
public boolean GotCampList(ArrayList<HashMap<String, String>> campDetails) {
return false;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager().putFragment(outState,"fragmentInstanceSaved",getFragmentManager().findFragmentById(R.id.content));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Handle orientation changes here
}
}
Adapter:
public class CustomPagerAdapter extends PagerAdapter implements ColorChangeListener {
private ArrayList<HashMap<String, String>> campDetails;
private ViewGroup collection;
private Context mContext;
private boolean isRunning = false;
private ColorChangeListener colorChangeListener;
private int color= pink;
private int currentposition;
private ViewPager viewPager;
public CustomPagerAdapter(Context context, final ArrayList<HashMap<String, String>> campDetails, ViewPager viewPager) {
this.campDetails=campDetails;
this.mContext = context;
this.viewPager = viewPager;
colorChangeListener = (ColorChangeListener) mContext;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
currentposition = pos;
if (campDetails.get(currentposition).get("color").equals("green")) {
color = green;
} else {
color = pink;
}
ColorAppBar(color);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public Object instantiateItem(ViewGroup collection, final int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.child_item, collection, false);
if (campDetails.size() <= 0) {
Toast.makeText(mContext, "Error in getting camp details", Toast.LENGTH_SHORT).show();
return null;
}
if (campDetails.get(position).get("description").equals("RD") ) {
layout.setBackgroundColor(mContext.getResources().getColor(green));
} else {
layout.setBackgroundColor(mContext.getResources().getColor(pink));
}
collection.addView(layout);
this.collection = collection;
TextView eName = (TextView) layout.findViewById(R.id.en);
TextView nEName= (TextView) layout.findViewById(R.id.nen);
TextView textView6 = (TextView) layout.findViewById(R.id.textView6);
// ImageView nextImg = (ImageView) groupLayout.get(index).findViewById(R.id.nextImg);
eName.setText(campDetails.get(position).get("name"));
if (position+1 < campDetails.size()) {
nEName.setText(campDetails.get(position+1).get("name"));
textView6.setVisibility(View.VISIBLE);
} else {
nEName.setText("You are DONE!!");
textView6.setVisibility(View.INVISIBLE);
}
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return campDetails.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
return campDetails.get(position).get("name");
}
#Override
public void ColorAppBar(int color) {
colorChangeListener.ColorAppBar(color);
}
}
I finally managed to get it done.
I had to delay the function call setCurrentItem by a few milliseconds. Race condition? I don't know why this is the case but now it works perfectly.
Here is what I added in case someone else may find it useful:
pager.postDelayed(new Runnable() {
#Override
public void run() {
pager.setCurrentItem(pos);
}
}, 100);
I'm having trouble following the details well enough to pinpoint the problem, but this guy seems to have accomplished what you're trying to do: dynamically add and remove view to viewpager
hope it helps
i have problem with using Butterknife libray. There is I have SearchActivity.class use ViewPager with 3 Fragment in FragmentSearchAdapter:
SearchActivity.class
mAdapter = new FragmentSearchAdapter(getSupportFragmentManager(), SearchActivity.this);
mAdapter.addFragment("search histori");
mAdapter.addFragment("search query");
mAdapter.addFragment("search result");
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int currentIndex) {
if(currentIndex==2) {
SearchResultFragment SearchResultFragment = (SearchResultFragment) mAdapter.getItem(2);
if (SearchResultFragment != null) {
SearchResultFragment.setDescription("Text 1","Text 2");
}
}
}
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
});
FragmentSearchAdapter.class
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
SearchHistoryFragment search_histori = new SearchHistoryFragment();
return search_histori;
case 1:
SearchQueryFragment search_query = new SearchQueryFragment();
return search_query;
case 2:
SearchResultFragment search_result = new SearchResultFragment();
return search_result;
}
return null;
}
Where one fragment is SearchResultFragment.Class
public class SearchResultFragment extends Fragment {
#Bind(R.id.text1)
TextView text1;
#Bind(R.id.text2)
TextView text2;
private String page_index;
private PageAlquranActivity activity;
public SearchResultFragment() {
}
public static SearchResultFragment newInstance(int page_index) {
SearchResultFragment fragment = new SearchResultFragment();
Bundle args = new Bundle();
args.putString(Variabel.page_index, String.valueOf(page_index));
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
page_index = getArguments().getString(Variabel.page_index);
}
activity = (PageAlquranActivity) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search_result, container, false);
ButterKnife.bind(this, v);
return v;
}
public void setDescription(String s1, String s2) {
text1.setText(s1);
text2.setText(s2);
}
#Override
public void onAttach(Context context) {super.onAttach(context);}
#Override
public void onDetach() {
super.onDetach();
}
}
My Problem : when call method SearchResultFragment.setDescription("Text 1","Text 2"); from SearchActivity, I get error :
null object reference
each TextView. This error if use ButterKnife,but if not, it's work if I declare View like this :
text1 = rootView.findViewById(R.id.text1);
text2 = rootView.findViewById(R.id.text2);
in onCreateView.
so how to solve it ? Sorry for my English. Thanks.
#AmayDiam you need to bind ButterKnife again in the called method. Pass along the dependency for the bind - the fragment view from the OnPageChangeListener
SearchActivity.class
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int currentIndex)
{
if(currentIndex==2)
{
SearchResultFragment SearchResultFragment = (SearchResultFragment) mAdapter.getItem(2);
if (SearchResultFragment != null)
{
SearchResultFragment.setDescription(mPager.getChildAt(currentIndex)"Text 1","Text 2");
}
}
}
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
});
SearchResultFragment.Class
public void setDescription(View view,String s1, String s2)
{
ButterKnife.bind(this, view);
//
text1.setText(s1);
text2.setText(s2);
}
Had similar issue too, just because I've added butterknife from Android Studio's Dependency management and not by copy-pasting gradle lines from Butterknife website.
So I had to add
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
instead of just
compile 'com.jakewharton:butterknife:8.5.1'
I`m trying to implement ImageGallery on Android. I use AndroidTouchGallery library. In MainActyvity I have list of images and by clicking on them open AndroidTouchGallery. Everything work, but when open the image gallery starts with the first one.
There need to set the image position, in which to start. In this stage I have a problem. Maybe someone how to make it.
int pos ; //Picture Position
UrlPagerAdapter pagerAdapter = new UrlPagerAdapter(Full_Image_Activity.this, ArrayImgBig);
mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(pagerAdapter);
The code of UrlPageAdapter. I try to set the position in setPrimaryItem, but it still open the first image.
/**
Class wraps URLs to adapter, then it instantiates {#link UrlTouchImageView} objects to paging up through them.
*/
public class UrlPagerAdapter extends BasePagerAdapter {
public UrlPagerAdapter(Context context, List<String> resources)
{
super(context, resources);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
((GalleryViewPager)container).mCurrentView = ((UrlTouchImageView)object).getImageView();
}
#Override
public Object instantiateItem(ViewGroup collection, int position){
final UrlTouchImageView iv = new UrlTouchImageView(mContext);
iv.setUrl(mResources.get(position));
iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
collection.addView(iv, 0);
return iv;
}
}
BasePagerAdapter
/**
Class wraps URLs to adapter, then it instantiates <b>UrlTouchImageView</b> objects to paging up through them.
*/
public class BasePagerAdapter extends PagerAdapter {
protected final List<String> mResources;
protected final Context mContext;
protected int mCurrentPosition = -1;
protected OnItemChangeListener mOnItemChangeListener;
public BasePagerAdapter()
{
mResources = null;
mContext = null;
}
public BasePagerAdapter(Context context, List<String> resources)
{
this.mResources = resources;
this.mContext = context;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (mCurrentPosition == position) return;
GalleryViewPager galleryContainer = ((GalleryViewPager)container);
if (galleryContainer.mCurrentView != null) galleryContainer.mCurrentView.resetScale();
mCurrentPosition = position;
if (mOnItemChangeListener != null) mOnItemChangeListener.onItemChange(mCurrentPosition);
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view){
collection.removeView((View) view);
}
#Override
public int getCount()
{
return mResources.size();
}
#Override
public boolean isViewFromObject(View view, Object object){
return view.equals(object);
}
#Override
public void finishUpdate(ViewGroup arg0){
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1){
}
#Override
public Parcelable saveState(){
return null;
}
#Override
public void startUpdate(ViewGroup arg0) { }
public int getCurrentPosition() { return mCurrentPosition; }
public void setOnItemChangeListener(OnItemChangeListener listener) { mOnItemChangeListener = listener; }
public static interface OnItemChangeListener
{
public void onItemChange(int currentPosition);
}
}
Olso I have some other queston.
*is the "setPrimaryItem" set up the main Item(Image) witch is open first?
*is the "instantiateItem" initialise every item from the array, whitch is shows?
I made it by this:
mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(pagerAdapter);
//set position
mViewPager.setCurrentItem(pos);
Yesterday, I posted a question about the PagerAdapter and how to achieve it when using database. I managed to sorted it out, however, I do not want the viewpager to swipe/scroll left I want the opposite (swipe to right). The following is my code:
public class ScrollViewTest6 extends ActionBarAppActivity {
private ViewPager awesomePager;
private static int NUM_AWESOME_VIEWS;
private Context cxt;
private AwesomePagerAdapter awesomeAdapter;
TextView tv;
int _id;
int row_numbers;
int row_position;
private DataAdapter mySQLiteAdapter;
private Cursor cursor;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cxt = this;
awesomeAdapter = new AwesomePagerAdapter(awesomeAdapter);
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
mySQLiteAdapter = new DataAdapter(this);
mySQLiteAdapter.createDatabase();
mySQLiteAdapter.open();
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
_id = extras.getInt("id");
row_numbers = extras.getInt("row_num");
row_position = extras.getInt("row_pos");
NUM_AWESOME_VIEWS = row_numbers;
awesomePager.setCurrentItem(row_position);
cursor = mySQLiteAdapter.get_AllColumns();
this.startManagingCursor(cursor);
this.awesomePager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels){
}
#Override
public void onPageSelected(int position){
}
});
}
private class AwesomePagerAdapter extends PagerAdapter{
public AwesomePagerAdapter(PagerAdapter fm) {
}
#Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
#Override
public int getItemPosition(Object object) {return POSITION_NONE;}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater)cxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.mylayout, null);
TextView Title = (TextView)layout.findViewById(R.id.title);
if (cursor != null ) {
if (cursor.moveToPosition(position)) {
//do {
//cursor.moveToPosition(position);
String text = cursor.getString(
cursor.getColumnIndexOrThrow(DataAdapter.KEY_Title));
Title.setText(text);
}
}
((ViewPager) collection).addView(layout,0);
return layout;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==((View)object);
}
#Override
public void finishUpdate(View arg0) {
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View arg0) {
}
}
}
I know some people suggest using
setCurrentItem(int); //Last page
But that conflicts with the listview order.
e.g. Listview:
1
2
3
when we use the line above it shows 1 <- 2 <- 3 (starting from 3)
and I want 3 <- 2 <- 1 (starting from 1)
I face this issue and I resolve with this library
use it and your pagination will work right to left perfectly
it work same as ViewPager
https://github.com/diego-gomez-olvera/RtlViewPager
<com.booking.rtlviewpager.RtlViewPager
android:id="#+id/arabicViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
arabicViewPager = (ViewPager) findViewById(R.id.arabicViewPager);
adapterViewPager = new Adpt_fragmentPageAdapter(getSupportFragmentManager());
arabicViewPager.setAdapter(adapterViewPager);
tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(arabicViewPager);
Thanks to AleksG
Here is what he suggested to do which works for the required purpose, so add the following line to the list:
setCurrentItem(count - 1)
Then in the cursor you'll need to set up the list order in the cursor "_desc"
Thanks again.
One of my layouts inside of my ViewPager has a button. "R.layout.add_site". I would like the option of hitting the button and it scroll to the specific page for me. I already have the option to swipe to the specific page, but I would like to have both.
Now I'm sure there's a way to do that, but for some reason, I cannot figure it out.
You'll see that I've made an attempt , but just dont know what method to call in order to make it scroll to the desired page. Which is R.layout.main.
Here's my code.
public class fieldsActivity extends Activity {
Button addSiteButton;
Button cancelButton;
Button signInButton;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
Pager adapter = new Pager();
ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
mPager.setAdapter(adapter);
mPager.setCurrentItem(1);
addSiteButton = (Button) findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Don't know what method to call!?
}
});
cancelButton = (Button) findViewById(R.id.cancel_button);
signInButton = (Button) findViewById(R.id.sign_in_button);
}
private class Pager extends PagerAdapter {
public int getCount() {
return 3;
}
#Override
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.field01;
break;
case 1:
resId = R.layout.add_site;
break;
case 2:
resId = R.layout.main;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
}
Any help is appreciated!
call :
mPager.setCurrentItem(2);
in your onClick() method, or for a smoother scroll:
mPager.setCurrentItem(2, true);
I can't really answer WHY exactly this happens, but if you delay the setCurrentItem call for a few milliseconds it should work. My guess is that because during onResume there hasn't been a rendering pass yet, and the ViewPager needs one or something like that.
private ViewPager viewPager;
#Override
public void onResume() {
final int pos = 3;
viewPager.postDelayed(new Runnable() {
#Override
public void run() {
viewPager.setCurrentItem(pos);
}
}, 100);
}
Original Answer: here