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;
}
Related
I have an activity that has five fragments, One fragments is the notification fragment that has a recycler view where notification should be populating upon receiving them. now i have a function that add the items to the recycler view but when i try add it from another fragment it throws and null reference error.
Here is the fragment where there is the recycler and function to add the items on the recyclerview
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View v = inflater.inflate (R.layout.fragment_notificationcict, container, false);
notimodels = new ArrayList<> ();
RecyclerView mRecyclerView = v.findViewById (R.id.notificationsRecycler);
mRecyclerView.setHasFixedSize (true);
mLayoutManager = new LinearLayoutManager (getContext ());
mAdapter = new NotificationAdapter (notimodels);
mRecyclerView.setLayoutManager (mLayoutManager);
mRecyclerView.setAdapter (mAdapter);
}
public void addItem(NotificationModel n)
{
notimodels = new ArrayList<> ();
notimodels.add (n);
mAdapter.notifyItemInserted (notimodels.size () -1);
}
On the second fragment that adds items to the notification fragment
NotificationFragmentCict fragment = new NotificationFragmentCict ();
NotificationModel model = (new NotificationModel (R.drawable.logo, "OCApp", "Where are yiu.", "min"));
fragment.addItem (model);
Here is the Error
rocess: com.univibezstudios.ocappservice.ocapp, PID: 27625
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView$Adapter.notifyItemInserted(int)' on a null object reference
at com.univibezstudios.ocappservice.ocapp.Fragments.NotificationFragmentCict.addItem(NotificationFragmentCict.java:99)
at com.univibezstudios.ocappservice.ocapp.Fragments.AccountFragmentCict$4$1$1.onDataChange(AccountFragmentCict.java:374)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6803)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
See This is Fragment A
package com.codinginflow.fragmentcommunicationexample;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentA extends Fragment {
private FragmentAListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentAListener {
void addItemsToFragmentB();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_a, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItemsToFragmentB();
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentAListener) {
listener = (FragmentAListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentAListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
This is Fragment B
package com.codinginflow.fragmentcommunicationexample;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentB extends Fragment {
private FragmentBListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentBListener {
addItemsToFragmentA();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_b, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItemsToFragmentA();
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentBListener) {
listener = (FragmentBListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentBListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
This is an Activity in which u r going to add items to your recycler view
package com.codinginflow.fragmentcommunicationexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements FragmentA.FragmentAListener, FragmentB.FragmentBListener {
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = new FragmentA();
fragmentB = new FragmentB();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_a, fragmentA)
.replace(R.id.container_b, fragmentB)
.commit();
}
#Override
public void addItemsToFragmentA() {
fragmentB.updateEditText(input);
}
#Override
public void addItemsToFragmentB() {
fragmentA.updateEditText(input);
}
}
I'm trying to create VeiwPager inside a Fragment using FragmentStatePagerAdapter.
it displays the first fragment but after scrolling to the second fragment there is just white fragment (even on scrolling back to the first fragment)
I've tried to use PagerAdapter and set pictures without fragment but the result is same.
is there RAM problem ? what can I do to solve it?
Home fragment(contains ViewPager) :
private void initSlideShow(View view){
VPImageSlider = (ViewPager16by9) view.findViewById(R.id.VPImageSlider);
sliderDotsPanel = (LinearLayout) view.findViewById(R.id.SliderDots);
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_1);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_2);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_3);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_4);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_5);
VPImageSlider.setAdapter(vpImageSliderAdapter);
}
ViewPager Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import iranelab.samsoft.net.iranelab.Classes.ImageView16by9;
import iranelab.samsoft.net.iranelab.R;
public class ViewPagerFragment extends Fragment {
private static final String ARG_PARAM4 = "imageTest";
private int imageTest;
public ViewPagerFragment() {}
public static ViewPagerFragment newInstance(String imageId, String type, String text,int imageTest) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM4, imageTest);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
imageTest = getArguments().getInt(ARG_PARAM4);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
ImageView16by9 image = (ImageView16by9) view.findViewById(R.id.IVSlide);
image.setImageResource(imageTest);
return view;
}
}
ViewPager Adapter :
public class VPImageSliderAdapter extends FragmentStatePagerAdapter {
private int[] slides = {};
public VPImageSliderAdapter(FragmentManager fm){
super(fm);
}
public void addSlide(int drawable){
slides = Arrays.copyOf(slides,slides.length+1);
slides[slides.length-1]=drawable;
}
#Override
public int getCount() {
return slides.length;
}
#Override
public Fragment getItem(int position) {
return ViewPagerFragment.newInstance(slides[position]);
}
}
Change
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
to
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getChildFragmentManager());
it will work
Just needed to add :
ViewPager.setOffscreenPageLimit(5);
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.
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.
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;
}