ListView Contacts List breaking main activity - android

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

Related

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

Radio buttons on previous fragment stop working after error E/TextView﹕ Saved cursor position 2/2 out of range for (restored) text

E/TextView﹕ Saved cursor position 2/2 out of range for (restored) text
is the message I get.
When I read on S.O. that using hardcoded values for colours like #ffffffff causes this so i used values in my strings.xml but i still kept getting the same error.
My app is using multiple fragments in swipe view
Do text Views cause this? But none of my textViews are editable.
I also lose all the data on my previous fragments the moment this error pops in my logcat.
This include selected radio buttons mainly.
Apparently even their listener stops working.
here is my code:
package com.iiitk.zeda.aapkaauto;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
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.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Request extends ActionBarActivity implements LocationListener{
/**
* 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}.
*/
static LocationManager locationManager;
static double[] gps=new double[2];
SectionsPagerAdapter mSectionsPagerAdapter;
static TextWatcher mTextEditorWatcher;
static View InforootView,PickuprootView,DestinationrootView,SchedulerootView,PoolingrootView,SummaryRootView;
private static Context context;
static ArrayAdapter adapter;
static AutoCompleteTextView picker;
static String st;
static LocationManager mLocationManager;
static NumberPicker np3;
static NumberPicker np2;
static NumberPicker np;
static String longitude,latitude;
static EditText specify,specify2;
static Button GPS,GPS2;
static Spinner pickupspinner;
static Spinner destinationspinner;
static String Src,Dest,Username,Contact,Email;
static RadioGroup pickupgroup,destinationgroup,schedulergroup,payment;
static LinearLayout scheduler,pool,nonpool;
static RadioButton p1,p2,p3,d1,d2,d3,s1,s2,s3,prepaid,postpaid;
static CheckBox Sharing;
static TextView estimate,fare;
public static String AreaList[]= {
"22 Godam",
"Airport",
"Ajmeri Gate",
"Birla Auditorium",
"Birla Mandir",
"Central Park",
"Chauda Rasta",
"City Palace",
"Durga Pura",
"EP",
"Fortis Hospital",
"Galaxy",
"Gandhinagar Railway Station",
"Gaurav Tower",
"Hawa Mahal",
"Hyper City",
"Jagatpura",
"Jaipur Railway Station",
"Jantar Mantar",
"Jawahar Circle",
"Kanak Vrindavan",
"Lalkothi",
"Maharani College",
"Narayan Singh Cicle",
"Pink Square Mall",
"Pt Education",
"Raja Park",
"Rajmandir",
"Sanganer",
"Sindhi camp",
"SKIT College",
"SMS Hospital",
"SMS Stadium",
"St Xaviers School",
"T.I.M.E",
"Tonk Phatak",
"Transport Nagar",
"WTP"};
static Thread poolinglistener,pickuplistener,destinationlistener,schedulelistener,summarylistener;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Request.context=getApplicationContext();
Runnable pickup=new pickuplistener();
pickuplistener=new Thread(pickup);
pickuplistener.setDaemon(true);
pickuplistener.setPriority(Thread.MAX_PRIORITY);
Runnable destination=new destinationlistener();
destinationlistener=new Thread(destination);
destinationlistener.setDaemon(true);
destinationlistener.setPriority(Thread.MAX_PRIORITY);
Runnable pooling=new poolinglistener();
poolinglistener=new Thread(pooling);
poolinglistener.setDaemon(true);
poolinglistener.setPriority(Thread.MAX_PRIORITY);
Runnable schedule=new schedulelistener();
schedulelistener=new Thread(schedule);
schedulelistener.setDaemon(true);
schedulelistener.setPriority(Thread.MAX_PRIORITY);
Runnable summary=new Summarize();
summarylistener=new Thread(summary);
summarylistener.setDaemon(true);
summarylistener.setPriority(Thread.MAX_PRIORITY);
// 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);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.request, 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;
}
return super.onOptionsItemSelected(item);
}
public class selection implements Spinner.OnItemSelectedListener{
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
if (view==pickupspinner){
pickupspinner.setSelection(position);
Src = (String) pickupspinner.getSelectedItem();
}
else{destinationspinner.setSelection(position);
Dest = (String) destinationspinner.getSelectedItem();}
}
public void onNothingSelected(AdapterView<?> arg0) {
pickupspinner.setSelection(0);
destinationspinner.setSelection(0);
Src = (String) pickupspinner.getSelectedItem();
Dest=(String) destinationspinner.getSelectedItem();
}
}
/**
* 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).
switch(position){
case 0: return InformationFragment.newInstance(position + 1);
case 1: return PickupFragment.newInstance(position+1);
case 2: return DestinationFragment.newInstance(position+1);
case 3: return ScheduleFragment.newInstance(position+1);
case 4: return PoolingFragment.newInstance(position+1);
case 5: return SummaryFragment.newInstance(position + 1);
case 6: return PaymentFragment.newInstance(position+1);
default:
return PlaceholderFragment.newInstance(position + 1);
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 7;
}
#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);
case 3:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* 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();
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_request, container, false);
return rootView;
}
}
public static class InformationFragment 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 InformationFragment newInstance(int sectionNumber) {
InformationFragment fragment = new InformationFragment();
return fragment;
}
public InformationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
InforootView = inflater.inflate(R.layout.fragment_fragment_info, container, false);
return InforootView;
}
}
public static class PickupFragment extends Fragment implements View.OnClickListener{
/**
* 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 PickupFragment newInstance(int sectionNumber) {
PickupFragment fragment = new PickupFragment();
return fragment;
}
public PickupFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_pickup, container, false);
GPS=(Button) rootView.findViewById(R.id.gps);
GPS.setOnClickListener(this);
adapter = new ArrayAdapter<String>(rootView.getContext(),R.layout.item_list);
picker= (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView);
adapter.setNotifyOnChange(true);
picker.setAdapter(adapter);
PickuprootView=rootView;
EditText pickers=(EditText)picker;
pickers.addTextChangedListener(mTextEditorWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// When No Password Entered
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (count%3 == 1) {
//we don't want to make an insanely large array, so we clear it each time
adapter.clear();
//create the task
st=s.toString();
GetPlaces task = new GetPlaces();
//now pass the argument in the textview to the task
task.execute(picker.getText().toString());
}
}
public void afterTextChanged(Editable s) {
}
});
if (pickuplistener.getState()==Thread.State.NEW)pickuplistener.start();
return rootView;
}
#Override
public void onClick(View v) {
System.out.println("Reached");
Intent gpset;
boolean statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!statusOfGPS){
gpset = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpset);
}
else {
System.out.println("GPS is on");
new getGps();
try{
System.out.println(longitude);
System.out.println(latitude);}
catch(NullPointerException e){}
}
}
}
public static class DestinationFragment 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 DestinationFragment newInstance(int sectionNumber) {
DestinationFragment fragment = new DestinationFragment();
return fragment;
}
public DestinationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_destination, container, false);
DestinationrootView=rootView;
if (destinationlistener.getState()==Thread.State.NEW)destinationlistener.start();
return rootView;
}
}
public static class ScheduleFragment 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 ScheduleFragment newInstance(int sectionNumber) {
ScheduleFragment fragment = new ScheduleFragment();
return fragment;
}
public ScheduleFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_schedule, container, false);
SchedulerootView=rootView;
if (schedulelistener.getState()==Thread.State.NEW)schedulelistener.start();
return rootView;
}
}
public static class PoolingFragment 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 PoolingFragment newInstance(int sectionNumber) {
PoolingFragment fragment = new PoolingFragment();
return fragment;
}
public PoolingFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_pooling, container, false);
PoolingrootView=rootView;
if(poolinglistener.getState()==Thread.State.NEW)poolinglistener.start();
return rootView;
}
}
public static class SummaryFragment 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 SummaryFragment newInstance(int sectionNumber) {
SummaryFragment fragment = new SummaryFragment();
return fragment;
}
public SummaryFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_summary, container, false);
SummaryRootView=rootView;
return rootView;
}
}
public static class PaymentFragment 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 PaymentFragment newInstance(int sectionNumber) {
PaymentFragment fragment = new PaymentFragment();
return fragment;
}
public PaymentFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (summarylistener.getState()==Thread.State.NEW) summarylistener.start();
View rootView = inflater.inflate(R.layout.fragment_fragment_payment, container, false);
payment=(RadioGroup) rootView.findViewById(R.id.payment);
prepaid=(RadioButton) rootView.findViewById(R.id.prepaid);
postpaid=(RadioButton) rootView.findViewById(R.id.prepaid);
estimate=(TextView) rootView.findViewById(R.id.estimate);
fare=(TextView) rootView.findViewById(R.id.fare);
System.out.println("Reached");
payment.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (prepaid.isChecked()) {
estimate.setVisibility(View.VISIBLE);
} else if (postpaid.isChecked()){
estimate.setVisibility(View.VISIBLE);
}
}
});
return rootView;
}
}
public static boolean isGpsEnabled(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
String providers = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (TextUtils.isEmpty(providers)) {
return false;
}
return providers.contains(LocationManager.GPS_PROVIDER);
} else {
final int locationMode;
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(),
Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
switch (locationMode) {
case Settings.Secure.LOCATION_MODE_HIGH_ACCURACY:
case Settings.Secure.LOCATION_MODE_SENSORS_ONLY:
return true;
case Settings.Secure.LOCATION_MODE_BATTERY_SAVING:
case Settings.Secure.LOCATION_MODE_OFF:
default:
return false;
}
}
}
#Override
public void onLocationChanged(Location location) {
System.out.println("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public IBinder onBind(Intent arg0) {
return null;
}
}
You need to store #ffffffff as a color not string. Create colors.xml like
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="color>#ffffffff </color>
</resources>

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

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

Calling Custom ListView Adapter from Fragment Class Main Activity

I've written a few listView activities, as a proof of concept for myself that I could do it. Now, I'm having trouble loading a listView activity into a single tab for an app with multiple tabs, that allows both swiping and tab selection for navigation. I get the error "The constructor ListView_Adapter(MainActivity.DummySectionFragment) is undefined" when I try to write the code for it. I'm a beginner, and I've lurked pretty hard here for the past few days. Any help is appreciated.
TL;DR : I'm a n00b, and I can't figure out this problem.
My Custom List Adapter
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 CustomListViewAdapter extends ArrayAdapter<String> {
public CustomListViewAdapter (Context c) {
super(c, R.layout.list_cell);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ListView_Text holder = null;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_cell, parent, false);
holder = new ListView_Text(row);
row.setTag(holder);
}
else
{
holder = (ListView_Text) row.getTag();
}
holder.populateFrom(getItem(position));
return row;
}
static class ListView_Text {
private TextView cell_name = null;
ListView_Text(View row) {
cell_name = (TextView) row.findViewById(R.id.list_cell_name);
}
void populateFrom(String index) {
cell_name.setText(index);
}
}
}
My Main Activity
import java.util.Locale;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import com.example.twigglebeta2.ListView_Adapter;
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.app.NavUtils;
import android.support.v4.view.ViewPager;
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.ListView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private static ListView_Adapter listViewAdapter;
private ListView listView;
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create adapter
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Switch tab selection to match current page when swiped
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Create a tab for each 'count' in the activity from getCount()
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
Tab thisTab = actionBar.newTab();
thisTab.setText(mSectionsPagerAdapter.getPageTitle(i));
thisTab.setTabListener(this);
actionBar.addTab(thisTab);
}
}
#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 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 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;
}
#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;
}
}
/**
* 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.
*/
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);
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
//The constructor ListView_Adapter(MainActivity.DummySectionFragment) is undefined
listViewAdapter = new ListView_Adapter(this);
ListView listView = (ListView) rootView.findViewById(R.id.listView1);
for (int i=0;i<20;i++)
{
listViewAdapter.add("this Index : "+i);
}
return listView;
}
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Instead of listViewAdapter = new ListView_Adapter(this);, you should instead try listViewAdapter = new ListView_Adapter(getActivity().getBaseContext());
The Issue is that you are passing a Fragment to the constructor, and not an Activity context.

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

Categories

Resources