How to hand different Strings to dynamically created Fragments using ViewPager? - android

I can't seem to find a way to give different text to a dynamically created fragment for my pageviewer-supoorted application. I've came to a point of my codding where I got stuck. For my application I want to have 400-500 dynamically created fragments, where you can horizontally slide thru them and every content of the fragment to be the same (repeating the same fragment) and the only different thing to be the text on them.
Here's where I got stuck at my codding :
package com.example.testarearg;
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/ private String mText; // display this text in your fragment
public static Fragment getInstance(String text) {
Fragment f = new Fragment();
Bundle args = new Bundle();
args.putString("text", text);
f.setArguments(args);
return f;
}
public void onCreate(Bundle state) {
super.onCreate(state);
setmText(getArguments().getString("text"));
// rest of your code
}
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
}
}

You need to create your own custom Fragment:
import android.support.v4.app.Fragment;
public class YourFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container, false);
TextView tv = (TextView) v.findViewById(R.id.yourtextview);
tv.setText(getArguments().getString("text"));
return v;
}
public static YourFragment newInstance(String text) {
YourFragment f = new YourFragment();
Bundle b = new Bundle();
b.putString("text", text);
f.setArguments(b);
return f;
}
}
And then modify your adapter. The basic idea is that the adapter
contains the Strings that you want to display and the getItem(...)
method will choose the text.
public class MyPagerAdapter extends FragmentPagerAdapter {
private String [] strings;
public MyPagerAdapter(FragmentManager fm, String [] stringstodisplay) {
super(fm);
this.strings = stringstodisplay;
}
#Override
public Fragment getItem(int pos) {
return YourFragment.newInstance(strings[pos]);
}
#Override
public int getCount() {
return 500; // or strings.length to be save
}
}
From your Activity, you hand over the String array containing the different strings to the adapter.
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the content that your fragments will display
String [] strings = new String[500];
for(int i = 0; i < 500; i++) {
strings[i] = "This is Fragment " + i;
}
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), strings));
}
}

Related

How i can move data from DB to my ViewPager?

Class with DB and realization of Adapter.
public class MainActivity extends AppCompatActivity {//implements
View.OnClickListener{
ArrayList<String> titles = new ArrayList<>();
ArrayAdapter arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
titles);
listView.setAdapter(arrayAdapter);
try {
SQLiteDatabase myDatabase = this.openOrCreateDatabase("Places",
MODE_PRIVATE, null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS places (name VARCHAR,
time INT(2), solo INT(1), id INTEGER PRIMARY KEY)");
myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES
('One', 23, 1)");
myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES
('Two', 24, 2)");
myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES
('Three', 22, 1)");
myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES
('Four', 02, 2)");
Cursor c = myDatabase.rawQuery("SELECT * FROM places WHERE solo =
1", null);
int nameIndex = c.getColumnIndex("name");
int timeIndex = c.getColumnIndex("time");
int soloIndex = c.getColumnIndex("solo");
int idIndex = c.getColumnIndex("id");
if (c.moveToFirst()) {
titles.clear();
do {
titles.add(c.getString(nameIndex));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
}
c.close();
myDatabase.execSQL("DELETE FROM places");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Class with realization Fragment and PagerAdapter:
public class MyGallery extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_gallery);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_gallery,
container, false);
TextView textView = (TextView)
rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format,
getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
I'm trying to move a field named "name" (nameIndex) from the database to the viewpager screen. I can not move cursor values ​​to a class with the creation of a Fragment. I read about the method of entering data into the List and moved from there, the number of the required position to the FragmentPager, but it did not quite work out. Can someone know a simple and elegant way to solve this problem?
When you instantiate your FragmentPagerAdapter, pass an ArrayList to adapter constructor as argument
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager(), titles);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
In your adapter use a reference, and get string from array, such like
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<String> strings;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<String> strings) {
super(fm);
this.strings = strings;
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1, strings.get(position + 1));
}
#Override
public int getCount() {
return strings.size();
}
}
And finally, in your Fragment class, pass it as argument, and get as a global variable from onCreate method
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private String title;
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String title) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString("key", title);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title = getArguments().getString("key");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_gallery,
container, false);
TextView textView = (TextView)
rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format,
getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
Note. For better control on your code, if you have limited number of fragment, you should make an all cases using switch statement. Calling position + 1 in you adapter may throw nullpointerexception, when an index of your array will be exceeded. You can start any postion using viewPager.setCurrentItem(position);, example of FragmentPagerAdapter with switch statement should looks like
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return PlaceholderFragment.newInstance(position, strings.get(position));
case 1:
return PlaceholderFragment.newInstance(position, strings.get(position));
case 2:
return PlaceholderFragment.newInstance(position, strings.get(position));
default:
return something...
}
}

How to instantiate a fragment on method instantiateItem?

i'm very new to Android programming, and i'm trying to make the instantiateItem on my SlidingTabsBasicFragment class, to return the fragment of my ConversationsFragment.
In my understanding, my Class ConversationsFragment returns a fragment, that would be instantiated. But instead, nothing shows at the second page.
I'm using the SlidingTabsBasic sample to make this:
Main Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("Logs", "first");
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
transaction.replace(R.id.sample_content_fragment, fragment);
//ConversationsFragment fragment = new ConversationsFragment();
//transaction.replace(R.id.sample_content_fragment, new ConversationsFragment());
transaction.commit();
}
}
SlidingTabsBasicFragment:
package com.example.android.slidingtabsbasic;
import com.example.android.common.logger.Log;
import com.example.android.common.view.SlidingTabLayout;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.TextView;
/**
* A basic sample which shows how to use {#link com.example.android.common.view.SlidingTabLayout}
* to display a custom {#link ViewPager} title strip which gives continuous feedback to the user
* when scrolling.
*/
public class SlidingTabsBasicFragment extends Fragment {
static final String LOG_TAG = "SlidingTabsBasicFragment";
/**
* A custom {#link ViewPager} title strip which looks much like Tabs present in Android v4.0 and
* above, but is designed to give continuous feedback to the user when scrolling.
*/
private SlidingTabLayout mSlidingTabLayout;
/**
* A {#link ViewPager} which will be used in conjunction with the {#link SlidingTabLayout} above.
*/
private ViewPager mViewPager;
/**
* Inflates the {#link View} which will be displayed by this {#link Fragment}, from the app's
* resources.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sample, container, false);
}
// BEGIN_INCLUDE (fragment_onviewcreated)
/**
* This is called after the {#link #onCreateView(LayoutInflater, ViewGroup, Bundle)} has finished.
* Here we can pick out the {#link View}s we need to configure from the content view.
*
* We set the {#link ViewPager}'s adapter to be an instance of {#link SamplePagerAdapter}. The
* {#link SlidingTabLayout} is then given the {#link ViewPager} so that it can populate itself.
*
* #param view View created in {#link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
*/
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// BEGIN_INCLUDE (setup_viewpager)
// Get the ViewPager and set it's PagerAdapter so that it can display items
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new CustomPagerAdapter(getFragmentManager(),getActivity()));
// END_INCLUDE (setup_viewpager)
// BEGIN_INCLUDE (setup_slidingtablayout)
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
// END_INCLUDE (setup_slidingtablayout)
}
// END_INCLUDE (fragment_onviewcreated)
public class CustomPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public CharSequence getPageTitle(int position) {
return "Item " + (position + 1);
}
#Override
public Fragment getItem(int position) {
if(position==0){
// return fragment
}else{
ConversationsFragment fragment = new ConversationsFragment();
return fragment;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
}
And this is my ConversationsFragment:
public class ConversationsFragment extends Fragment implements AbsListView.OnItemClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private List conversationsListItemList; // at the top of your fragment listW
private ListAdapter mAdapter;
// TODO: Rename and change types of parameters
public static ConversationsFragment newInstance(String param1, String param2) {
ConversationsFragment fragment = new ConversationsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ConversationsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
conversationsListItemList = new ArrayList();
conversationsListItemList.add(new ConversationsListItem("Example 1","conversa"));
conversationsListItemList.add(new ConversationsListItem("Example 2","conversa"));
conversationsListItemList.add(new ConversationsListItem("Example 3","conversa"));
mAdapter = new ConversationsListAdapter(getActivity(), conversationsListItemList);
/* mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_conversations, container, false);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(String id);
}
}
Screenshots:
First Screen:
https://goo.gl/photos/Ze5ThZgevGaALDj47
Second Screen:
https://goo.gl/photos/x7JPnESAtZsBT5DC8
And now this errors appears:
06-16 12:32:58.946 12228-12228/com.example.android.slidingtabsbasic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.slidingtabsbasic, PID: 12228
java.lang.NullPointerException
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:417)
at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:412)
at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:99)
I think problem with your code is returning View and Fragment
below code worked for me
public class CustomPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public CharSequence getPageTitle(int position) {
return "" + tabsTitle[position];
}
#Override
public Fragment getItem(int position) {
if(position==0){
// return fragment
}else{
ConversationsFragment fragment = new ConversationsFragment();
return fragment;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}

ListView Contacts List breaking main activity

I am trying to make the Contact tab in my app to list the users address book's name and phone number, however when I set the adapter for contactlist the app no longer shows its tabs and the fragment is empty.
Code:
package com.spgrn.smsim;
import java.util.ArrayList;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
String phoneNumber;
ListView contactlist;
ArrayList <String> aa= new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactlist= (ListView) findViewById(R.id.contactv);
getNumber(this.getContentResolver());
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
Log.v("I", "curtab="+ mSectionsPagerAdapter.getCount() + "i=" + i);
if (i != 1)
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this),
false);
if (i == 1)
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this),
true);
}
}
public void getNumber(ContentResolver cr)
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(name + phoneNumber);
aa.add(name + "\n" + phoneNumber);
}
Log.v("Contacts", "Total= " + phones.getCount());
phones.close();// close cursor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,aa);
contactlist.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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;
}
if (id == R.id.action_compose) {
Intent intent = new Intent(this, NewMessage.class);
this.startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position){
case 0:
Fragment fragmentContacts = new FragmentContacts();
return fragmentContacts;
case 1:
Fragment fragmentMessages = new FragmentMessages();
return fragmentMessages;
case 2:
Fragment fragmentAccounts = new FragmentAccounts();
return fragmentAccounts;
}
return null;
}
#Override
public int getCount() {
// Show 5 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
//Make fragments for each tab
public static class FragmentContacts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentContacts() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
return rootView;
}
}
public static class FragmentMessages extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentMessages() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,
container, false);
return rootView;
}
}
public static class FragmentAccounts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentAccounts() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_accounts,
container, false);
return rootView;
}
}
//End of Tab Fragments
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Also, in the debugger I noticed the main activity was suspended due to a run time exception. Here is the stack:
Thread [<1> main] (Suspended (exception RuntimeException))
<VM does not provide monitor information>
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2195
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2245
ActivityThread.access$800(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 135
ActivityThread$H.handleMessage(Message) line: 1196
ActivityThread$H(Handler).dispatchMessage(Message) line: 102
Looper.loop() line: 136
ActivityThread.main(String[]) line: 5017
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 515
ZygoteInit$MethodAndArgsCaller.run() line: 779
ZygoteInit.main(String[]) line: 595
XposedBridge.main(String[]) line: 126
NativeStart.main(String[]) line: not available [native method]
Thanks!
Edit: Looking more, I think the list needs to be generated in the fragments class, but I am not sure what to do with the context. I keep getting a NullPointerException.
Code:
public static class FragmentContacts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentContacts() {
}
Context context;
String phoneNumber;
ListView contactlist;
ArrayList <String> aa= new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
contactlist = (ListView) rootView.findViewById(R.id.contactv);
getNumber(context.getContentResolver());
return rootView;
}
public void getNumber(ContentResolver cr)
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(name + phoneNumber);
aa.add(name + "\n" + phoneNumber);
}
Log.v("Contacts", "Total= " + phones.getCount());
phones.close();// close cursor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
.getApplicationContext(),
android.R.layout.simple_list_item_1,aa);
contactlist.setAdapter(adapter);
}
}
write
context=container.getContext();
in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
contactlist = (ListView) rootView.findViewById(R.id.contactv);
context=container.getContext();
getNumber(context.getContentResolver());
return rootView;
}

swipe view and fragments android

I currently have the following code which I found as an example and modified slightly:
package com.boy.test;
import java.util.Locale;
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.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new Facebook();
Bundle args = new Bundle();
args.putInt(Facebook.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Welcome".toUpperCase(l);
case 1:
return "Facebook".toUpperCase(l);
case 2:
return "Twitter".toUpperCase(l);
case 3:
return "dashboard".toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class Facebook extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
private WebView faceBook;
public Facebook() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_facebook, container, false);
return rootView;
}
}
}
What I want to do is add facebook into the second tab. This is code I have in another class for doing so:
public class Facebook extends Activity {
private WebView faceBook;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
faceBook = new WebView(this);
faceBook.getSettings().setJavaScriptEnabled(true);
final Activity act = this;
faceBook.setWebViewClient(new WebViewClient(){
public void onRecievedError(WebView view,int errorCode,String description,String failingUrl){
Toast.makeText(act,description,Toast.LENGTH_SHORT).show();
}
});
faceBook.loadUrl("http://m.facebook.com/pages/hi");
setContentView(faceBook);
}
I tried simply copying it into my static facebook fragment and got errors. I also tried making that extend fragment activity instead of fragment and got more errors. Can anyone advise me on to how to best approach this?
Thank you.
first of all you don't need a Facebook activity, you will have to override Fragment's onCreateView() method in class Facebook to return a WebView.
try this,
your fragment should look like following,
public final class MyTab extends Fragment {
public static MyTab newInstance(int type) {
MyTab tab = new MyTab();
tab.mType = type;
return fragment;
}
private int mType = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*
* Create a web view here, and on the basis of mType decide what to load.
* and return that web view.
*/
}
}
and your adapter will be
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return MyTab.newInstance(position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Welcome".toUpperCase(l);
case 1:
return "Facebook".toUpperCase(l);
case 2:
return "Twitter".toUpperCase(l);
case 3:
return "dashboard".toUpperCase(l);
}
return null;
}
}

use SectionsPagerAdapter with custom fragment

When creating a template project with holo fragments and tabs and sectionsPagerAdapter you get something like this
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
The definition of DummySectionFragment:
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public DummySectionFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
Bundle args = getArguments();
textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
return textView;
}
}
Now I replace this code with my own extension of Fragment:
#Override
public Fragment getItem(int i) {
Fragment fragment = new TargetsFragment();
Bundle args = new Bundle();
I defined this in its own file:
public class TargetsFragment extends Fragment {
boolean mDualPane;
int mCurCheckPosition = 0;
private CheckedExpandableListAdapter expandableListAdapter;
private ExpandableListView expandableListView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//TODO: serve with correct data instead of this!
final ArrayList<ListNode> dummyList = buildDummyData();
loadHosts(dummyList);
}
[...]
The error I get is that it is not possible to convert TargetsFragment to Fragment in getItem. I feel i'm missing something simple here. But what? If you need more code please ask.
Solution: take a close look at the imports. Make sure you import and extend the same Fragment in both classes. eg android.app.fragment or import android.support.v4.app.Fragment;

Categories

Resources