I've been looking for an answer for a while now, but I haven't been able to find the same situation, so I'll try asking it here.
I'm currently creating an app with an Activity, 2 fragments and viewpager functionality. Fragment 1 has a button that will update the list on fragment 2 (the usual way, frag 1 -> activity -> frag 2) and when it reaches that method and calls notifyDataSetChanged it crashes because the adapter is null. Apparently the adapter is null and the existing List to fill the listview is empty (which isn't a huge problem because it gets filled again, but I'd like to keep the original items).
How can I update my list and why is my adapter null?
My code:
MainActivity
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements FirstFragment.OnUpdatedListListener {
private ViewPager viewPager;
private TestAdapter mAdapter;
//Lifecycle functions
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.TestPager);
mAdapter = new TestAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {}
#Override
public void onPageScrollStateChanged(int state) {}
});
}
#Override
public void onListUpdated() {
logcat("Click received in main");
SecondFragment sf = SecondFragment.newInstance();
if (sf == null || !sf.isInLayout()) {
logcat("frag == null || !frag.isInLayout()");
SecondFragment newFragment = SecondFragment.newInstance();
Bundle args = new Bundle();
newFragment.setArguments(args);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.second_fragment, newFragment);
transaction.addToBackStack(null);
transaction.commit();
newFragment.receiver();
} else {
logcat("frag bestaat");
sf.receiver();
}
}
}
ListItemAdapter:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class ListItemAdapter extends ArrayAdapter<ListItem> {
private final Context context;
private List<ListItem> items;
public ListItemAdapter(Context context, int resource, List<ListItem> values) {
super(context, R.layout.list_items, values);
this.context = context;
this.items = values;
}
private static class ViewHolder {
TextView tvName;
TextView tvDescription;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_items, parent, false);
ViewHolder viewholder = new ViewHolder();
viewholder.tvName = (TextView) rowView.findViewById(R.id.tvName);
viewholder.tvDescription = (TextView) rowView.findViewById(R.id.tvDescription);
rowView.setTag(viewholder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
holder.tvName.setText(items.get(position).getName());
holder.tvDescription.setText(items.get(position).getDescription());
return rowView;
}
}
SecondFragment:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class SecondFragment extends Fragment {
private final static String TAG = "SecondFragment";
private List<ListItem> items = new ArrayList<>();
private ListView lv;
private ListItemAdapter adapter;
public SecondFragment() {}
public static SecondFragment newInstance() {
Bundle args = new Bundle();
secondFragment.setArguments(args);
return secondFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
items.add(new ListItem(1, "Willem", "Willemkeurige beschrijving"));
items.add(new ListItem(2, "Jos", "De Klos"));
items.add(new ListItem(3, "Leo", "Pold"));
adapter = new ListItemAdapter(getActivity(), 0, items);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_second, container, false);
lv = (ListView) v.findViewById(R.id.lvSecond);
lv.setAdapter(adapter);
return v;
}
public void receiver() {
items.add(new ListItem(4, "Willem2", "Willemkeurige beschrijving"));
items.add(new ListItem(5, "Jos2", "De Klos"));
items.add(new ListItem(6, "Leo", "Pold3"));
adapter.notifyDataSetChanged();
}
}
You can try this:
In MyActivity add:
public class MyActivity extends FragmentActivity {
//...
private ListItemAdapter mAdapter;
public ListItemAdapter getAdapter(){
if (mAdapter==null){
mAdapter = new ListItemAdapter();
}
return mAdapter;
}
}
In your Fragment you can get the Adapter using:
((MyActivity)getActivity()).getAdapter();
This way you can "share" your Adapter.
The problem is that your calling receiver() before the fragment has been added. The fragment has its own lifecycle, so there is not guarantee that onCreate and onCreateView has been called. This is why your adapter is null. To fix this you can do:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_second, container, false);
lv = (ListView) v.findViewById(R.id.lvSecond);
lv.setAdapter(adapter);
receiver();
return v;
}
public void receiver(){
//add your strings as normal
if(adapter != null){
adapter.notifyDataSetChanged();
}
}
Related
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();
}*/
}
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.
Here's my UI hierarchy:
Main Fragment -> Fragment with ActionBar.TabListener -> Fragment with FragmentStatePagerAdapter -> ListFragment
The issue is that the ListFragment does display the first time I go into the tab of the ListFragment, but it does not display the second time (so going to tab 2 displays it, but then going to tab 1 and then tab 2 it doesn't display itself. The ListFragment is in tab 2).
This layout works fine if I remove the FragmentStatePagerAdapter, but now my project requires pages, so I needed to add the FragmentStatePagerAdapter to make the paging work.
However, at this point I dont really know what the problem is. I dont know if the issue is in the FragmentStatePagerAdapter, the ListFragment or if the phone just for some reason looses the data of the ListFragment.
I do know that getItem in FragmentStatePagerAdapter does not get called again when switching tabs.
Here's my code for the TrendsPagerHolder and FragmentStatePagerAdapter (as inner class):
import java.util.ArrayList;
import java.util.Collections;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.os.Bundle;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TrendsPagerHolder extends Fragment
{
private ArrayList<String>testArray = new ArrayList<String>();
private Context context;
private SharedPreferences preferences;
private Bundle applicationStatus;
// The number of pages to display
private static final int NUM_PAGES = 3;
private ViewPager pager;
//The pager adapter, which provides the pages to the view pager widget
private PagerAdapter pagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
context = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
context = inflater.getContext();
applicationStatus = savedInstanceState;
View rootView = (View) inflater.inflate(R.layout.trends_screen_slider, container, false);
System.out.println("in TrendsPagerHolder onCreateView");
pager = (ViewPager) rootView.findViewById(R.id.trends_pager);
pagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(0);
return rootView;
}
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
TrendsLV[] arrayOfTrendsFragments;
public ScreenSlidePagerAdapter(FragmentManager fragmentManager)
{
super(fragmentManager);
testArray.add("One");
testArray.add("Two");
testArray.add("Three");
arrayOfTrendsFragments = new TrendsLV[NUM_PAGES];
arrayOfTrendsFragments[0] = new TrendsLV(testArray, 0);
arrayOfTrendsFragments[1] = new TrendsLV(testArray, 1);
arrayOfTrendsFragments[2] = new TrendsLV(testArray, 2);
}
#Override
public Fragment getItem(int position)
{
System.out.println("in getItem. Position = " + position);
return arrayOfTrendsFragments[position];
}
#Override
public int getCount()
{
return NUM_PAGES;
}
}
}
Here's the code for my ListFragment:
import java.util.ArrayList;
import java.util.Collections;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TrendsLV extends ListFragment
{
private Context context;
private ArrayList<String>testArray;
private Bundle applicationStatus;
private int pageIndex;
public TrendsLV(ArrayList<String> test, int index)
{
testArray = test;
pageIndex = index;
}
public TrendsLV()
{
// required
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
context = inflater.getContext();
applicationStatus = savedInstanceState;
System.out.println("in TrendsLV onCreateView");
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
if (testArray != null)
{
TrendsListAdapter adapter = new TrendsListAdapter(context, testArray, pageIndex);
setListAdapter(adapter);
}
}
return super.onCreateView(inflater, container, savedInstanceState);
}
}//end class TrendsLV
And here's the code for the Adapter that is called from the ListFragment:
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class TrendsListAdapter extends ArrayAdapter<String>
{
private Context context;
private ArrayList<String>testArray;
private int pageIndex;
public TrendsListAdapter (Context c, ArrayList<String> test, int index)
{
super(c, R.layout.trends_row, test);
context = c;
testArray = test;
pageIndex = index;
}
#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.trends_row, parent, false);
TextView label_totalArea = (TextView) rowView.findViewById(R.id.trends_labelTotalArea);
label_totalArea.setText(context.getResources().getString(R.string.stringTotalArea));
return rowView;
}
}
Let me know if you need additional information to solve this issue.
I am testing it on a device using Android 4.4.4.
Thank you.
If you are inflating Fragment inside Fragment you should use getChildFragmentManager() instaed of getFragmentManager().
Here is the doc : http://developer.android.com/reference/android/app/Fragment.html#getChildFragmentManager()
public class TrendsPagerHolder extends Fragment
{
private ArrayList<String>testArray = new ArrayList<String>();
private Context context;
private SharedPreferences preferences;
private Bundle applicationStatus;
// The number of pages to display
private static final int NUM_PAGES = 3;
private ViewPager pager;
//The pager adapter, which provides the pages to the view pager widget
private PagerAdapter pagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
context = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
context = inflater.getContext();
applicationStatus = savedInstanceState;
View rootView = (View) inflater.inflate(R.layout.trends_screen_slider, container, false);
System.out.println("in TrendsPagerHolder onCreateView");
pager = (ViewPager) rootView.findViewById(R.id.trends_pager);
pagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(0);
return rootView;
}
I think you should create the instance of ListFragment and use that instance in FragmentStatePagerAdapter.. some thing like this..
In Your TrendsLV class , remove the constructor and add below method to create the instance of fragment..
public static TrendsLV newInstance(ArrayList<String> test, int index) {
TrendsLV fragment = new TrendsLV();
testArray = test;
pageIndex = index;
return fragment;
}
Then update your ScreenSlidePagerAdapter as follow..
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
TrendsLV[] arrayOfTrendsFragments;
public ScreenSlidePagerAdapter(FragmentManager fragmentManager)
{
super(fragmentManager);
testArray.add("One");
testArray.add("Two");
testArray.add("Three");
arrayOfTrendsFragments = new TrendsLV[NUM_PAGES];
arrayOfTrendsFragments[0] = TrendsLV.newInstance(testArray, 0);
arrayOfTrendsFragments[1] = TrendsLV.newInstance(testArray, 1)
arrayOfTrendsFragments[2] = TrendsLV.newInstance(testArray, 2)
}
#Override
public Fragment getItem(int position)
{
System.out.println("in getItem. Position = " + position);
return arrayOfTrendsFragments[position];
}
#Override
public int getCount()
{
return NUM_PAGES;
}
}
or instead of creating the array of fragments.. you can replace the in getItem() method like this..
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
public ScreenSlidePagerAdapter(FragmentManager fragmentManager)
{
super(fragmentManager);
testArray.add("One");
testArray.add("Two");
testArray.add("Three");
}
#Override
public Fragment getItem(int position)
{
System.out.println("in getItem. Position = " + position);
Fragment instanceFragment = null;
switch (position) {
case 0:
instanceFragment =TrendsLV.newInstance(testArray, 0);;
break;
case 1:
instanceFragment =TrendsLV.newInstance(testArray, 1);;
break;
case 2:
instanceFragment =TrendsLV.newInstance(testArray, 2);;
break;
default:
break;
}
return instanceFragment;
}
#Override
public int getCount()
{
return NUM_PAGES;
}
}
I don't know what is the use of testArray so i haven't made any changes for it.
Hope it helps..!! :)
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;
}
I have a ViewPager setup with 3 fragment Classes, and a pageadapter class.
MainActivity class
package com.example.swipeview;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpager = (ViewPager) findViewById(R.id.viewpagers);
com.example.swipeview.PagerAdapter padapter = new com.example.swipeview.PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(padapter);
}
}
PageAdapter class
package com.example.swipeview;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch(arg0){
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
case 2:
return new FragmentThree();
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
and my first FragmentClass as an example
package com.example.swipeview;
import com.example.swipeview.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_one_layout, container, false);
}
}//end of class
I've tried my usual methods for creating a listview inside of an Activity class but that doesn't work with the fragment class. I was wondering if anyone could show me how to code a listview into a fragment class.
An example with a custom adapter (using a List as source):
public class ItemsFragment extends Fragment {
/* Must be populated later. */
private final List<Item> items = new ArrayList<>();
private ItemAdapter adapter;
private ListView listView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_items_list, container, false);
adapter = new ItemAdapter(this.getActivity(), items);
listView = (ListView) layout.findViewById(R.id.listview_items);
return layout;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Item currentItem = adapter.getItem(position);
// (...)
}
});
}
/* (...) */
}