i have created an app which contain number of buttons and each button is connected with number of photos (image slider (i think i am using image slider using viewerpage)) ....... it works perfectly on some devices such as 6.0.1 but when i am tring to use it on another devices such as 4.2.2 it stops immediately once i click on the butuon and here and i have done in xml (it's name tip_3)
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
and i have created another xml ( as the walk-through in the youtube ) (xml name algwhra )
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
and here is the java for (tips_3) :
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Tips_3 extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_3);
viewPager = (ViewPager) findViewById(R.id.viewPager);
AlGwhra viewPagerAdapter = new AlGwhra(this);
viewPager.setAdapter(viewPagerAdapter);
}
}
and here is the (algwhra) java :
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import javax.xml.transform.Result;
/**
* Created by Hassan on 12-Jul-17.
*/
public class AlGwhra extends PagerAdapter{
private Context context;
private LayoutInflater layoutInflater;
private Integer[] images ={R.drawable.g1,R.drawable.g2,R.drawable.g3,R.drawable.g4,R.drawable.g5,R.drawable.g6,R.drawable.g7,R.drawable.g8,R.drawable.g9,R.drawable.g10,R.drawable.g11,R.drawable.g12,R.drawable.g13};
public AlGwhra(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.algwhra, null);
ImageView imageView =(ImageView) view.findViewById(R.id.imageView2);
imageView.setImageResource(images[position]);
ViewPager vp =(ViewPager) container;
vp.addView(view ,0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp =(ViewPager) container;
View view =(View) object;
vp.removeView(view);
}
}
Related
I'm trying to implement a feature on my application, where - if you click on a RecyclerView item - it opens up a dialog box for that item with a picture - kind of like InstaGram.
However, I am trying to make an onClickListener, where I get the position of the adapter. The goal is, that it reads what item I click on, so it can open up a dialog box for that specific item. But no matter what item in the recyclerview I click on, it returns the position as being -1.
Here is my code for it:
UserAdapter.java
import android.app.Dialog;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.myndapplication.R;
import com.example.android.myndapplication.model.User;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> userList;
Dialog myDialog;
public UserAdapter(Context mContext, List<User> userList) {
this.mContext = mContext;
this.userList = userList;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_list_item, parent, false);
final ViewHolder ViewHolder = new ViewHolder(view);
ViewHolder.item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Test Click"+String.valueOf(ViewHolder.getBindingAdapterPosition()), Toast.LENGTH_SHORT).show();
}
});
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
User user = userList.get(position);
holder.imageView.setImageResource(userList.get(position).getImage());
holder.textView.setText(userList.get(position).getTitle());
}
#Override
public int getItemCount() {
return userList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private CardView item;
private CircleImageView iv_profile;
private TextView tv_username;
private TextView tv_date;
private ImageView iv_content;
private ImageView imageView;
private TextView textView;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.img_bookmarks);
textView = itemView.findViewById(R.id.title_bookmarks);
item = (CardView) itemView.findViewById(R.id.profile_item);
iv_profile = (CircleImageView) itemView.findViewById(R.id.dialog_profile_image);
tv_username = (TextView) itemView.findViewById(R.id.dialog_profile_username);
tv_date = (TextView) itemView.findViewById(R.id.dialog_profile_date);
iv_content = (ImageView) itemView.findViewById(R.id.dialog_content_image);
}
}
}
UserRecycler1.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.myndapplication.R;
import com.example.android.myndapplication.adapter.UserAdapter;
import com.example.android.myndapplication.model.User;
import java.util.ArrayList;
import java.util.List;
public class UserRecycler1 extends Fragment {
private RecyclerView recyclerView;
private UserAdapter adapter;
private List<User> userList;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userList = new ArrayList<>();
User user1 = new User(R.drawable.annapelzer, "Salad");
User user2 = new User(R.drawable.brookelark_1, "Pasta");
User user3 = new User(R.drawable.brookelark_2, "Fruit Salad");
User user4 = new User(R.drawable.brookelark_3, "Smoothies with Fruit");
User user5 = new User(R.drawable.cala, "Soup");
User user6 = new User(R.drawable.davide_cantelli, "Lobster Salad");
User user7 = new User(R.drawable.joseph_gonzales, "Breakfast toast with Berries");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
userList.add(user6);
userList.add(user7);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_recycler, container, false);
recyclerView = view.findViewById(R.id.recycler1);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
adapter = new UserAdapter(getActivity(), userList);
recyclerView.setAdapter(adapter);
return view;
}
}
MainFragmentTab.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.myndapplication.R;
import com.example.android.myndapplication.adapter.TabAdapter;
public class MainFragmentTab extends Fragment {
private TabAdapter adapter;
private TabLayout tableLayout;
private ViewPager viewPager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tabs, container, false);
viewPager = view.findViewById(R.id.request_orders_view_pager);
tableLayout = view.findViewById(R.id.request_orders_tabs);
adapter = new TabAdapter(getFragmentManager());
adapter.addFragment(new UserRecycler1(), "Public Bookmarks");
adapter.addFragment(new UserRecycler1(), "Latest Posts");
viewPager.setAdapter(adapter);
tableLayout.setupWithViewPager(viewPager);
return view;
}
}
recycler_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardCornerRadius="8dp"
android:id="#+id/profile_item">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/img_bookmarks"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/title_bookmarks"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/title2"
android:textColor="#color/dark_green"
android:padding="5dp"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
I hope you all can help, as I have tried for a while, but continue to receive the same output no matter what I do.
You have to move your setOnClickListener from onCreateViewHolder into onBindViewHolder.
You might want to check this tutorial
Edit
Something like here:
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_list_item, parent, false);
final ViewHolder ViewHolder = new ViewHolder(view);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
User user = userList.get(position);
holder.imageView.setImageResource(userList.get(position).getImage());
holder.textView.setText(userList.get(position).getTitle());
holder.item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Test Click"+userList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
I am making a tour app, it structure is like this:
First activity shows seasons like Summer, Winter, Spring, Autumn. After selecting any season, another activity pops up with locations around the world best suited for that season. After selecting any one location, another activity will pop up with 2 to 3 images with the description, and we will slide through these images. That's it. To make it more accessible, I tried adding this code to NawDrawer activity:
Debugging Error Message Image
Originally the ViewPagerAdapter.java was for Hawaii (check the image), but I created exact same as Yoshimiteadapter.java for Yosemite, but it's not working.
I apologize for the inconvenience caused by the files :) ,it's messy ,but desperate help is needed:
Link to android studio project zip file
There are total 7 java files and 12 activity files although I have an error in yosemiteadapter.Java line no 35 , error message is as follows:
04-16 12:00:09.563 12511-12511/com.example.android.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.myapplication, PID: 12511
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.example.android.myapplication.yoshimiteadapter.instantiateItem(yoshimiteadapter.java:35)
**Code for the app as follows,I have block quoted the line of error **
yoshimiteadapter.java
package com.example.android.myapplication;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by sanchitdeshmukh on 17/03/18.
*/
public class yoshimiteadapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer []images1 ={R.drawable.yosemite1,R.drawable.yoshemite2,R.drawable.yoshemite3};
private Integer []strings1 = {R.string.yoshimite};
public yoshimiteadapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.custom_layout_yos, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
imageView.setImageResource(images1[position]);
TextView textView = (TextView)view.findViewById(R.id.textView);
textView.setText(strings1[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view,0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
#Override
public int getCount() {
return images1.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
}
yosemite.java
package com.example.android.myapplication;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class yoshemite extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yoshemite);
viewPager = (ViewPager)findViewById(R.id.yoshimite);
yoshimiteadapter yoshimiteadapter = new yoshimiteadapter(this);
viewPager.setAdapter(yoshimiteadapter);
}
}
ViewPagerAdapter.java
package com.example.android.myapplication;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by sanchitdeshmukh on 17/03/18.
*/
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer []images ={R.drawable.napalicoast,R.drawable.haleakaaa,R.drawable.roadtohana};
private Integer []strings = {R.string.haleaka,R.string.napali,R.string.Paragraph_hawaii};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.custom_layout, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
TextView textView = (TextView)view.findViewById(R.id.textView);
textView.setText(strings[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
I found the solution , it's related to this:
textView.setText(strings1[position]);
I have only one string, three images, which causes the error. [position] should be set to '0'; so the modification is like this:
textView.setText(strings1[0]);
I am using a listAdapter to try to populate a listView. but i am having an issue and it is causing my application to crash. i initially wanted to populate the list into xml objects but i believe a listView would be better for my application..THIS IS MY ADAPTER
package com.example.victor.kidsrewards;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.view.LayoutInflater;
import android.widget.TextView;
import java.util.List;
/**
* Created by Victor on 3/20/2016.
*/
public class ListAdapter extends ArrayAdapter<Task> {
private final Context context;
private final List<Task> taskList;
public ListAdapter(Context context, List<Task> taskList){
super(context, R.layout.fragment_tasks, taskList);
this.context = context;
this.taskList= taskList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_tasks,parent,false);
/*TextView taskText = (TextView)rowView.findViewById(R.id.newTaskText);
taskText.setText(taskList.get(position).getText());
TextView pointsText = (TextView)rowView.findViewById(R.id.newPointsText);
pointsText.setText(taskList.get(position).getText());*/
return rowView;
}
}
**
**
this is my xml code
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:text="TODO TEXT GOES_HERE">
</ListView>
</FrameLayout>
**
**
This is my fragment where i call my listadapter
package com.example.victor.kidsrewards;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class TaskList extends ListFragment {
private TaskDataBase tdb;
public TaskList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_task_list, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tdb = new TaskDataBase(getContext());
setListAdapter(new ListAdapter(getContext(), tdb.getTasks()));
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
}
What is the name of the layout file that you have included?
If it is fragment_tasks.xml then fragment_tasks.xml should not have a ListView. It should at least have the textView with id newTaskText.
Define the content layout which contains a listView. Then there is a layout for each row. This should only contain the TextView (and other views relevant to a single row) but not ListView.
I want to load some data from a website using Jsoup in my fragment activity and show the output in the Textview. I am using AsyncTask to load the data from a website using Jsoup but after successfully getting the data from the website the onPostExecute method in AsyncTask is not displaying the data. I have tried to debug it and it seems like the there is a problem in onPostExecute
and I don't know why.
Here is my code..
MainActivity2.java
package com.example.ebad.bustudentprofile;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.example.ebad.bustudentprofile.tabs.SlidingTabLayout;
public class MainActivity2 extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// Layout manager that allows the user to flip through the pages
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// getSupportFragmentManager allows use to interact with the fragments
// MyFragmentPagerAdapter will return a fragment based on an index that is passed
viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(),
MainActivity2.this));
// Initialize the Sliding Tab Layout
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
// Connect the viewPager with the sliding tab layout
slidingTabLayout.setViewPager(viewPager);
}
}
MyFragmentPagerAdapter.java
package com.example.ebad.bustudentprofile;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = new String[]{"Tab 1", "Tab 2", "Tab 3"};
private Context context;
public MyFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return 3;
}
// Return the correct Fragment based on index
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new TabFragment1();
} else if (position == 1) {
return new TabFragment2();
} else if (position == 2) {
return new TabFragment3();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Return the tab title to SlidingTabLayout
return tabTitles[position];
}
}
TabFragment1.java
package com.example.ebad.bustudentprofile;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
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;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.util.HashMap;
public class TabFragment1 extends Fragment {
ProgressDialog progressDialoge;
TextView fa, na;
String urlw = "http://111.68.99.8/StudentProfile/PersonalInfo.aspx";
HashMap<String, String> hashMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
hashMap = Data.map;
//hashMap = (HashMap<String, String>) getArguments().get("hashMap");
View rootview = inflater.inflate(R.layout.tab_fragment_1, container, false);
Activity activity = getActivity();
fa = (TextView) rootview.findViewById(R.id.Fathere);
na = (TextView) rootview.findViewById(R.id.Y_Name);
new peea(activity,rootview).execute();
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
private class peea extends AsyncTask<Void, Void, Void> {
String father ;
String son ;
private Context activity;
private View rootView;
public peea(Context context, View main){
this.activity=context;
this.rootView=main;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialoge = new ProgressDialog(getActivity());
progressDialoge.setMessage("Getting into your information");
progressDialoge.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doce = Jsoup.connect(urlw)
.cookies(hashMap)
.get();
father = doce.select("span[id=ctl00_Body_FATHERNAME]").html();
son = doce.select("span[id=ctl00_Body_NAME]").html();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPreExecute();
TextView wa = (TextView)rootView.findViewById(R.id.Y_Name);
wa.setText(son);
/*fa.setText(father);
na.setText(son);*/
/*fa = (TextView)findViewById(R.id.das);
fa.setText(father);*/
progressDialoge.dismiss();
}
}
}
tab_fragment_1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/Fathere"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Father Name"
android:textSize="25dp" />
<TextView
android:id="#+id/Y_Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Your name"
android:textSize="30dp" />
</LinearLayout>
If you guys tell where the problem is or how to solve it, it will be very helpful to me
I don't think that your super class has an onPreExecute function, so
super.onPreExecute();
may be causing you some issues. You can try
super.onPostExecute();
That may be fix it.
I'm wondering if anyone can help me. I'm pretty new to programming and this is a little over my head, but once this issue is resolved I think I can complete the rest of my program with my current skill set (I hope). Anyway, I'm using Actionbarsherlock to create a swipe tab interface. The code I used was found on Youtube as an example of how to do it. The URL to download the source is: https://www.dropbox.com/s/p91dzt4dekuia3q/SwipeyTabs.zip if anyone wants to look. The sourcecode is available for download, but I'll post what I believe are the relevant parts here. Basically, whenever the device (and emulator) is rotated, the app crashes. If I start the device in landscape mode, it works until rotated into portrait, and if I start in portrait it works until rotated into landscape. I get a null pointer exception as the error and could provide the logcat output if needed.
The MainActivity.java file is:
package com.rufflez.swipeytabs;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class MainActivity extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Fragment 1"), Fragment_1.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Fragment 2"), Fragment_2.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Fragment 3"), Fragment_3.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Fragment 4"), Fragment_4.class, null);
}
}
The TabsAdapter.java file is:
package com.rufflez.swipeytabs;
import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener , ViewPager.OnPageChangeListener{
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final String TAG = "21st Polling:";
static final class TabInfo{
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args){
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity fa, ViewPager pager) {
super(fa.getSupportFragmentManager());
mContext = fa;
mActionBar = fa.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args){
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i = 0; i<mTabs.size(); i++){
if (mTabs.get(i) == tag){
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mContext, "You've deselected a tab", Toast.LENGTH_SHORT).show();
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
Each Fragment_#.java is basically this with the appropriate reference:
package com.rufflez.swipeytabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_1, container, false);
}
}
The activity_main.xml is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager" />
</RelativeLayout>
Each fragment_#.xml is basically this with the appropriate reference changed:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Fragment 1"/>
</LinearLayout>
From what I could figure out, doing several hours of research, is that this used to be a bug in ABS that was addressed several versions ago and likely this issue is somehow connected to that issue. Any help would be very much appreciated. Especially if you can provide it in a teacher-student style so I can learn more effectively. :-) Thanks in advance to anyone attempting to help though!