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

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.

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.

Send data from fragment to fragment using Tab Layout with Swipeable Views in Android

I created a Tab Layout with Swipeable Views.
I'm trying to pass a string from fragment
to Fragment Thank you in Advance
Details_customer.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
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.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class Details_customer extends AppCompatActivity implements Cust_Details_basic.FragmentDataListener {
SharedPreferences login_pref, IP;
private ProgressDialog pDialog;//For Loading activity..
Bundle dataBundle;
/**
* The {#link 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 FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_customer);
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);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onFragmentDataUpdated(Bundle dataBundle)
{
this.dataBundle=dataBundle;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
//getMenuInflater().inflate(R.menu.menu_details_customer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
login_pref = getSharedPreferences("Login Pref", MODE_PRIVATE);
SharedPreferences.Editor editor = login_pref.edit();
editor.putString("username", null);
Intent intent = new Intent(this, MainActivity.class);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Logout", Toast.LENGTH_SHORT).show();
/*editor.clear();*/
editor.commit();
finish();
break;
}
return super.onOptionsItemSelected(item);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Details_customer Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
//deleted
/**
* 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) {
switch (position) {
case 0:
Cust_Details_basic cust_basic = new Cust_Details_basic();
cust_basic.setArguments(dataBundle);
return cust_basic;
case 1:
Cust_Details_address address = new Cust_Details_address();
address.setArguments(dataBundle);
return address;
/* case 2:
Cust_Details_last details_last = new Cust_Details_last();
return details_last;*/
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
/***
* new addition
***/
public void showFragment(String val) {
System.out.println(val);
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Basic Info";
case 1:
return "Address";
/* case 2:
return "Address";*/
}
return null;
}
}}
Cust_Details_basic.java Here is my Edittext i want to send the value to next fragment
public class Cust_Details_basic extends Fragment {
EditText finame;
private ProgressDialog pDialog;//For Loading activity..
public interface FragmentDataListener{
void onFragmentDataUpdated(Bundle dataBundle);
}
private FragmentDataListener mFragmentDataListener;
#Override
public void onAttach( Context context )
{
super.onAttach( context );
mFragmentDataListener=(FragmentDataListener)getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_1, container, false);
finame = (EditText)view.findViewById(R.id.fname);
/**********************************************/
Bundle bundle = new Bundle();
bundle.putString("fname",finame.getText().toString());
mFragmentDataListener.onFragmentDataUpdated(bundle);
/*********************************************/
return view;
}}
Here is Cust_Details_address.java here i want Edittext value
public class Cust_Details_address extends Fragment implements View.OnClickListener{
Button btnsubmit;
String fname,firstname;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_2, container, false);
Bundle bundle = this.getArguments();
if (bundle != null) {
firstname = bundle.getString("fname",fname);
Toast.makeText(getActivity().getApplicationContext(),"fname:"+firstname,Toast.LENGTH_SHORT).show();
Log.d("First Name:","=======>"+firstname);
}
else{
Toast.makeText(getActivity().getApplicationContext(),"Am Empty:",Toast.LENGTH_SHORT).show();
}
btnsubmit = (Button)view.findViewById(R.id.btnsubmit);
btnsubmit.setOnClickListener(this);
return view;
}}
In Cust_Details_address.java I Override the method like this
#Override
public void onStart(){
super.onStart();
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstname = ((EditText)getActivity().findViewById(R.id.fname)).getText().toString();
Toast.makeText(getActivity().getApplicationContext(),"Hi "+firstname ,Toast.LENGTH_SHORT).show();
} });
I got the result which i have accepted. Thank you so much 'Talha' for your needful help.
CallBacks(interface) and Bundles are recommended way but this is a quick solution:
YourActivity:
public void randomMethod(String val){
System.out.println(val);
}
Fragment1:
onClick(){
((YourActivity) getActivity()).randomMethod(yourString1);
}
Fragment2:
onClick(){
((YourActivity) getActivity()).randomMethod(yourString2);
}
You can call that method from any fragment of an activity and use the updated value.
In your activity define interface, bundle object, then call interface method of Activity instance with data from your fragment:
In Details_customer activity you do this,
public class Details_customer extends AppCompatActivity
implements Cust_Details_basic.FragmentDataListener {
SharedPreferences login_pref,IP;
private ProgressDialog pDialog;//For Loading activity..
Bundle dataBundle;
..... other code
// override method of interface
#override void onFragmentDataUpdated(Bundle dataBundle)
{
this.dataBundle=dataBundle;
}
...... other code
// in SectionsPagerAdapter adapter
#Override public Fragment getItem(int position) {
switch (position) {
case 0:
Cust_Details_basic cust_basic = new Cust_Details_basic();
cust_basic.setArguments(dataBundle); // remember to update
//bundle object as per requirement
return cust_basic;
case 1:
Cust_Details_address address = new Cust_Details_address();
address.setArguments(dataBundle);
return address;
/* case 2:
Cust_Details_last details_last = new Cust_Details_last();
return details_last;*/
}
return null;
}
In your Cus_Details_basic Fragment, declare interface:
public class Cust_Details_basic extends Fragment {
public interface FragmentDataListener{
void onFragmentDataUpdated(Bundle dataBundle);
}
private FragmentDataListener mFragmentDataListener;
// create fragment object and initialize it in onAttach()
#Override public void onAttach( Context context )
{
super.onAttach( context );
mFragmentDataListener=(FragmentDataListener)getActivity();
}
// then update your onCreate as:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_1, container, false);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("fname",fname);
//fragment.setArguments(bundle);
mFragmentDataListener.onFragmentDataUpdated(bundle);
// this will update dataBundle object in your activity
return view;
}
This will call onFragmentDataUpdated() of your Details_customer class, which will update its dataBundle object, now whenever Viewpager changes, you should be able to setArguments() with this Bundle object, and eventually getArguments() in onCreate of that fragment will be able to retrieve data.
Useful links:
Communicating between Fragments.
How To Communicate Between Fragments and Activities in Android.
Since all the fragment are in view pager that means they share the same activity.So just put the value inside the intent and get it in any fragment of that view pager, no need to pass the data separately in bundle.
In your Cust_Details_basic Fragment (Save it like this)
getActivity().getIntent().putExtra("name",fname);
In Cust_Details_address Fragment (Get it like this )
String fname = getActivity().getIntent().getStringExtra("name");

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

Populate 3 ListViews from a Database in three Fragments

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

Categories

Resources