Android: tabs with swipe not showing listfragment - android

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;
}

Related

Android: Change text in a PagerAdapter

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.

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();
}*/
}

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.

ListFragment doesn't re-display data when calling it from FragmentStatePagerAdapter

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..!! :)

viewpager implemented in gridview position

I am working on an application that have to have a GridView in the main activity containing images.
When an image is clicked, it has to open in another Activity in a bigger size. In this Activity, a ViewPager has to be implemented so that I can swipe right and left to change between the images.
The problem is that when i click on an image, the first image of the images appear firstly (argentina flag) and then the viewpager works .. how can i make it start by the image that i clicked ?
This is my main activity code :
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
public class MainActivityPager extends ActionBarActivity
{
static int[] FLAG;
ViewPager viewPager;
PagerAdapter adapter;
GridView gridview;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_pager);
FLAG = new int[] { R.drawable.flag_of_argentina, R.drawable.flag_of_brazil,
R.drawable.flag_of_england, R.drawable.flag_of_france,
R.drawable.flag_of_germany, R.drawable.flag_of_italy, R.drawable.flag_of_spain,
R.drawable.flag_of_uruguay };
AdapterGrid adapter = new AdapterGrid(MainActivityPager.this, FLAG);
gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
Intent intent = new Intent(view.getContext(), ActivityImage.class);
intent.putExtra("position", position);
count = gridview.getCount();
intent.putExtra("count", count);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my AdapterGrid class code :
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class AdapterGrid extends BaseAdapter
{
private int[] mFlag;
private Context mContext;
public AdapterGrid(Context context, int[] flag) {
//super(context, flag);
mContext = context;
mFlag = flag;
}
#Override
public int getCount() {
return mFlag.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View grid;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
imageView.setImageResource(mFlag[position]);
} else {
grid = (View) convertView;
}
return grid;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
This is my ActivityImage code :
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class ActivityImage extends FragmentActivity
{
private static int COUNT;
MyAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
Intent intent = getIntent();
COUNT = intent.getExtras().getInt("count");
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return COUNT;
}
#Override
public Fragment getItem(int position) {
return FragmentImage.init(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_image, menu);
return true;
}
}
This is my FragmentImage class code :
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.ImageView;
public class FragmentImage extends Fragment {
int fragVal;
static FragmentImage init(int pos) {
FragmentImage frag = new FragmentImage();
Bundle args = new Bundle();
args.putInt("val", pos);
frag.setArguments(args);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_image, container,
false);
ImageView imageView = (ImageView) layoutView.findViewById(R.id.imageView1);
imageView.setImageResource(MainActivityPager.FLAG[fragVal]);
return layoutView;
}
}
Thanks.
You set the position intent.putExtra("position", position); but never use it.
get it and
set after
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(CurrentPosition);

Categories

Resources