I want to pass data from main activity to one tab of TabView.Here is my code and it isn't working,what to do now
There is my codes
MainActivity :
public class MainActivity extends AppCompatActivity {
Button button;
EditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.getInfoButton);
text= (EditText) findViewById(R.id.gitHubUserName);
Logger.addLogAdapter(new AndroidLogAdapter());
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String user = text.getText().toString();
Intent in=new Intent(MainActivity.this,Tab.class);
in.putExtra("SS",user);
Logger.d(user);
Bundle bundle=new Bundle();
bundle.putString("NAME",user);
ProfileActivity pro = new ProfileActivity();
pro.setArguments(bundle);
startActivity(in);
}
});
}
}
my Adapter for tabViews :
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
ProfileActivity profileActivity=new ProfileActivity();
return profileActivity;
case 1:
FollowersActivity followersActivity=new FollowersActivity();
return followersActivity;
case 2:
PublicRepos publicRepos=new PublicRepos();
return publicRepos;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile Info";
case 1:
return "Followers";
case 2:
return "Public Repos";
}
return null;
}
}
and this is ProfileActivity where I want to pass the data which I got from EditText in Main Activity :
public class ProfileActivity extends Fragment {
ImageView imageView;
TextView name;
TextView bio;
String text;
public void dataPass(String txt){
text = txt;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_profile, container, false);
name = rootView.findViewById(R.id.name);
bio = rootView.findViewById(R.id.bio);
Logger.addLogAdapter(new AndroidLogAdapter());
Bundle bundle = this.getArguments();
String nameString = bundle.getString("NAME");
Logger.d(nameString);
name.setText(nameString);
return rootView;
}
}
when I run the app, app stopped working and in logcat this error :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.salman.getgithubofgeek.Activity.Activity.Activites.ProfileActivity.onCreateView(ProfileActivity.java:43)
You cannot use setArguments like that.
Do this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String user = text.getText().toString();
Intent in=new Intent(MainActivity.this,Tab.class);
in.putExtra("SS",user);
in.putExtra("NAME",user);
Logger.d(user);
startActivity(in);
}
});
then in Tab activity, pass the extra to the adapter wherever you call it like so:
PagerAdapter adapter = new PagerAdapter(fm, user);
and make the following changes to the adapter class:
public class PagerAdapter extends FragmentPagerAdapter {
String nameString;
public PagerAdapter(FragmentManager fm, String nameString) {
super(fm);
this.nameString = nameString;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
ProfileActivity profileActivity=new ProfileActivity();
Bundle bundle=new Bundle();
bundle.putString("NAME",nameString);
profileActivity.setArguments(bundle);
return profileActivity;
case 1:
FollowersActivity followersActivity=new FollowersActivity();
return followersActivity;
case 2:
PublicRepos publicRepos=new PublicRepos();
return publicRepos;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile Info";
case 1:
return "Followers";
case 2:
return "Public Repos";
}
return null;
}
}
The problem is you are trying to add the bundle in fragment that is in `
TabActivity
and inPager` you are again declaring ProfileActivity fragment that is with out
setArguments()
.
All you need to do is send the bundle to activity first and then before using ProfileActivity fragment in Pager set the bundle to the ProfileActivity fragment.
Button button;
EditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.getInfoButton);
text= (EditText) findViewById(R.id.gitHubUserName);
Logger.addLogAdapter(new AndroidLogAdapter());
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String user = text.getText().toString();
Intent in=new Intent(MainActivity.this,Tab.class);
in.putExtra("SS",user);
Logger.d(user);
//modification goes here
intent.putString("NAME",user);
startActivity(in);
}
});
}
}
and
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
ProfileActivity profileActivity=new ProfileActivity();
//modifications goes here
Bundle b = new Bundle();
bundle.putString("NAME",user);
profileActivity.setArguments(b);
return profileActivity;
case 1:
FollowersActivity followersActivity=new FollowersActivity();
return followersActivity;
case 2:
PublicRepos publicRepos=new PublicRepos();
return publicRepos;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile Info";
case 1:
return "Followers";
case 2:
return "Public Repos";
}
return null;
}
}
Related
Need a little help on how to approach saving state in my single activity application. I looked at a few resources but couldn't quite find one that fits the build. Essentially I have single activity with a Fragment container view that I'm using to swap out fragments as needed. My issue is that as my activity is destroyed when a lifecycle event occurs, the fragment with my view pager is restored but the individual fragments on the tabs are not loaded. I cannot figure out how to save the state properly. Below is my code:
Activity:
public class StartActivity extends AppCompatActivity {
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mAuth = FirebaseAuth.getInstance();
if (savedInstanceState == null) {
LoginFragment fragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, fragment)
.commit();
}
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){
MainActivity mainActivityFrag = new MainActivity();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, mainActivityFrag)
.commit();
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
}
Fragment With View Pager:
public class MainActivity extends Fragment {
private FirebaseAuth mAuth;
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private TabLayout tabs;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = mAuth = FirebaseAuth.getInstance();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
sectionsPagerAdapter = new SectionsPagerAdapter(getContext(),((AppCompatActivity)getActivity()).getSupportFragmentManager());
viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.showContextMenu();
toolbar = view.findViewById(R.id.topAppBar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
tabs.getTabAt(0).setIcon(R.drawable.home_selector);
tabs.getTabAt(1).setIcon(R.drawable.destination);
tabs.getTabAt(2).setIcon(R.drawable.mail_outline_blk);
tabs.getTabAt(3).setIcon(R.drawable.notification_bell);
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.logout:
mAuth.signOut();
//navigate to home fragment
LoginFragment fragment = new LoginFragment();
((AppCompatActivity)getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout, fragment)
.commit();
return true;
default:
return false;
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Adapter Code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3, R.string.tab_text_4};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mContext = context;
}
#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:
PostFragment postFragment = new PostFragment();
return postFragment;
case 1:
TestFragment userFeedFragmentt = new TestFragment();
return userFeedFragmentt;
default:
TestFragment userFeedFragmenttt = new TestFragment();
return userFeedFragmenttt;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 2 total pages.
return 4;
}
}
I have created a bottomNavigation bar which consists of 5 Fragments, so once each tab is clicked it will switch from one fragment to another.
The question is:The second fragment (Search fragment) have 1 TextView with setOnClickListener so once it is been licked a layout activity will open on the top which includes a ListView to allow the user to select/click on a specific Item, so later on this selected item info should be displayed on that TextView within the(Search fragment).
The issue is that this Textview won't be updated, unless I call the mainActivity to so all fragments in bottom Navigation bar will be updated
My question is how I can refresh that specific fragment without calling the MainActivity.
public class MainActivity extends AppCompatActivity {
final Fragment f1 = new HomeFragment();
final Fragment f2 = new SearchFragment();
final Fragment f3 = new CameraFragment();
final Fragment f4 = new ChatFragment();
final Fragment f6 = new LogginFragment();
final FragmentManager fm = getSupportFragmentManager();
Fragment active = f1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationViewEx bnve = (BottomNavigationViewEx) findViewById(R.id.bottom_navigation);
bnve.enableAnimation(false);
bnve.enableShiftingMode(false);
bnve.enableItemShiftingMode(false);
bnve.setOnNavigationItemSelectedListener(navListener);
if(SharePrefManager.getInstance(this).isLoggedin()){
finish();
startActivity(new Intent(this, SuccessActivity.class));
return;
}
fm.beginTransaction().add(R.id.fragment_container, f6, "6").hide(f6).commit();
//fm.beginTransaction().add(R.id.fragment_container, f5, "5").hide(f5).commit();
fm.beginTransaction().add(R.id.fragment_container, f4, "4").hide(f4).commit();
fm.beginTransaction().add(R.id.fragment_container, f3, "3").hide(f3).commit();
fm.beginTransaction().add(R.id.fragment_container, f2, "2").hide(f2).commit();
fm.beginTransaction().add(R.id.fragment_container, f1, "1").commit();
}
public BottomNavigationViewEx.OnNavigationItemSelectedListener navListener =
new BottomNavigationViewEx.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fm.beginTransaction().hide(active).show(f1).commit();
active = f1;
return true;
case R.id.nav_search:
fm.beginTransaction().hide(active).show(f2).commit();
active = f2;
return true;
case R.id.nav_camera:
fm.beginTransaction().hide(active).show(f3).commit();
active = f3;
return true;
case R.id.nav_chat:
fm.beginTransaction().hide(active).show(f4).commit();
active = f4;
return true;
case R.id.nav_account:
fm.beginTransaction().hide(active).show(f6).commit();
active = f6;
return true;
}
return false;
}
};
}
------------------------SearchFragment Class----------------------------------
This is the search fragment which has the textView (Categories) which supposed to be updated/be refershed without calling the MainActivity
public class SearchFragment extends Fragment {
private Context mContext;
TextView Categories;
static boolean status = false;
String SelectedItem;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search,container,false);
Categories = (TextView) v.findViewById(R.id.categories);
SelectedItem = DataHolder.getInstance().getItem();
Categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(mContext, AllCateActivity.class));
}
});
if(status){Categories.setText(SelectedItem);}
return v;
}
public void ChangeStatus(Boolean status){
this.status = status;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
}
--------------------------DataHolder Class---------------------------------
This works as a design pattern to share arguments between the search fragment and Categories_Activity
public class DataHolder {
private static DataHolder dataHolder = null;
private DataHolder() {
}
public static DataHolder getInstance() {
if (dataHolder == null)
{
dataHolder = new DataHolder();
}
return dataHolder;
}
private String item;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
--------------------------Categories_Activity---------------------------------
This Activity once it's being called a listview will show allowing user to select an item. So once an Item has been selected it will start the MainActivity in order to refresh the Text field in the search Fragment
public class Categories_Activity extends AppCompatActivity implements View.OnClickListener {
ImageView BacktoMainCate;
ListView subCate;
public String selectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_subcategory);
subCate = (ListView)findViewById(R.id.listview_subcate);
BacktoMainCate = (ImageView)findViewById(R.id.BacktoMainCate);
BacktoMainCate.setOnClickListener(this);
final SearchFragment SF = new SearchFragment();
subCate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItem = String.valueOf(parent.getItemAtPosition(position));
DataHolder.getInstance().setItem(selectedItem);
SF.ChangeStatus(true);
Intent in = new Intent(Categories_Activity.this,SuccessActivity.class);
startActivity(in);
});
}
#Override
public void onClick(View v) {
if (v == BacktoMainCate){
//startActivity(new Intent(this,AllCateActivity.class));
finish();
}
}
}
I have used SharedPreferences on both Fragment/Activity life cycle.
So once the Categories_Activity get started, Main Activity will go in onPause and with it all its Fragments will be put in onPause. When user clicks on one of the ListView items in the Categories_Activity, data of that selected item will be store inside SharedPreferences like:
PreferenceManager.getDefaultSharedPreferences(Categories_Activity .this)
.edit().putString(key, selectedItemInfo).apply();
Then override onResume() method inside MainActivity and SearchFragment:
#Override
public void onResume() {
super.onResume();
String value = PreferenceManager.getDefaultSharedPreferences(getContext())
.getString(key, "");
if (value != null && !value.isEmpty()) {
Categories.setText(value);
PreferenceManager.getDefaultSharedPreferences(getContext()).edit().remove(key);
}
}
I am trying a simple interaction between two fragments in Tabbed activity.
I have a two layouts with TextView, EditText and Button. I am trying to achieve move text from EditText in FragmentOne to the EdidText (or TextView) in Fragment two when the Button from FragmentOne is pressed. But it doesnt works.
During debuging there isnt any problem. App doesnt stop working.
Is something problem in ViewPager or SectionsPagerAdapter?
I have this two fragments.
Fragments One:
public class FragmentOne extends Fragment {
TextView textView;
EditText editText;
Button button;
private OnFragmentOneInteractionListener mListener;
public FragmentOne()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_one, container, false);
editText = (EditText) view.findViewById(R.id.fragOne_txb);
textView = (TextView) view.findViewById(R.id.fragTwo_header);
button = (Button) view.findViewById(R.id.fragOne_btn_to2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String text = editText.getText().toString();
mListener.onFragmentOneInteraction(text);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentOneInteractionListener) {
mListener = (OnFragmentOneInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentOneInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnFragmentOneInteractionListener
{
void onFragmentOneInteraction(String string);
}
}
And fragments two:
public class FragmentTwo extends Fragment{
private OnFragmentTwoInteractionListener mListener;
public EditText editText;
public FragmentTwo()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_two, container, false);
editText = (EditText) view.findViewById(R.id.fragTwo_txb);
return view;
}
public void onUpdateEditText(String string)
{
this.editText.setText(string);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentTwoInteractionListener) {
mListener = (OnFragmentTwoInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentTwoInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnFragmentTwoInteractionListener
{
void onFragmentTwoInteraction(Uri uri);
}
}
And this is my main activity:
public class MainActivity extends AppCompatActivity
implements FragmentOne.OnFragmentOneInteractionListener,
FragmentTwo.OnFragmentTwoInteractionListener
{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public void onFragmentOneInteraction(String string)
{
FragmentTwo fr2 = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fr2);
fr2.onUpdateEditText(string);
}
#Override
public void onFragmentTwoInteraction(Uri uri)
{
}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
case 1:
FragmentTwo fragmentTwo = new FragmentTwo();
return fragmentTwo;
default:
return null;
}
}
#Override
public int getCount()
{
// Show 2 total pages.
return 2;
}
}
}
I just tried your code and this is the update i did to make it work. Please mark it correct if its what you are looking for
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public void onFragmentOneInteraction(String string)
{
fragmentTwo.onUpdateEditText(string);
/*FragmentTwo fr2 = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fr2);
fr2.onUpdateEditText(string);*/
}
#Override
public void onFragmentTwoInteraction(Uri uri)
{
}
FragmentTwo fragmentTwo = new FragmentTwo();
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
case 1:
return fragmentTwo;
default:
return null;
}
}
#Override
public int getCount()
{
// Show 2 total pages.
return 2;
}
}
I suggest to use getActivity() instead
if (getActivity() instanceof OnFragmentOneInteractionListener) {
mListener = (OnFragmentOneInteractionListener) getActivity();
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentOneInteractionListener");
}
I have two Edittexts in MainActivity: etFrom and etTo.
When clicked etFrom goes to ListFrom activity and etTo to ListTo activity.ListFrom and ListTo activities contain Listview and after choosing an item it comes back to Main activity and displays results in edittexts. I use MainActivity.putExtra("To",v); and etTo.setText(getIntent().getStringExtra("To")); to get data from an activity.
After clicking on first edittext, choosing an item from Listview and coming back to Main Activity, when I do the same for second edittext the first edittext becomes empty. And the same when I do first one, second one becomes empty.First Second
ListTo Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_to);
etSearchTo=(EditText) findViewById(R.id.etSearchTo);
listViewTo=(ListView) findViewById(R.id.listViewTo);
initList();
listViewTo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v="";
Intent intent=new Intent(ListTo.this,SearchRide.class);
switch (position) {
case 0:
v = items[0];
break;
case 1:
v = items[1];
break;
case 2:
v = items[2];
break;
case 3:
v = items[3];
break;
case 4:
v = items[4];
break;
case 5:
v = items[5];
break;
}
intent.putExtra("To",v);
startActivity(intent);
}
});
ListFrom Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_from);
listView=(ListView) findViewById(R.id.listviewFrom);
editText=(EditText) findViewById(R.id.etsearchFrom);
initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v="";
Intent intent=new Intent(ListFrom.this,SearchRide.class);
switch (position) {
case 0:
v = items[0];
break;
case 1:
v = items[1];
break;
case 2:
v = items[2];
break;
case 3:
v = items[3];
break;
case 4:
v = items[4];
break;
case 5:
v = items[5];
break;
}
intent.putExtra("From",v);
startActivity(intent);
}
});
SearchRide as Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_ride);
etDate=(EditText) findViewById(R.id.etDate);
TextView tFrom=(TextView) findViewById(R.id.tFrom);
TextView tTo=(TextView) findViewById(R.id.tTo);
etFrom=(EditText) findViewById(R.id.etFrom);
etTo=(EditText) findViewById(R.id.etTo);
Button bSearch=(Button) findViewById(R.id.bSearch);
ImageView iplussign=(ImageView) findViewById(R.id.iplussign);
ImageView iminussign=(ImageView) findViewById(R.id.iminussign);
final TextView tNumber=(TextView) findViewById(R.id.tNumber);
etTo.setText(getIntent().getStringExtra("To"));
tNumber.setText(String.valueOf(p));
iplussign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(p<=9) {
p++;
tNumber.setText(String.valueOf(p));
}
}
});
iminussign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(p>=2) {
p--;
tNumber.setText(String.valueOf(p));
}
}
});
etFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ListFrom=new Intent(SearchRide.this,ListFrom.class);
startActivity(ListFrom);
}
});
etFrom.setText(getIntent().getStringExtra("From"));
etTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ToList =new Intent(SearchRide.this,ListTo.class);
startActivity(ToList);
}
});
etTo.setText(getIntent().getStringExtra("To"));
etDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog= new DatePickerDialog(SearchRide.this,R.style.MyDatePickerStyle,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR));
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
use startActivityForResult() to start ListFrom and ListTo Activities and the receive the result from these activities in OnActivityResult() method.
SearchRide as Main Activity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_ride);
etDate=(EditText) findViewById(R.id.etDate);
TextView tFrom=(TextView) findViewById(R.id.tFrom);
TextView tTo=(TextView) findViewById(R.id.tTo);
etFrom=(EditText) findViewById(R.id.etFrom);
etTo=(EditText) findViewById(R.id.etTo);
Button bSearch=(Button) findViewById(R.id.bSearch);
ImageView iplussign=(ImageView) findViewById(R.id.iplussign);
ImageView iminussign=(ImageView) findViewById(R.id.iminussign);
final TextView tNumber=(TextView) findViewById(R.id.tNumber);
tNumber.setText(String.valueOf(p));
iplussign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(p<=9) {
p++;
tNumber.setText(String.valueOf(p));
}
}
});
iminussign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(p>=2) {
p--;
tNumber.setText(String.valueOf(p));
}
}
});
etFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ListFrom = new Intent(SearchRide.this,ListFrom.class);
startActivityForResult(ListFrom,0);
}
});
etTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ToList = new Intent(SearchRide.this,ListTo.class);
startActivityForResult(ToList,1);
}
});
etDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog= new DatePickerDialog(SearchRide.this,R.style.MyDatePickerStyle,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR));
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if(resultCode == Activity.RESULT_OK){
etFrom.setText(data.getStringExtra("From"));
}
} else if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
etTo.setText(data.getStringExtra("To"));
}
}}
ListFrom code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_from);
listView=(ListView) findViewById(R.id.listviewFrom);
editText=(EditText) findViewById(R.id.etsearchFrom);
initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v="";
switch (position) {
case 0:
v = items[0];
break;
case 1:
v = items[1];
break;
case 2:
v = items[2];
break;
case 3:
v = items[3];
break;
case 4:
v = items[4];
break;
case 5:
v = items[5];
break;
}
Intent intent = new Intent();
intent.putExtra("From",v);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
ListTo code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_to);
etSearchTo=(EditText) findViewById(R.id.etSearchTo);
listViewTo=(ListView) findViewById(R.id.listViewTo);
initList();
listViewTo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v="";
switch (position) {
case 0:
v = items[0];
break;
case 1:
v = items[1];
break;
case 2:
v = items[2];
break;
case 3:
v = items[3];
break;
case 4:
v = items[4];
break;
case 5:
v = items[5];
break;
}
Intent intent = new Intent();
intent.putExtra("To",v);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
Here is what you can do. Put both from and to values as extra when starting an activity and return them both as result. This way you will be able to remember it. I am assuming you just do not want to use static variables.
// in ListTo activity
intent.putExtra("To",v);
intent.putExtra("From", getIntent().getStringExtra("From"));
// in ListFrom activity
intent.putExtra("From",v);
intent.putExtra("To", getIntent().getStringExtra("To"));
// in Main activity
etTo.setText(getIntent().getStringExtra("To"));
etFrom.setText(getIntent().getStringExtra("From"));
// when starting ListFrom activity
Intent ListFrom=new Intent(SearchRide.this,ListFrom.class);
intent.putExtra("From", getIntent().getStringExtra("From"));
intent.putExtra("To", getIntent().getStringExtra("To"));
startActivity(ListFrom);
// when starting ListTo activity
Intent ToList =new Intent(SearchRide.this,ListTo.class);
intent.putExtra("From", getIntent().getStringExtra("From"));
intent.putExtra("To", getIntent().getStringExtra("To"));
startActivity(ToList);
PS: I have not tested the above code. You can experience null pointer errors, but it should give you the general idea.
I am developing an app which have a single activity and several fragments.
The first fragment contains a viewpager which have 3-4 fragments extra. I can switch from one fragment to another easily and the viewpager works fine, but when i am going back from one fragment to the first(not in viewpager), the viewpager is not loading all fragments. Below is the code:
mainactivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private String[] mOptionMenu;
private DrawerLayout mDrawerLayout;
private DrawerLayout loginlayout;
private RelativeLayout mDrawerRelativeLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitleSection;
private CharSequence mTitleApp;
private Fragment mFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1= (Button) findViewById(R.id.button1);
Button btn2= (Button) findViewById(R.id.button2);
Button login= (Button) findViewById(R.id.login);
Button about= (Button) findViewById(R.id.about);
about.setOnClickListener(this);
login.setOnClickListener(this);
btn2.setOnClickListener(this);
btn1.setOnClickListener(this);
FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets(), "fonts/font.ttf");
fontChanger.replaceFonts((ViewGroup)this.findViewById(android.R.id.content));
if (findViewById(R.id.content_frame) != null) {
if (savedInstanceState != null) {
return;
}
FirstFragment firstFragment = new FirstFragment();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().addToBackStack(null)
.add(R.id.content_frame, firstFragment).commit();
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setCustomView(R.layout.actionbar_image);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#662e91")));
mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
FirstFragment firstFragment = new FirstFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
case R.id.login:
callLoginDialog();
break;
case R.id.about:
about abt = new about();
abt.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame, abt).commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
}
}
public class FontChangeCrawler
{
private Typeface typeface;
public FontChangeCrawler(Typeface typeface)
{
this.typeface = typeface;
}
public FontChangeCrawler(AssetManager assets, String assetsFontFileName)
{
typeface = Typeface.createFromAsset(assets, "fonts/font.ttf");
}
public void replaceFonts(ViewGroup viewTree)
{
View child;
for(int i = 0; i < viewTree.getChildCount(); ++i)
{
child = viewTree.getChildAt(i);
if(child instanceof ViewGroup)
{
// recursive call
replaceFonts((ViewGroup)child);
}
else if(child instanceof TextView)
{
// base case
((TextView) child).setTypeface(typeface);
}
}
}
}
public void callLoginDialog()
{
Dialog myDialog = new Dialog(this);
myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myDialog.setContentView(R.layout.loginwindow);
myDialog.setCancelable(false);
TextView reg= (TextView) myDialog.findViewById(R.id.register);
Button login = (Button) myDialog.findViewById(R.id.login);
EditText emailaddr = (EditText) myDialog.findViewById(R.id.editText2);
EditText password = (EditText) myDialog.findViewById(R.id.editText3);
myDialog.show();
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Register",
Toast.LENGTH_LONG).show();
}
});
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//your login calculation goes here
}
});
myDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.cancel();
return true;
}
return false;
}
});
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.user:
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
firstfragment.java
public class FirstFragment extends Fragment {
public ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first,
container, false);
viewPager = (ViewPager) rootView.findViewById(pager);
viewPager.setAdapter(new ViewPagerAdapter(getFragmentManager()));
viewPager.setCurrentItem(0);
PagerTitleStrip pagerTitleStrip= (PagerTitleStrip) rootView.findViewById(R.id.titlestrip);
pagerTitleStrip.setNonPrimaryAlpha(Float.parseFloat("0.3"));
viewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
#Override
public void transformPage(View view, float position) {
final float normalizedposition = Math.abs(Math.abs(position) - 1);
view.setAlpha(normalizedposition);
}
});
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf");
for (int counter = 0 ; counter<pagerTitleStrip.getChildCount(); counter++) {
if (pagerTitleStrip.getChildAt(counter) instanceof TextView) {
((TextView)pagerTitleStrip.getChildAt(counter)).setTypeface(font);
}
}
return rootView;
}
}
viewpageadapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
// Tab Titles
private String tabtitles[] = new String[] { "Home", "Men", "Women", "Children" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
SecondFragment fragmenttab1 = new SecondFragment();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
ThirdFragment fragmenttab2 = new ThirdFragment();
return fragmenttab2;
case 2:
Fourthfragment fragmenttab3 = new Fourthfragment();
return fragmenttab3;
case 3:
FifthFragment fragmenttab4 = new FifthFragment();
return fragmenttab4;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
Try changing viewPager.setAdapter(new ViewPagerAdapter(getFragmentManager())); with viewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));