Populate 3 ListViews from a Database in three Fragments - android

I'm working on an app that allows the user to add an item to a list (todo list). The user has the choise of which list the item will go into. The app uses Tabbed Views (Simular to Skype), and I need to be able to populate the lists from the Database (SQLite).
My MainActivity.java :
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.speech.RecognizerIntent;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import static com.example.todo.Constants.*;
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.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static String[] FROM = { _ID, TODO_TEXT, LOCATION, };
private static int[] TO = { R.id.todoTextView };
private static String ORDER_BY = ORDER + " DESC";
ListView taskListView;
/**
* 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;
public Button speakButton;
/**
* 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());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Context context = this;
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAlert();
}
});
Cursor cursor = getEvents();
showEvents(cursor);
}
private void addEvent(String string) {
// Insert a new record into the Events data source.
// You would do something similar for delete and update.
ContentValues values = new ContentValues();
values.put(ORDER, System.currentTimeMillis());
values.put(REMINDER_TEXT, string);
getContentResolver().insert(CONTENT_URI, values);
}
#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;
}
void showAlert(){
final EditText reminderinput = (EditText) findViewById(R.id.reminderText);
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
adb.setView(inflater.inflate(R.layout.dialog_new_reminder, null))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id) {
// save reminder here
Editable reminderText = reminderinput.getText();
String reminderTextString = String.valueOf(reminderText);
addEvent(reminderTextString);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//it already cancels
}
});
adb.setTitle("Set a reminder");
AlertDialog ad = adb.create();
ad.show();
}
private Cursor getEvents() {
// Perform a managed query. The Activity will handle closing
// and re-querying the cursor when needed.
return managedQuery(CONTENT_URI, FROM, null, null, ORDER_BY);
}
private void showEvents(Cursor cursor) {
// Set up data binding
ListView mListView = (ListView) findViewById(R.id.listview);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.task_item, cursor, FROM, TO);
mListView.setAdapter(adapter);
}
#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) {
Intent intent = new Intent(this, AppSettings.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Important";
case 1:
return "Kinda Important";
case 2:
return "Not very Important";
}
return null;
}
}
}
Obviously, i have a Constants.java and also some layout files in the project.
Unfortunately, the app throws an error saying:
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
HELP!

So you have the listviews in your fragment and you are doing
ListView mListView = (ListView) findViewById(R.id.listview);
This finds the listview in activity_main and not the fragment.
You should populate the listviews in the fragment.
Call this in the fragment.
ListView mListView = rootview.findViewById(R.id.listview);
Cursor cursor = getEvents();
showEvents(cursor);

Related

Unable to distinguish between two fragments with chart click events

I have implemented two pie charts in two different fragments. Whenever I click on a pie chart it will call the second fragments click events on both fragments.
Here is my MainActivity.java code.
package longitude.com.anychart;
import android.content.res.Resources;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.dataentry.ValueDataEntry;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
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}.
*/
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private AccountDashboardAdapter mSectionsPagerAdapter;
#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.
mViewPager = (ViewPager) findViewById(R.id.container);
//mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ArrayList<DataEntry> dateData = new ArrayList<>();
dateData.add(new ValueDataEntry("Apples", 123456));
dateData.add(new ValueDataEntry("Pears", 852465));
dateData.add(new ValueDataEntry("Bananas", 753159));
dateData.add(new ValueDataEntry("Grapes", 963215));
dateData.add(new ValueDataEntry("Oranges", 415263));
ArrayList<DataEntry> collectorData = new ArrayList<>();
collectorData.add(new ValueDataEntry("Applessssss", 6371664));
collectorData.add(new ValueDataEntry("Pearsssss", 789622));
collectorData.add(new ValueDataEntry("Bananasssss", 7216301));
collectorData.add(new ValueDataEntry("Grapesssss", 1486621));
collectorData.add(new ValueDataEntry("Orangesssss", 1200000));
HashMap<String, ArrayList<DataEntry>> childData=new LinkedHashMap<>();
childData.put("Apples",collectorData);
childData.put("Pears",collectorData);
childData.put("Bananas",collectorData);
childData.put("Grapes",collectorData);
childData.put("Oranges",collectorData);
childData.put("Applessssss",dateData);
childData.put("Pearsssss",dateData);
childData.put("Bananasssss",dateData);
childData.put("Grapesssss",dateData);
childData.put("Orangesssss",dateData);
mSectionsPagerAdapter = new AccountDashboardAdapter(getResources(), getSupportFragmentManager(), dateData, collectorData, childData);
mViewPager.setOffscreenPageLimit(5);
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class AccountDashboardAdapter extends FragmentStatePagerAdapter {
private final List<DataEntry> collectorData;
private final HashMap<String, ArrayList<DataEntry>> childData;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
List<DataEntry> dateData;
/**
* Create pager adapter
*
* #param resources
* #param fm
* #param data
* #param childData
*/
public AccountDashboardAdapter(final Resources resources, FragmentManager fm, List<DataEntry> data, List<DataEntry> collectorData, HashMap<String, ArrayList<DataEntry>> childData) {
super(fm);
this.dateData = data;
this.collectorData = collectorData;
this.childData = childData;
}
#Override
public Fragment getItem(int position) {
final Fragment result;
switch (position) {
case 0:
// First Fragment of First Tab
//result = new DatewiseAccountDashboardFragment();
result = new fragment1();
Bundle bundle = new Bundle();
bundle.putSerializable("data", (Serializable) dateData);
bundle.putSerializable("childData", childData);
result.setArguments(bundle);
break;
case 1:
// First Fragment of Second Tab
//result = new CollectorwiseAccountDashboardFragment();
result = new fragment2();
Bundle bundle1 = new Bundle();
bundle1.putSerializable("data", (Serializable) collectorData);
bundle1.putSerializable("childData", childData);
result.setArguments(bundle1);
break;
case 2:
// First Fragment of Second Tab
//result = new CollectorwiseAccountDashboardFragment();
result = new fragment1();
Bundle bundle2 = new Bundle();
bundle2.putSerializable("data", (Serializable) dateData);
bundle2.putSerializable("childData", childData);
result.setArguments(bundle2);
break;
default:
result = null;
break;
}
return result;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(final int position) {
switch (position) {
case 0:
return "DATEWISE";
case 1:
return "COLLECTORWISE";
default:
return null;
}
}
/**
* On each Fragment instantiation we are saving the reference of that Fragment in a Map
* It will help us to retrieve the Fragment by position
*
* #param container
* #param position
* #return
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
/**
* Remove the saved reference from our Map on the Fragment destroy
*
* #param container
* #param position
* #param object
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
/**
* Get the Fragment by position
*
* #param position tab position of the fragment
* #return
*/
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}
My First Fragment1.java code
package longitude.com.anychart;
import android.app.Activity;
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.Toast;
import com.anychart.APIlib;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.listener.Event;
import com.anychart.chart.common.listener.ListenersInterface;
import com.anychart.charts.Pie;
import com.anychart.enums.Align;
import com.anychart.enums.LegendLayout;
import java.util.List;
public class Fragment1 extends Fragment {
private AnyChartView anyChartView;
private List<DataEntry> data;
private Pie pie;
public Fragment1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
data = (List<DataEntry>) getArguments().getSerializable("data");
//childData = (HashMap<String, ArrayList<DataEntry>>) getArguments().getSerializable("childData");
getArguments().remove("data");
getArguments().remove("childData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
anyChartView = rootView.findViewById(R.id.any_chart_view1);
anyChartView.setProgressBar(rootView.findViewById(R.id.progress_bar1));
showChart(anyChartView, data);
return rootView;
}
private void showChart(AnyChartView anyChartView, List<DataEntry> data) {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
pie = AnyChart.pie();
pie.data(data);
pie.title("1st Anychart Title");
//pie.labels().position("outside");
pie.innerRadius(50);
pie.legend().title().enabled(true);
pie.legend().title(false);
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL_EXPANDABLE)
.align(Align.CENTER);
//pie.fill("aquastyle");
pie.labels().format("{%x}\\n{%value}");
anyChartView.setChart(pie);
pie.tooltip(false);
pie.setOnClickListener(new ListenersInterface.OnClickListener(new String[]{"x", "value"}) {
#Override
public void onClick(Event event) {
Toast.makeText(getActivity(), "Fragment1==>" + event.getData().get("x") + ":" + event.getData().get("value"), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
My Second Fragment2.java code
package longitude.com.anychart;
import android.app.Activity;
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.Toast;
import com.anychart.APIlib;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.listener.Event;
import com.anychart.chart.common.listener.ListenersInterface;
import com.anychart.charts.Pie;
import com.anychart.enums.Align;
import com.anychart.enums.LegendLayout;
import java.util.List;
public class Fragment2 extends Fragment {
private AnyChartView anyChartView;
private List<DataEntry> data;
private Pie pie;
public Fragment2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
data = (List<DataEntry>) getArguments().getSerializable("data");
//childData = (HashMap<String, ArrayList<DataEntry>>) getArguments().getSerializable("childData");
getArguments().remove("data");
getArguments().remove("childData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
anyChartView = rootView.findViewById(R.id.any_chart_view1);
anyChartView.setProgressBar(rootView.findViewById(R.id.progress_bar1));
showChart(anyChartView, data);
return rootView;
}
private void showChart(AnyChartView anyChartView, List<DataEntry> data) {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
pie = AnyChart.pie();
pie.data(data);
pie.title("2nd Anychart Title");
//pie.labels().position("outside");
pie.innerRadius(50);
pie.legend().title().enabled(true);
pie.legend().title(false);
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL_EXPANDABLE)
.align(Align.CENTER);
//pie.fill("aquastyle");
pie.labels().format("{%x}\\n{%value}");
anyChartView.setChart(pie);
pie.tooltip(false);
pie.setOnClickListener(new ListenersInterface.OnClickListener(new String[]{"x", "value"}) {
#Override
public void onClick(Event event) {
Toast.makeText(getActivity(), "Fragment2==>"+event.getData().get("x") + ":" + event.getData().get("value"), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btn_back"
android:enabled="false"
android:layout_width="60dp"
android:layout_height="40dp"
android:text="BACK" />
<com.anychart.AnyChartView
android:id="#+id/any_chart_view1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progress_bar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Here is my code link: https://drive.google.com/file/d/1YnIL1fE52W_Gy4yuc2rYb4fh4Y1hGNuG/view?usp=sharing
Unfortunately, now we have no idea what exactly happens with event dispatching in Fragments. But I would like to bring to your attention that there's a possible workaround.
Click on a chart returns correct point name and value. Only the fragment name is wrong. The name is hardcoded in the click event handler.
So if the fragment name is not required in output, you can just drop it. If the name is required you can apply a specific ID to the Fragment and then get that ID from active fragment view. This should solve the issue as a temporary workaround.

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.

How to navigate data between activity and fragment of other activity?

It may be dumb question but it is still confusing how to pass navigate data from activity to fragment of other activity how can i achieve this i have searched and tired still i cannot find anything can somebody help me out. Now let me tell my requirement am having tabactivity in one of the tab i have listview when i click listivew item it must goes to other activity where the data will go and populate the listview in tabs how can i achieve this so far what i have tried is
This is my tab activity:
package servicefiirst.precision.activitiestabs;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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;
import android.view.View;
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());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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 the fragment where listview getspopulated:
package servicefiirst.precision.activitiestabs;
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;
/**
* Created by 4264 on 08-01-2016.
*/
public class Task extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview= inflater.inflate(R.layout.yog,container,false);
Listview lv=(Listview)rootview.findviewbyId(R.id.lv);
lv.setOnItemClickListener(new OnItemClickListener(
#Override
public void onClick(View v) {
Intent intent=new Intent(getActivity,DetailActivity.class)
startactivity(intent);
}
});
return rootview;
}
}
Use a bundle to transfer data from one activity to another activity
Bundle bundle = new Bundle();
bundle.putString("KEY_NAME", "Abrakadabra");
Intent i = new Intent(this, MyActivityName.class);
i.putExtras(bundle);
startActivity(i) <-- new activity started
Then in the receiving activity: Put this code in the onCreate method
Bundle bundle = getIntent().getExtras();
String stringdata = bundle.getString("KEY_NAME");
To pass data from activity to fragment: Put this code anywhere
Bundle bundle = new Bundle();
bundle.putString("KEY_NAME", "Abrakadabra");
MyFragment myfragment = new MyFragment();
myfragment.setArguments(bundle);
Then in the onCreateView method of the fragment add this code
Bundle args = getArguments();
String stringdata = args.getString("KEY_NAME");
Try this for sending data to another activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView c = (TextView) view.findViewById(R.id.label);
String source = c.getText().toString();
Intent intent = new Intent(MetroFrom.this, Metro.class);
intent.putExtra("From", source);
startActivity(intent);
}
});
Then put this code on which activity you want to receive data
Intent intent = getIntent();
etsource.setText(intent.getStringExtra("from"));

Having trouble setting dynamic content within Fragments

In my MainActivity I have a list, and when an item is clicked, I go into my ScreenSlideActivity. This activity will produce a Fragment from another class I have called ScreenSlidePageFragment, and will produce a handful of Fragments for me when I swipe. I need the content in these Fragments to be unique depending on whichever item in the list I selected. Unfortunately I haven't been successful at this.
I've tried creating a set_all_data(string_data){} function inside the ScreenSlidePageFragment and the calling it/updating the textView before I create the Fragment, but I think I'm either getting a race condition with the new text, or I'm just doing it wrong and don't understand Fragments well enough.
ScreenSlideActivity
package com.example.dgzl.corvegas;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
/**
* Demonstrates a "screen-slide" animation using a {#link ViewPager}. Because {#link ViewPager}
* automatically plays such an animation when calling {#link ViewPager#setCurrentItem(int)}, there
* isn't any animation-specific code in this sample.
*
* <p>This sample shows a "next" button that advances the user to the next step in a wizard,
* animating the current screen out (to the left) and the next screen in (from the right). The
* reverse animation is played when the user presses the "previous" button.</p>
*
* #see ScreenSlidePageFragment
*/
public class ScreenSlideActivity extends android.support.v4.app.FragmentActivity {
/* The number of pages (wizard steps) to show in this demo.*/
private static final int NUM_PAGES = 3;
/* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.*/
private ViewPager mPager;
/* The pager adapter, which provides the pages to the view pager widget.*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
final String biz_data[] = in.getStringArrayExtra("biz_data");
set_fragment_data(biz_data);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
}
});
}
public void onFragClick (View view){
Toast.makeText(ScreenSlideActivity.this, "button", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
// enable 'prev' and 'next' when not on first node
menu.findItem(R.id.action_prev).setEnabled(mPager.getCurrentItem() > 0);
menu.findItem(R.id.action_next).setEnabled(mPager.getCurrentItem() < (NUM_PAGES-1));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 16908332:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
finish();
return true;
case R.id.action_prev:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
String test_data = "Soem data";
ScreenSlidePageFragment newFrag = new ScreenSlidePageFragment();
newFrag.set_all_data(test_data);
Fragment newFragment = newFrag.create(position);
return newFragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
public void set_fragment_data(String biz_data[]){
// title as business name
setTitle(biz_data[1]);
}
}
ScreenSlidePageFragment
package com.example.dgzl.corvegas;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* A fragment representing a single step in a wizard. The fragment shows a dummy title indicating
* the page number, along with some dummy text.
*
* <p>This class is used by the {#link } and {#link
* ScreenSlideActivity} samples.</p>
*/
public class ScreenSlidePageFragment extends android.support.v4.app.Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
/**
* The fragment's page number, which is set to the argument value for {#link #ARG_PAGE}.
*/
private int mPageNumber;
public String[] todays_data, biz_data, special_data;
public String all_data = "hardcoded and not good";
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
Log.d("OnCreateView: ", "2");
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView;
Log.d("OnCreateView: ", "1");
TextView tv;
switch(getPageNumber()){
case 0:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_today, container, false);
tv = (TextView)rootView.findViewById(R.id.today_frag_tv);
tv.setText(R.string.today_frag);
break;
case 1:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_business, container, false);
tv = (TextView)rootView.findViewById(R.id.biz_frag_tv);
tv.setText(all_data);
break;
case 2:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_specials, container, false);
tv = (TextView)rootView.findViewById(R.id.specials_frag_tv);
tv.setText(R.string.special_frag);
break;
default:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_today, container, false);
tv = (TextView)rootView.findViewById(R.id.today_frag_tv);
tv.setText(R.string.today_frag);
}
// Set the title view to show the page number.
// ((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.title_template_step, mPageNumber + 1));
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
public void set_data(String[] todays_data, String[] biz_data, String[] special_data) {
this.todays_data = todays_data;
this.biz_data = biz_data;
this.special_data = special_data;
}
public void set_all_data(String all_data) {
this.all_data = all_data;
}
public void get_data() {
}
}
The problem is in getItem() method. You are creating a new ScreenSlidePageFragment, and after that, you call create() method that creates a new ScreenSlidePageFragment again. You need to call ScreenSlidePageFragment.create(position) in a static way.
#Override
public Fragment getItem(int position) {
String test_data = "Soem data";
ScreenSlidePageFragment newFrag = ScreenSlidePageFragment.create(position);
newFrag.set_all_data(test_data);
return newFragment;
}

Categories

Resources