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.
Related
I Create a tabbed activity from android studio from the options. Then i tried to add Navigation Bar. Now its giving me error on
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
The error is
Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]
Code:
MainActivity.java
package com.example.android.myves;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
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.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
/**
* 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);
dl = (DrawerLayout)findViewById(R.id.d1);
t = new ActionBarDrawerToggle(this, dl,R.string.Open, R.string.Close);
t.setDrawerIndicatorEnabled(true);
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nv = (NavigationView)findViewById(R.id.nv);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch(id)
{
case R.id.lib:
Toast.makeText(MainActivity.this, "My Account",Toast.LENGTH_SHORT).show();
case R.id.evt:
Toast.makeText(MainActivity.this, "Settings",Toast.LENGTH_SHORT).show();
case R.id.que:
Toast.makeText(MainActivity.this, "My Cart",Toast.LENGTH_SHORT).show();
default:
return true;
}
}
});
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);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(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;
}
else if(t.onOptionsItemSelected(item))
{
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_t1comps, 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;
}
}
}
What can I do to make the error go away?
First you have to set your SupportActionBar.
Just add the following lines to your code:
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
It's important to declare the SupportActionBar before setting it DisplayHomeAsUpEnabled.
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.
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"));
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);
so I have tested this code on a newer android and when I test it on an older version and click on a button to take me to a page with SwipeView and tabs, I get an error:
The application has stopped unexpectedly. Please try again.
I have set the minimumSDK level in the android manifest to 7. I'm not sure why it won't work on the older android phone.
Here's my code for the SwipeView class:
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SwipeMode extends SherlockFragmentActivity{
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipemode);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home button should show an "Up" caret, indicating that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed in the action bar.
// Create a simple intent that starts the hierarchical parent activity and
// use NavUtils in the Support Package to ensure proper handling of Up.
Intent upIntent = new Intent(this, MainActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is not part of the application's task, so create a new task
// with a synthesized back stack.
TaskStackBuilder.from(this)
// If there are ancestor activities, they should be added here.
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
// This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
//unimplemented methods were automatically added
#Override
public Fragment getItem(int i) {
// TODO Auto-generated method stub
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1); // Our object is just an integer :-P
fragment.setArguments(args);
return fragment;
}
//number of pages
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.text_object, container, false);
Bundle args = getArguments();
//This part sets the integer to string text on the layouts
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
}
Use getSupportActionBar() instead of getActionBar().
getActionBar() is supported from API lvl 11+