Using SherlockFragmentActivity works in newer android phone but not older model - android

so I have tested this code on a newer android and when I test it on an older version and click on a button to take me to a page with SwipeView and tabs, I get an error:
The application has stopped unexpectedly. Please try again.
I have set the minimumSDK level in the android manifest to 7. I'm not sure why it won't work on the older android phone.
Here's my code for the SwipeView class:
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SwipeMode extends SherlockFragmentActivity{
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipemode);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home button should show an "Up" caret, indicating that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed in the action bar.
// Create a simple intent that starts the hierarchical parent activity and
// use NavUtils in the Support Package to ensure proper handling of Up.
Intent upIntent = new Intent(this, MainActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is not part of the application's task, so create a new task
// with a synthesized back stack.
TaskStackBuilder.from(this)
// If there are ancestor activities, they should be added here.
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
// This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
//unimplemented methods were automatically added
#Override
public Fragment getItem(int i) {
// TODO Auto-generated method stub
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1); // Our object is just an integer :-P
fragment.setArguments(args);
return fragment;
}
//number of pages
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.text_object, container, false);
Bundle args = getArguments();
//This part sets the integer to string text on the layouts
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
}

Use getSupportActionBar() instead of getActionBar().
getActionBar() is supported from API lvl 11+

Related

Destroy FragmentStatePagerAdapter instance with parent Fragment

I am not sure how to ask this. I tried in here, but I guess I was not clear enough. So, I thought I just write a small App to describe the situation. Please note, the App uses Googles SlidingTabLayout.
Long story short, at any point if I click Button1, the FrameLayout should contain Fragment1, removing Fragment2 (if exists). Therefore, FragmentViewPager should also be destroyed as Fragment2. However, even then if I change the orientation of my device, I get the Toast which is defined in the onCreate() method of FragmentViewPager.
Why FragmentViewPager's onCreate is called even if Fragment2 is paused/destroyed? Is it possible that, the Toast of FragmentViewPager will not be shown when Fragment2 is destroyed?
MainActivity:
package com.abdfahim.testproject;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(onClickListener);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(onClickListener);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
switch (v.getId()){
case R.id.button1:
fragment = new Fragment1();
break;
case R.id.button2:
fragment = new Fragment2();
break;
default:
return;
}
getFragmentManager().beginTransaction().replace(R.id.frame_container, fragment, v.getTag().toString()).addToBackStack(null).commit();
}
};
}
Fragment1
package com.abdfahim.testproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public Fragment1(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1,container,false);
setHasOptionsMenu(true);
return rootView;
}
}
Fragment2
package com.abdfahim.testproject;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
public Fragment2(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment2,container,false);
setHasOptionsMenu(true);
CharSequence titles[]= {"Tab A", "Tab B"};
// Creating The ViewPagerAdapter
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getFragmentManager(), titles, titles.length);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assigning the Sliding Tab Layout View
SlidingTabLayout tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
return rootView;
}
static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private CharSequence titles[];
private int numbOfTabs;
public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabs) {
super(fm);
this.titles = mTitles;
this.numbOfTabs = mNumbOfTabs;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString("displayText", "Inside Fragment 2, " + titles[position]);
FragmentViewPager fragment = new FragmentViewPager();
fragment.setArguments(bundle);
return fragment;
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return numbOfTabs;
}
}
}
FragmentViewPager
package com.abdfahim.testproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentViewPager extends Fragment {
public FragmentViewPager(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_pager,container,false);
setHasOptionsMenu(true);
Bundle bundle = this.getArguments();
TextView textView = (TextView) rootView.findViewById(R.id.tabText);
textView.setText(bundle.getString("displayText"));
return rootView;
}
#Override
public void onStart() {
super.onStart();
Toast.makeText(getActivity(), "This is View Pager Fragment", Toast.LENGTH_SHORT).show();
}
}
when you use fragment inside another fragment. you use getChildFragmentManager() instead of getFragmentManager. You can call setAdapter() for the ViewPager from onCreateView() or onActivityCreated()
for more detail. have a look at it
Why it is not possible to use ViewPager within a Fragment? It actually is
For every click your OnClickListener creates the instance of Fragment2 and does not create Fragment1. That is due to the misuse of View#getTag.
In MainActivity#onCreate, change the if in the definition of onClickListener to this(using this answer):
switch (v.getId()){
case R.id.button1:
fragment = new Fragment1();
break;
case R.id.button2:
fragment = new Fragment2();
break;
default:
return;
}
In your code, in the if that is checked upon a click (for example after clicking button1) android asks v (the clicked View) for its tag - but as none was set using View#setTag - it returns null which is of course not equal to the String object created for "button1", thus the if reverts to the else every time.

How to pass value to viewpager fragment from other activity?

Here let me explain my requirement i have two tabs of viewpager namely task and calls . There is one button in task fragment when user clicks that it will go to new activity from there users will enter the values in edittext then the values from this activity need to populate listview in task fragment of that viewpager how can i do this. So far what i have tried is:
THis is my Main activity:
package servicefiirst.precision.activitiestabs;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Bundle bundle=getIntent().getExtras();
// Intent intent=getIntent();
// ActivityView activityView=(ActivityView)intent.getSerializableExtra("yog");
// intent.putExtra("yogs",activityView);
// Bundle bundle=new Bundle();
// bundle.putSerializable("yogs",activityView);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String yogan = bundle.getString("yog");
String yogans = bundle.getString("yogs");
Bundle bundle1 = new Bundle();
bundle.putString("yoges", yogan);
bundle.putString("yogesh", yogans);
Task task = new Task();
task.setArguments(bundle1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
/**
* 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:
Task task=new Task();
return task;
case 1:
Calls calls=new Calls();
return calls;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Task";
case 1:
return "Call";
}
return null;
}
}
}
This is Task fragment in viewpager where listview is there:
package servicefiirst.precision.activitiestabs;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class Task extends Fragment
{
List<ActivityView>activityViews;
ActivityView activityView=new ActivityView();
ActivityListAdapter activityListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview= inflater.inflate(R.layout.yog,container,false);
ListView listview=(ListView)rootview.findViewById(R.id.listView);
if (activityViews == null)
{
activityViews = new ArrayList<ActivityView>();
}
if(getArguments()!=null) {
getArguments().getSerializable("yog");
}
activityViews.add(activityView);
activityListAdapter = new ActivityListAdapter(getActivity(), R.id.listView, activityViews);
listview.setAdapter(activityListAdapter);
activityListAdapter.notifyDataSetChanged();
Button btn=(Button)rootview.findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), DetailActivity.class);
startActivity(intent);
}
});
return rootview;
}
}
This is detail activity where data go to populate listview in task fragment:
package servicefiirst.precision.activitiestabs;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class DetailActivity extends AppCompatActivity {
ActivityView activityView = new ActivityView();
// public static String endpoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final EditText editText = (EditText) findViewById(R.id.editText);
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.yog, R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
final Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityView.setDescription(editText.getText().toString());
activityView.setStatus(spinner.getSelectedItem().toString());
// Bundle bundle=new Bundle();
// bundle.putSerializable("yog", activityView);
Task task=new Task();
//task.setArguments(bundle);
android.support.v4.app. FragmentManager fm=getSupportFragmentManager();
android.support.v4.app. FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.container,task,"");
ft.commit();
}
});
}
}
how to navigate data from other activity to fragment of viewpager of other acitivity? can anybody help me
Please use static variable to save the value from your activity and then resuse it in task fragment by calling the task fragment of viewpager activity , i guess it would helps you..!!
Start the activity from task fragment using
startActivityForResult(Intent intent, int requestCode)
method, it will let fragment to receive result data from the activity. In new Activity when button is pressed to populate values save the values to a intent so you can send that intent to fragment by using
setResult(intent) // setResult has other overloaded methods pick them to your requirement
method of Activity class in your button onClickListener onClick() method.
Ex : onClick() {
intent.putString("name", editText.getText());
setResult(intent); // setting the intent as result to receive at fragment
this.finish(); // To finish the activity
}
When activity gets finished(when you call finish() or press back button)
onActivityResult(intent)
method of Fragment which started the activity will be automatically called. you can use this method to retrieve the intent which contained the populated data.

How to pass value between activity and viewpager fragment? [duplicate]

This question already has answers here:
Send data from activity to fragment in Android
(22 answers)
Closed 7 years ago.
It may be dumb question but am struggling with this how to pass value between activity and viewpager. Now let me explain my requirement i have two tabs namely task and calls . Having one button in task when user press that it will go to new activity from there will be two forms one is edittext and spinner need to populate listview in task fragment from that activity data so far what i have tried is:
This is my Main activity:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Bundle bundle=getIntent().getExtras();
// Intent intent=getIntent();
// ActivityView activityView=(ActivityView)intent.getSerializableExtra("yog");
// intent.putExtra("yogs",activityView);
// Bundle bundle=new Bundle();
// bundle.putSerializable("yogs",activityView);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String yogan = bundle.getString("yog");
String yogans = bundle.getString("yogs");
Bundle bundle1 = new Bundle();
bundle.putString("yoges", yogan);
bundle.putString("yogesh", yogans);
Task task = new Task();
task.setArguments(bundle1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
/**
* 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:
Task task=new Task();
return task;
case 1:
Calls calls=new Calls();
return calls;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Task";
case 1:
return "Call";
}
return null;
}
}
}
This is my task fragment(where listview is gets populated)
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class Task extends Fragment
{
List<ActivityView>activityViews;
ActivityView activityView=new ActivityView();
ActivityListAdapter activityListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview= inflater.inflate(R.layout.yog,container,false);
ListView listview=(ListView)rootview.findViewById(R.id.listView);
if (activityViews == null)
{
activityViews = new ArrayList<ActivityView>();
}
if(getArguments()!=null) {
getArguments().getSerializable("yog");
}
activityViews.add(activityView);
activityListAdapter = new ActivityListAdapter(getActivity(), R.id.listView, activityViews);
listview.setAdapter(activityListAdapter);
activityListAdapter.notifyDataSetChanged();
Button btn=(Button)rootview.findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), DetailActivity.class);
startActivity(intent);
}
});
return rootview;
}
}
This is the activity where data go to populate listview in task fragment:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class DetailActivity extends AppCompatActivity {
ActivityView activityView = new ActivityView();
// public static String endpoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final EditText editText = (EditText) findViewById(R.id.editText);
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.yog, R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
final Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityView.setDescription(editText.getText().toString());
activityView.setStatus(spinner.getSelectedItem().toString());
// Bundle bundle=new Bundle();
// bundle.putSerializable("yog", activityView);
Task task=new Task();
//task.setArguments(bundle);
android.support.v4.app. FragmentManager fm=getSupportFragmentManager();
android.support.v4.app. FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.container,task,"");
ft.commit();
}
});
}
}
Here how to pass data between activity and fragment of viewpager can anybody help me out? Thanks in advance!
You can use a Bundle to pass datas from an Activity to a Fragment:
In the Activity, create your Bundle and add it to the Fragment
Bundle myBundle = new Bundle();
myBundle .putLong( "exampleId", mExampleId);
myBundle .putString("exampleName", mName);
...
myFragment.setArguments( myBundle );
Then, when the Fragment is created, get the values in your Bundle using the function getArguments() like:
Long exampleId = getArguments().getLong("exampleId");
And even set a default value if you don't find the key in your Bundle
String exampleName = getArguments().getString( "exampleName", "None"));
You should create a NewInstance method inside your fragment. In short, it could look like this:
public class MyFragment {
private int value;
private static final String ARG_VALUE = "argValue";
public static MyFragment NewInstance(int value) {
Bundle args = new Bundle();
args.putInt(ARG_VALUE, value);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate() {
Bundle args = getArguments();
this.value = args.getInt(ARG_VALUE, 0); // Default 0 if key not found.
}
}
And you just pass in that value anytime you create the fragment:
MyFragment tenFragment = MyFragment.newInstance(10);
Then it can be used in a fragment transaction or inserted into a FragmentStatePagerAdapter however you need it. The same principle applies to any data type, so you can do this if you need to pass in Strings, or your own serializable object, etc.

I'm trying to add sliding tabs in eclipse, but something isn't working

i'm trying to add sliding tabs in my application following one guide from google, but i'm getting this error when i try to start application:
05-29 02:04:40.353: E/AndroidRuntime(21092): java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
05-29 02:50:06.212: E/AndroidRuntime(3506): at com.tabs.dusandimitrijevic.Tab1.onCreate(Tab1.java:33)
Here are my one Fragment Tab:
package com.tabs.dusandimitrijevic;
import com.dusandimitrijevic.spisakzakupovinu.R;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by hp1 on 21-01-2015.
*/
//In this case, the fragment displays simple text based on the page
public class Tab1 extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static Tab1 newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
Tab1 fragment = new Tab1();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_1, container, false);
TextView textView = (TextView) view;
textView.setText("Fragment #" + mPage);
return view;
}
}
And here are my FragmentPagerAdapter:
package com.tabs.dusandimitrijevic;
import android.R;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by hp1 on 21-01-2015.
*/
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[] { "Tab1", "Tab2", "Tab3" };
private Context context;
public SampleFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Tab1();
case 1:
return new Tab2();
case 2:
return new Tab3();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
And here are my MainActivity:
package com.dusandimitrijevic.spisakzakupovinu;
import java.util.ArrayList;
import com.tabs.dusandimitrijevic.SampleFragmentPagerAdapter;
import com.tabs.dusandimitrijevic.SlidingTabLayout;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
MainActivity.this));
// Give the SlidingTabLayout the ViewPager
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.tabs);
// Center the tabs in the layout
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(viewPager);
}
#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) {
Toast.makeText(MainActivity.this, "Ovo su podešavanja", Toast.LENGTH_SHORT).show();
return true;
}
if(id == R.id.navigate){
Intent i= new Intent(MainActivity.this, SubActivity.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Can anyone help me with this?
You have coded a static factory function to create your fragments , but you don't use it ?!
Your adapter should create the fragments using it:
#Override
public Fragment getItem(int position) {
return Tab1.newInstance(position);
}

TabHost inside Fragment when select an item in slide menu

My project allows user can use slide menu function (on the left). On slide menu, user can select 4 items: Zero, One, Two, and Three. My project has action bar.
When user clicked Zero item, a screen is displayed. When user clicked One, Two, Three, screen is displayed and similar. One, Two, and Three Screen is designed as TabView. You can see project to understand it easier:
With Zero item it runs OK. However, I meet problem when coding One, Two, Three. When I select them, error happens. I don't know more about Fragment and Tabhost.
Here is code where I selected an any item (in MainActivity.java):
private void selectItem(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
Fragment fragment = new ZeroItem();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
break;
case 1: break;
case 2: break;
case 3: break;
}
}
Case 0 (it means you select Zero item, Zero Item screen is displayed)
ZeroItem.java
package com.example.android.navigationdrawerexample;
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
public class ZeroItem extends Fragment {
public ZeroItem() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_zero_item,
container, false);
return rootView;
}
}
Now, I want you help me write code in case 1, case 2, case 3. It's similar. It must call TabHost.java
Here is TabHost:
package com.ramesh.fragmenttabhostdemo;
import com.example.android.navigationdrawerexample.R;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.Menu;
public class TabHost extends FragmentActivity {
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bottom_tabs);
// mTabHost = new FragmentTabHost(this);
// mTabHost.setup(this, getSupportFragmentManager(),
// R.id.menu_settings);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
Bundle b = new Bundle();
b.putString("key", "1");
mTabHost.addTab(mTabHost.newTabSpec("1").setIndicator("1"),
OneItem.class, b);
//
b = new Bundle();
System.out.print("hello git");
b.putString("key", "2");
mTabHost.addTab(mTabHost.newTabSpec("2")
.setIndicator("2"), TwoItem.class, b);
b = new Bundle();
b.putString("key", "3");
mTabHost.addTab(mTabHost.newTabSpec("3").setIndicator("3"),
ThreeItem.class, b);
// setContentView(mTabHost);
}
#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;
}
}
OneItem.java
package com.ramesh.fragmenttabhostdemo;
import com.example.android.navigationdrawerexample.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class OneItem extends Fragment {
private TextView text;
public OneItem() {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = LayoutInflater.from(getActivity()).inflate(R.layout.layout,
null);
text = (TextView) v.findViewById(R.id.text);
if (getArguments() != null) {
//
try {
String value = getArguments().getString("key");
text.setText("1");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
//
}
TwoItem.java
package com.ramesh.fragmenttabhostdemo;
public class TwoItem extends OneItem {
}
ThreeItem.java
package com.ramesh.fragmenttabhostdemo;
import com.ramesh.fragmenttabhostdemo.OneItem;
import com.ramesh.fragmenttabhostdemo.TwoItem;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ThreeItem extends OneItem {
private FragmentTabHost mTabHost;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mTabHost = new FragmentTabHost(getActivity());
Bundle b = new Bundle();
b.putString("key", "1");
mTabHost.addTab(mTabHost.newTabSpec("1").setIndicator("1"),
OneItem.class, b);
//
b = new Bundle();
b.putString("key", "2");
mTabHost.addTab(mTabHost.newTabSpec("2")
.setIndicator("2"), TwoItem.class, b);
return mTabHost;
}
}
Can you download my project here.
Use getChildFragmentManager() instead of getFragmentManager().
If this Fragment is a child of another Fragment, the FragmentManager
returned here will be the parent's getChildFragmentManager().
quoted from http://developer.android.com/reference/android/app/Fragment.html

Categories

Resources