Android: Change text in a PagerAdapter - android

I have a MainActivity which calls a fragment (ReadStory).
ReadStory has a ViewPager which uses a PagerAdapter.
The page has an image and a TextView at the bottom. (This example only shows the TextView)
All of this works well.
There's a requirement that when the user touches/clicks the TextView various words are highlighted in red. This also works well.
The problem I have is that the text (with red highlights) is displayed on the next screen not the current visible screen.
I have set a onClickListener on the TextView which sets the relevant parts to red and then sets the text on the TextView.
The ViewPager loads the current screen plus the previous and next screens. The TextView is 'attached' to the "nextScreen".
How do I change the TextView on the current screen?
I've searched for the answer for several days but I can't seem to find an answer. Any help would be appreciated.
My code - MainActivity
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button myButton;
ReadStory RS;
// *********************************************************************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button);
myButton.setOnClickListener(textViewClickListener);
}
// *********************************************************************************************
private View.OnClickListener textViewClickListener = new View.OnClickListener() {
public void onClick(View v) {
int[] mStory_resources = {R.string.S1P0, R.string.S1P1, R.string.S1P2, R.string.S1P3, R.string.S1P4, R.string.S1P5, R.string.S1P6, R.string.S1P7,
R.string.S1P8, R.string.S1P9, R.string.S1P10, R.string.S1P11};
int mStoryWords = R.string.S1words;
RS = new ReadStory();
Bundle args = new Bundle();
args.putIntArray("Story", mStory_resources);
args.putInt("storyWords", mStoryWords);
RS.setArguments(args);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("readStory");
ft.replace(R.id.activity_main, RS);
ft.commit();
}
};
// *********************************************************************************************
}
ReadStory
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class ReadStory extends Fragment {
static String currentString = "";
static String newString = "";
private static final String story = "Story";
private static final String storyWords = "storyWords";
private int[] mStory_resources;
private int mStory_words;
ViewPager viewPager;
CustomSwipeAdapter adapter;
public ReadStory() {
// Required empty public constructor
}
// *********************************************************************************************
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mStory_resources = getArguments().getIntArray(story);
mStory_words = getArguments().getInt(storyWords);
}
}
// *********************************************************************************************
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final RelativeLayout parent = (RelativeLayout) inflater.inflate(R.layout.read_story, container, false);
viewPager = (ViewPager) parent.findViewById(R.id.view_pager);
adapter = new CustomSwipeAdapter(getActivity());
adapter.story_resources = mStory_resources;
adapter.story_words = mStory_words;
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
currentString = getString(mStory_resources[position]);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return parent;
}
// *********************************************************************************************
}
PagerAdapter
import android.content.Context;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class CustomSwipeAdapter extends PagerAdapter{
int[] story_resources;
int story_words;
private TextView textView;
private Context ctx;
CustomSwipeAdapter(Context ctx)
{
this.ctx = ctx;
}
// *********************************************************************************************
#Override
public int getCount() {
return story_resources.length;
}
// *********************************************************************************************
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==object);
}
// *********************************************************************************************
#SuppressWarnings("deprecation") // Put here as setText is deprecated as of API 16 - Jelly_bean
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater layoutInflater;
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
textView = (TextView) item_view.findViewById(R.id.image_count);
textView.setText(story_resources[position]);
textView.setOnClickListener(textViewClickListener);
container.addView(item_view);
return item_view;
}
// *********************************************************************************************
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout)object);
}
// *********************************************************************************************
#SuppressWarnings("deprecation") // Put here as fromHtml is deprecated as of API 24 - N
private View.OnClickListener textViewClickListener = new View.OnClickListener() {
public void onClick(View v) {
String patternString = "\\b(" + ctx.getString(story_words) + ")\\b";
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(ReadStory.currentString);
StringBuffer bufStr = new StringBuffer();
while (matcher.find()) {
String rep = matcher.group();
matcher.appendReplacement(bufStr, "<font color='#EE0000'>" + rep + "</font>");
}
matcher.appendTail(bufStr);
ReadStory.newString = bufStr.toString();
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(ReadStory.newString));
} else {
textView.setText(Html.fromHtml(ReadStory.newString));
}
Toast.makeText(ctx, "Clicked", Toast.LENGTH_LONG).show();
}
};
// *********************************************************************************************
}

Using
((TextView)v).setText(Html.fromHtml(ReadStory.newString));
instead of
textView.setText(Html.fromHtml(ReadStory.newString));
There is reference problem with textView object it consists reference of next item.

Related

GridView is not updating in android?

this is my main screen.Above 3 boxes are Twowayview items.upon clicking them gridview show some images,first time its loading manually but when i clicked twowayview item to change the value gridview is not updating,i debug my program i think only in adapter have problem.
here is my code
ChapterActivity.java
package com.focusmedica.bphandoab1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import org.lucasr.twowayview.TwoWayView;
import java.util.ArrayList;
/**
* Created by ashish on 11/15/2016.
*/
public class ChapterActivity extends AppCompatActivity {
ArrayList<DIctionaryContent> AppDetails=new ArrayList<>();
ArrayList<DIctionaryContent> head=new ArrayList<>();
TwoWayView twvCategory;
TextView tvHeading;
Fragment fragmentCategories;
MyDataBase handler;
DIctionaryContent content;
String url,heading;
LazyAdapter adapter;
int position=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter);
twvCategory=(TwoWayView)findViewById(R.id.twvCategory);
tvHeading=(TextView)findViewById(R.id.tvHeading);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentCategories=fragmentManager.findFragmentById(R.id.fragmentCategories);
fragmentTransaction.commit();
handler = new MyDataBase(ChapterActivity.this);
ArrayList<DIctionaryContent> chapterList = handler.getContent();
adapter=new LazyAdapter(ChapterActivity.this,chapterList);
twvCategory.setAdapter(adapter);
AppDetails=handler.getDetails();
content=AppDetails.get(0);
url=content.getDlink();
head=handler.getDesc(position+1);
content=head.get(0);
heading=content.getTitle();
tvHeading.setText(heading);
twvCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position1, long id) {
head=handler.getDesc(position1+1);
content=head.get(0);
heading=content.getTitle();
tvHeading.setText(heading);
Category category=new Category();
Bundle bundle=new Bundle();
bundle.putString("heading",heading);
bundle.putInt("position",position1+1);
bundle.putString("url",url);
bundle.putBoolean("flag",true);
category.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentCategories, category);
fragmentTransaction.commit();
}
});
}
}
Category.java
package com.focusmedica.bphandoab1;
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.GridView;
import java.util.ArrayList;
/**
* Created by ashish on 11/15/2016.
*/
public class Category extends Fragment{
ArrayList<DIctionaryContent> AppDetails=new ArrayList<>();
ArrayList<DIctionaryContent> head=new ArrayList<>();
ArrayList<DIctionaryContent> video_chapter=new ArrayList<>();
GridView gvChapter;
MyDataBase handler;
DIctionaryContent content;
Chapter_content_Adapter adapter;
int position=0;
String heading,url;
boolean flag=false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
gvChapter=(GridView)rootView.findViewById(R.id.gvChapter);
handler=new MyDataBase(getActivity());
Bundle bundle=getArguments();
if(getArguments()!=null) {
flag = bundle.getBoolean("flag");
position = bundle.getInt("position");
heading = bundle.getString("heading");
url = bundle.getString("url");
}
if(flag==true){
video_chapter = handler.getContent_Aspects(position);
adapter = new Chapter_content_Adapter(getActivity(), video_chapter, url, heading, position);
gvChapter.setAdapter(adapter);
}else{
AppDetails=handler.getDetails();
content=AppDetails.get(0);
url=content.getDlink();
head=handler.getDesc(position+1);
content=head.get(0);
heading=content.getTitle();
video_chapter = handler.getContent_Aspects(position+1);
adapter = new Chapter_content_Adapter(getActivity(), video_chapter,url,heading,position+1);
gvChapter.setAdapter(adapter);
}
return rootView;
}
}
Chapter_content_Adapter
package com.focusmedica.bphandoab1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ashish on 11/15/2016.
*/
public class Chapter_content_Adapter extends BaseAdapter {
ArrayList<DIctionaryContent> listcontent=new ArrayList<>();
Context context;
DIctionaryContent content;
String folder2,folder1,heading,title;
int listPos,id;
String url;
boolean mIsPremium=false;
boolean[] isPremium;
public Chapter_content_Adapter(Context context, ArrayList<DIctionaryContent> listcontent, String url, String heading, int listPos){
this.context = context;
this.listcontent.clear();
this.listcontent = listcontent;
this.url=url;
this.heading=heading;
this.listPos=listPos;
isPremium=new boolean[listcontent.size()];
}
#Override
public int getCount() {
return listcontent.size();
}
#Override
public Object getItem(int position) {
return listcontent.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
class ViewHolder {
private TextView tv;
ImageView img,ivDownload;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.gridview_content, null);
viewHolder = new ViewHolder();
viewHolder.tv=(TextView) view.findViewById(R.id.tvGridViewTitle);
viewHolder.img=(ImageView) view.findViewById(R.id.ivGridImage);
viewHolder.ivDownload=(ImageView) view.findViewById(R.id.ivDownload);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
content = listcontent.get(position);
id=content.getID();
title=content.getTitle();
viewHolder.tv.setText(title);
folder1=content.getTitle();
folder2 = folder1.replaceAll(" ", "%20");
Glide.with(context).load(url+"/"+listPos+"/"+id+"_"+folder2+ "/Video.png").into(viewHolder.img);
return view;
}
/*public void refresh(List<DIctionaryContent> list){
listcontent.clear();
listcontent.addAll(list);
notifyDataSetChanged();
}*/
}

How use getDrawable() while using ViewPager

I was trying to use Drawable Animation in one of my Viewpager. But when I try to use getDrawable() method, it gives me null pointer exception. My ViewPager has 4 page. I think this is because my XML files are made in Viewpager and I cannot access them with this method. I already set a source for an ImageView in my Viewpager but still it doesn't work. Please have a look at my codes and help me.
My Main Activity:
import android.graphics.drawable.AnimationDrawable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(this));
ImageView myAnimation = (ImageView)findViewById(R.id.imageView2);
final AnimationDrawable myAnimationDrawable = (AnimationDrawable)myAnimation.getDrawable();
myAnimationDrawable.start();
}
}
My ViewPager Adapter:
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
and my enum to add new Pages:
public enum ModelObject {
RED(R.string.wp1, R.layout.wp1),
BLUE(R.string.wp2, R.layout.wp2),
LOL(R.string.wp3, R.layout.wp3),
WP(R.string.wp5,R.layout.wp4),
GREEN(R.string.wp4, R.layout.wp4);
private int mTitleResId;
private int mLayoutResId;
ModelObject(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
Please help me if you can.
sorry for bad English.
#Override
public void onPageSelected(int pos) {
//find your layout in with the position & then implement
ImageView myAnimation = (ImageView)findViewById(R.id.imageView2); // this imageview for particular viewpager page
final AnimationDrawable myAnimationDrawable = (AnimationDrawable)myAnimation.getDrawable();
myAnimationDrawable.start();
}

Starting Fragment from ArrayAdapter

I have 4 Fragments that I'm using for my application. One of my fragments(ChatList) has a ListView that uses an adapter which extends ArrayAdapter. Now in my ArrayAdapter class, when a certain row is clicked I want to open up my CurrentChat Fragment. How would I go about this? As far I have looked, it seems as though fragments can only be accessed from activities and other fragments.
ChatList.java
package com.example.jj.fragments;
import android.database.DataSetObserver;
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.AbsListView;
import android.widget.ListView;
/**
* Created by jj on 11/23/2015.
*/
public class ChatList extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
ListView chatListLV;
ChatListAdapter adapter;
public static ChatList newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
ChatList fragment = new ChatList();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Inflate the fragment layout we defined above for this fragment
// Set the associated text for the title
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chatlist, container, false);
chatListLV = (ListView) view.findViewById(R.id.chatLV);
adapter = new ChatListAdapter(getContext(),R.layout.single_chatlist_row);
chatListLV.setAdapter(adapter);
chatListLV.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
chatListLV.setSelection(adapter.getCount() - 1);
}
});
fillChatList();
return view;
}
public void fillChatList(){
DBHelper db = new DBHelper(getActivity());
db.getChatList(adapter);
db.close();
}
}
ChatListAdapter.java
package com.example.jj.fragments;
/**
* Created by jj on 11/28/2015.
*/
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import io.socket.client.IO;
import io.socket.client.Socket;
public class ChatListAdapter extends ArrayAdapter<ChatListDataProvider>{
public Socket mSocket;
{
try {
mSocket = IO.socket("https://great-sarodh.c9.io/");
}
catch (URISyntaxException e){}
}
private static final String TAG = "ChatListAdapter" ;
public List<ChatListDataProvider> chat_list = new ArrayList<ChatListDataProvider>();
private TextView dateTV;
private TextView messageTV;
private TextView timeTV;
private TextView sideTV;
private ImageView PictureIV;
private String gcmID;
private String androidID;
private String roomhash;
private int side;
CurrentChat CCFrag;
int type;
Context CTX;
public ChatListAdapter(Context context, int resource) {
super(context, resource);
CTX = context;
}
#Override
public void add(ChatListDataProvider object){
chat_list.add(object);
super.add(object);
}
#Override
public int getCount() {
return chat_list.size();
}
#Override
public ChatListDataProvider getItem(int position) {
return chat_list.get(position);
}
#Override public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflator = (LayoutInflater) CTX.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.single_chatlist_row,parent,false);
}
sideTV = (TextView) convertView.findViewById(R.id.sideTV);
messageTV = (TextView) convertView.findViewById(R.id.lastmsgTV);
timeTV = (TextView) convertView.findViewById(R.id.timeTV);
ChatListDataProvider provider = chat_list.get(position);
gcmID = provider.gcmID;
messageTV.setText(provider.lastMsg);
timeTV.setText(provider.time);
side = provider.side;
if(side == 0){
sideTV.setText("Who?:");
}
else if(side == 1){
sideTV.setText("You:");
}
roomhash = provider.roomID;
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stuck
Log.d(TAG, "JOINING ROOMID" + chat_list.get(position).roomID);
mSocket.emit("CreateRoom", chat_list.get(position).roomID, chat_list.get(position).gcmID);
//THE CODE TO OPEN CURRENTCHAT FRAGMENTS SHOULD GO HERE
}
});
notifyDataSetChanged();
return convertView;
}
}
ChatListDataProvider.java
package com.example.jj.fragments;
import android.support.v4.app.FragmentActivity;
/**
* Created by jj on 11/28/2015.
*/
public class ChatListDataProvider extends FragmentActivity{
public String roomID;
public String gcmID;
public String lastMsg;
public String date;
public String time;
public int side;
private ChatAdapter chat;
public ChatListDataProvider (String gcmID) {
super();
}
public ChatListDataProvider (String roomID, String gcmID, String lastMsg, int side, String time, String date) {
this.roomID = roomID;
this.gcmID = gcmID;
this.lastMsg = lastMsg;
this.side = side;
this.date = date;
}
}
CurrentChat.java
package com.example.jj.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CurrentChat extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
public static CurrentChat newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
CurrentChat fragment = new CurrentChat();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.currentchat, container, false);
return view;
}
}
In order to do that you can make a function inside your adapter passing your current activity context and container/frame layout like this.
public void changeFragmentFromAdapter(Activity act , int layoutid)
{
YourFragment fragmentToPopulate = new YourFragment();
FragmentManager frgManager = act.getFragmentManager();
FragmentTransaction fgTransation = frgManager.beginTransaction();
FgTransation.replace(layoutid, fragmentToPopulate).commit();
}
Paste this function in your ChatListAdapter.
now in your ChatList Class add itemclicklistener to your list
chatListLV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
//Here Add call change function
adapter.changeFragmentFromAdapter(getActivity() , R.layout.chatList);
}
}
i assume R.layout.chatList is your container for 3 fragments in MainActivity.
Now call this function from your activity of fragment.

Can't add fragments - android

I'm trying to build a simple application that displays two fragments. The first fragment is displayed by default. It contains a list of names which you can choose and when you click on one of the items, it supposes to display a second fragment with a text view, displaying the name you have chosen.
The problem is everytime I click one of the names on the list, it throws me a NullPointerException. I really don't know what could be the problem.
Here are the codes( The app contains three class - two fragments and one activity. The FriendsF fragment is the list fragment and it performs well. The second fragment is FeedFragment and onitemclick it should display the name that was clicked)
FriendsF fragment:
package com.example.fragmentsexcersize;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FriendsF extends ListFragment {
private static final String[] FRIENDS = { "ladygaga", "msrebeccablack",
"taylorswift13" };
public interface SelectionListener {
public void onItemSelected(int position);
}
private SelectionListener mCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
setListAdapter(new ArrayAdapter<String>(getActivity().getBaseContext(), layout, FRIENDS));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (SelectionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SelectionListener");
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (isInTwoPaneMode()) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
mCallback.onItemSelected(position);
}
private boolean isInTwoPaneMode() {
return getFragmentManager().findFragmentById(R.id.tweets) != null;
}
}
FeedFragment:
package com.example.fragmentsexcersize;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FeedFragment extends Fragment{
private TextView mTextView;
private static final String[] data = { "ladygaga", "msrebeccablack",
"taylorswift13" };
public FeedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tweet_view, container, false);
mTextView = (TextView) rootView.findViewById(R.id.tweet_view);
return rootView;
}
public void updateFeedDisplay(int position) {
mTextView.setText(data[position]);
}
}
MainActivity:
package com.example.fragmentsexcersize;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.app.FragmentTransaction;
public class MainActivity extends Activity implements FriendsF.SelectionListener{
private FriendsF mFriendsFragment;
private FeedFragment mFeedFragment;
private FragmentManager fragMana;
private FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFriendsFragment = new FriendsF();
fragMana = getFragmentManager();
transaction = fragMana.beginTransaction();
transaction.add(R.id.friends, mFriendsFragment);
transaction.commit();
}
private boolean isInTwoPaneMode() {
return findViewById(R.id.tweets) == null;
}
public void onItemSelected(int position) {
if (mFeedFragment == null)
mFeedFragment = new FeedFragment();
if (!isInTwoPaneMode()) {
transaction = fragMana.beginTransaction();
transaction.add(R.id.tweets, mFeedFragment);
transaction.commit();
}
mFeedFragment.updateFeedDisplay(position);
}
}
Make the following changes to your source:
MainActivity
public void onItemSelected(int position) {
Bundle bundle = new Bundle();
if (mFeedFragment == null)
mFeedFragment = new FeedFragment();
if (!isInTwoPaneMode()) {
bundle.putInt("POSITION", position);
mFeedFragment.setArguments(bundle);
transaction = fragMana.beginTransaction();
transaction.replace(R.id.tweets, mFeedFragment);
transaction.commit();
}
}
FeedFragment
private TextView mTextView;
private static final String[] data = { "ladygaga", "msrebeccablack",
"taylorswift13" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
View rootView = inflater.inflate(R.layout.tweet_view, container, false);
mTextView = (TextView) rootView.findViewById(R.id.tweet_view);
int mPosition = getArguments().getInt("POSITION", 0);
mTextView.setText(data[mPosition]);
return rootView;
}

Android: tabs with swipe not showing listfragment

I'm dealing with this tutorial: http://www.lucazanini.eu/2012/android/tabs-and-swipe-views/?lang=en .
The problem is that if I set as layout of the tab a simple static layout, like this (as the tutorial does), everything works fine:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/body1" />
</LinearLayout>
But I need the tab to be a ListFragment, and the matter is that my ListFragment shows nothing at all.
Here is the code. Don't desperate: I put lots of code but I think you will probably just need to look at the classes SongsFragment and SongsListAdapter (well, I am not sure because I were it I would not write here, however I suppose it because with a static layout everything works fine!)
EDIT: I post just one listfragment in the exemple, however it seems that every listfragment has the same issue
EDIT: probably the problem is that I need to use a method to show the fragment when the tab is selected
THANKS A LOT
Activity:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class PlayerActivity extends FragmentActivity implements
ActionBar.TabListener {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCollectionPagerAdapter = new CollectionPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select
// the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if
// we have a reference to the Tab.
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mCollectionPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// TODO Auto-generated method stub
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
SongsFragment
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class SongsFragment extends ListFragment {
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class SongsFragment extends ListFragment {
List<String[]> songs;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
songs = SongsDataSource.getInstance().getAllSongs();
List<String[]> values = new ArrayList<String[]>();
if (songs.size() == 0) {
values.add(new String[] { "No files found", "Try to update your database", "" });
}
for (String[] song : songs) {
values.add(new String[] { song[1], song[2], song[0] });
}
SongsListAdapter adapter = new SongsListAdapter(getActivity().getApplicationContext(),
R.layout.songs, R.id.songsFragment_titleTextView,R.id.songsFragment_artistTextView, values);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs, container, false);
return view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
}
}
SongsListAdapter
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SongsListAdapter extends ArrayAdapter<List<String[]>> {
private final Context context;
private final List<String[]> values;
private final Integer listViewId;
private final Integer titleTextViewId;
private final Integer artistTextViewId;
public SongsListAdapter(Context context, Integer listViewId, Integer titleTextViewId,
Integer artistTextViewId, List values) {
super(context, listViewId, values);
this.context = context;
this.listViewId = listViewId;
this.values = values;
this.titleTextViewId = titleTextViewId;
this.artistTextViewId = artistTextViewId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(listViewId, parent, false);
TextView titleView = (TextView) rowView.findViewById(titleTextViewId);
TextView artistView = (TextView) rowView.findViewById(artistTextViewId);
titleView.setText(values.get(position)[0]);
artistView.setText(values.get(position)[1]);
return rowView;
}
}
PagerAdapter
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class CollectionPagerAdapter extends FragmentPagerAdapter {
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return MyApplication.getInstance().infoFragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
if(0 <= position && position < MyApplication.getInstance().infoFragments.length) {
tabLabel = MyApplication.getInstance().infoFragments[position].getLabel();
}
return tabLabel;
}
}
TabFragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A fragment that launches other parts of the demo application.
*/
public class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
if(0 <= position && position < MyApplication.getInstance().infoFragments.length) {
tabLayout = MyApplication.getInstance().infoFragments[position].getLayout();
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
MyApplication class
import android.app.Application;
public class MyApplication extends Application {
//SIGLETON DECLARATION
private static MyApplication mInstance = null;
public static MyApplication getInstance() {
if (mInstance == null) {
mInstance = new MyApplication();
}
return mInstance;
}
public static InfoFragment[] infoFragments = new InfoFragment[] {
new InfoFragment("Songs", R.layout.songs)
};
public static class InfoFragment {
private String label;
private int layout;
public InfoFragment(String label, int layout) {
this.label = label;
this.layout = layout;
}
public String getLabel() {
return label;
}
public int getLayout() {
return layout;
}
}
}
Oh, it seems like you never actually return your SongsFragment in your getItem() method. It actually seems like you never use it!
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}

Categories

Resources