I came here with another problem, this time it concerns Android app.
I've made an app with Login activity (no NavigationView) which move us after login to Home activity where is NavigationView. User data is saved in SharedPreferences, I'm using Constants class.
My problem is that I can't setText on Home activity using SharedPreferences, but it working on Login activity (email address is inserted in EditText).
Here is my code:
Login.java
package com.example.appname;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.appname.models.ServerRequest;
import com.example.appname.models.ServerResponse;
import com.example.appname.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Login extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
private AppCompatButton btn_login;
private EditText et_email,et_password;
private TextView tv_register;
private ProgressBar progress;
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
pref = getPreferences(0);
btn_login = (AppCompatButton)findViewById(R.id.btn_login);
tv_register = (TextView)findViewById(R.id.tv_register);
et_email = (EditText)findViewById(R.id.et_email);
et_email.setText(pref.getString(Constants.EMAIL, ""));
et_password = (EditText)findViewById(R.id.et_password);
progress = (ProgressBar)findViewById(R.id.progress);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = et_email.getText().toString();
String password = et_password.getText().toString();
if(!email.isEmpty() && !password.isEmpty()) {
progress.setVisibility(View.VISIBLE);
loginProcess(email,password);
} else {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, R.string.empty_fields, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.GREEN);
snackbar.show();
}
}
});
tv_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Register.class);
startActivity(intent);
finish();
}
});
}
private void loginProcess(String email,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(coordinatorLayout, resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.NAME,resp.getUser().getName());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
editor.putString(Constants.POINTS,resp.getUser().getPoints());
editor.apply();
goToHome();
}
progress.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(coordinatorLayout, t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
private void goToHome(){
Intent intent = new Intent(getApplicationContext(), Home.class);
startActivity(intent);
}
}
Home.java
package com.examle.appname;
import android.app.ActivityOptions;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.internal.NavigationMenuPresenter;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
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.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class Home extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private SharedPreferences pref;
private TextView tvname, tvpoints;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
pref = getPreferences(0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tvname = (TextView)findViewById(R.id.tv_name);
tvpoints = (TextView)findViewById(R.id.tv_points);
tvname.setText(pref.getString(Constants.NAME, ""));
tvpoints.setText(pref.getString(Constants.POINTS, "") +R.string.act_points);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nvView);
navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
View headerView = navigationView.getHeaderView(0);
TextView tvemail = (TextView) headerView.findViewById(R.id.tv_email);
tvemail.setText(pref.getString(Constants.EMAIL, ""));
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
public boolean onNavigationItemSelected(MenuItem item) {
int id=item.getItemId();
switch (id){
case R.id.navigation_home:
Intent h= new Intent(Home.this,Home.class);
startActivity(h);
break;
case R.id.navigation_showall:
Intent i= new Intent(Home.this,ShowAllUsers.class);
startActivity(i);
break;
case R.id.navigation_about:
Intent g= new Intent(Home.this,About.class);
startActivity(g);
break;
case R.id.navigation_settings:
Intent s= new Intent(Home.this,AccountSettings.class);
startActivity(s);
case R.id.navigation_support:
Intent t= new Intent(Home.this,Support.class);
startActivity(t);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Try this way
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Constants.NAME))
{
tvname.setText(sharedpreferences.getString(Constants.NAME, ""));
}
Use getSharedPreferences instead of this getPreferences
Because you are using two different instance of the SharedPreference in different activity use single instance. for more info check - https://stackoverflow.com/a/11567825/3912847
Related
i am trying to retrieve the font size from the sharedpreferences from other activity. i already add the getPreferences method however it doesnt work. please explain to me i love knowledges.
as on the code, i succesfully changing the textsize using seekbar, and save it to sharedpreferences, however, in trying to retrieve the font size on other activity, it doesnt work.
here is my 1st activity java
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.android.material.navigation.NavigationView;
public class fontsize extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
//textsize
int textSize = 30;
//textView
TextView textViewFont, textViewSize;
//SharedPreferences
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
//variablesmenudrawer
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fontsize);
sharedPreferences = getSharedPreferences("fontsize", MODE_PRIVATE);
editor = sharedPreferences.edit();
int progress = sharedPreferences.getInt("progress", 0);
//definingtextview
textViewFont = findViewById(R.id.textViewFont);
textViewSize = findViewById(R.id.textViewSize);
//seekbar
SeekBar seekBar = findViewById(R.id.seekbar);
seekBar.setProgress(progress);
textViewFont.setTextSize(textSize+seekBar.getProgress()); // size 30sp
textViewSize.setText(seekBar.getProgress() + "/" + seekBar.getMax()); // 0/30
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNew = 0;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textSize = textSize + (progress - progressNew);
progressNew = progress;
textViewFont.setTextSize(textSize);
editor.putInt("progress", progress);
editor.apply();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
textViewSize.setText(seekBar.getProgress() + "/" + seekBar.getMax()); // 0/30
}
});
//definingmenudrawer
drawerLayout = findViewById(R.id.drawer_layout4);
navigationView = findViewById(R.id.nav_view4);
toolbar = findViewById(R.id.toolbar4);
//toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//toolbar.setNavigationIcon(R.drawable.ic_toolbar);
toolbar.setTitle("");
toolbar.setSubtitle("");
//toolbar.setLogo(R.drawable.ic_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_baseline_dehaze_24);
//navdrawermenu
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
Intent intent = new Intent(fontsize.this, home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
case R.id.nav_fontsize:
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
and my second activity java
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.google.android.material.navigation.NavigationView;
public class duatawassul extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
TextView textView;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
//variablesmenudrawer
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duatawassul);
sharedPreferences = getSharedPreferences("fontsize", MODE_PRIVATE);
textView = findViewById(R.id.duatawassultext);
//definingmenudrawer
drawerLayout = findViewById(R.id.drawer_layout1);
navigationView = findViewById(R.id.nav_view1);
toolbar = findViewById(R.id.toolbar1);
//toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//toolbar.setNavigationIcon(R.drawable.ic_toolbar);
toolbar.setTitle("");
toolbar.setSubtitle("");
//toolbar.setLogo(R.drawable.ic_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_baseline_dehaze_24);
//navdrawermenu
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
Intent intent = new Intent(duatawassul.this, home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
case R.id.nav_fontsize:
Intent intent1 = new Intent(duatawassul.this, fontsize.class);
startActivity(intent1);
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
in your on create method in the second activity add the following which appears to be missing in your original code
prefs = getSharedPreferences("fontsize", MODE_PRIVATE);
//this line is nowhere found in your second activity
int progress=prefs.getInt("progress",0);
if you want to use the share preferences in your app then you have to add value into the shared preference first like below keep in mind you can put it as a string and as an int, it's up to you that what you are using.
SharedPreferences.Editor editor = context.getSharedPreferences("fontsize", MODE_PRIVATE).edit();
editor.putInt("fontsizeis", 14);
editor.apply();
After adding the values to the share preferences than you have to get the value. you can get the value from anywhere you wants for getting the value you can use this.
SharedPreferences sharePreferences= getSharedPreferences("fontsize", MODE_PRIVATE);
if(sharePreferences.contains("fontsizeis")){
int fontsizeis= sharePreferences.getInt("fontsizeis", 0);
if(fontsizeis != 0){
Toast.makeText(context, "you find your desired value here", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "desired value not found some thing issue", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(context, "Share preferences does not contain this key value pair", Toast.LENGTH_SHORT).show();
}
These conditions are use yo avoid the null point execption
I have an Activity A which implements NavigationView.OnNavigationItemSelectedListener that connects it to fragments 1, 2, 3. Fragment 1 has a viewPager and a pagerAdapter which connects it to fragment 4, 5, 6.
I run this and I get an error when Activity A runs fragment 1, it says "No view found for id...for fragment...". I looked it up, but cant figure it out. Can someone tell me how to solve this? Thanks
Fragment 1 is TimeFragment
Activity A is AdminAddNewMerchantActivity
pagerAdapter is DetailsPageAdapter
Below I have the code:
TimeFragment.java
package com.vision.lateoclocktt.ui.time;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.fragment.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.vision.lateoclocktt.DetailsPageAdapter;
import com.vision.lateoclocktt.R;
import com.vision.lateoclocktt.ui.orders.OrdersAdminViewModel;
/**
* A simple {#link Fragment} subclass.
* Use the {#link TimeFragment} factory method to
* create an instance of this fragment.
*/
public class TimeFragment extends Fragment {
private Uri imageUri, imageUri2;
private static final int GalleryPick = 1, GalleryPickBanner = 2;
private StorageTask uploadTask, uploadTask2;
private OrdersAdminViewModel ordersAdminViewModel;
private RecyclerView orderList;
private DatabaseReference ordersRef;
private String downloadImageUrl, downloadImageUrl2;
private TabLayout tabLayout;
private TabItem tabDetails, tabAddress, tabPrice, tabStart, tabEnd;
private ViewPager viewPager;
DetailsPageAdapter pagerAdapter;
private ImageView inputImage, inputBanner;
private StorageReference storageBannerPictureRef,merchantImageReference;
Button saveMechantAddress;
private String myUrl = "";
private RelativeLayout rLayout;
private String currentFragment, currentNavFragment;
private final String CURRENT_FRAG = "current fragment";
private String NAV_FRAG = "navigation fragment";
SharedPreferences sharedPreferences;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_time, container, false);
tabLayout = root.findViewById(R.id.timeTabLayout);
tabDetails = root.findViewById(R.id.t_merchant_details);
tabAddress = root.findViewById(R.id.t_merchant_address);
tabPrice = root.findViewById(R.id.t_merchant_price);
tabStart = root.findViewById(R.id.t_start_time);
viewPager = root.findViewById(R.id.time_viewPager);
pagerAdapter = new DetailsPageAdapter(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
//viewPager.onRestoreInstanceState(new );
storageBannerPictureRef = FirebaseStorage.getInstance().getReference().child("Merchant Banner Images");
merchantImageReference = FirebaseStorage.getInstance().getReference().child("Mechant Images");
currentNavFragment = "Details";
sharedPreferences = getActivity().getSharedPreferences("root_preferences", Context.MODE_PRIVATE);
//SharedPreferences sharedPreferences = getSharedPreferences("root_preferences", MODE_PRIVATE);
currentFragment = sharedPreferences.getString(CURRENT_FRAG, "time");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(NAV_FRAG, currentNavFragment);
editor.commit();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("tab", tab.getPosition());
editor.commit();
viewPager.setCurrentItem(tab.getPosition());
if(tab.getPosition() == 0) {
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 1)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 2)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 3)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 4)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 5)
{
pagerAdapter.notifyDataSetChanged();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//tabLayout.setTabTextColors(Color.parseColor("#000000"), Color.parseColor("#ffffff"));
return root;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(currentFragment.equals("Find Food Admin"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Maps Merchant"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Price"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Start"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Options"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Brief"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
}
private void openGallery(int galleryNumber) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("`image/*");
//startActivityForResult(Intent.createChooser(galleryIntent, "Select Picture"), galleryNumber);
startActivityForResult(galleryIntent, galleryNumber);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
}
}
AdminAddNewMerchantActivity.java
package com.vision.lateoclocktt.Admin;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
//import android.support.v7.widget.Toolbar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.vision.lateoclocktt.Buyers.MainActivity;
import com.vision.lateoclocktt.Prevalent.Prevalent;
import com.vision.lateoclocktt.R;
import com.vision.lateoclocktt.Sellers.SettingsMerchantActivity;
import com.vision.lateoclocktt.ui.cart.CartFragment;
import com.vision.lateoclocktt.ui.favorites.FavoritesFragment;
import com.vision.lateoclocktt.ui.findFood.FindFoodFragment;
import com.vision.lateoclocktt.ui.map.MapsUserFragment;
import com.vision.lateoclocktt.ui.orders.OrdersAdminFragment;
import com.vision.lateoclocktt.ui.receipts.ReceiptsFragment;
import com.vision.lateoclocktt.ui.time.TimeFragment;
import com.vision.lateoclocktt.ui.userview.UserViewFragment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import io.paperdb.Paper;
public class AdminAddNewMerchantActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
NavigationView navigationView;
private String currentActivity;
private final String CURRENT_ACT = "current activity";
private String NAV_FRAG = "navigation fragment";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_add_new_merchant);
currentActivity = "adminaddnewmerchant";
sharedPreferences = getSharedPreferences("root_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CURRENT_ACT, currentActivity);
editor.commit();
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_admin);
setSupportActionBar(toolbar);
toolbar.setTitle("Home");
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_baseline_menu_24));
drawer = findViewById(R.id.container_admin);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view_admin);
BottomNavigationView navView = findViewById(R.id.bot_nav_view_admin);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_merchant_details_admin, R.id.navigation_user_view, R.id.navigation_orders_admin)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_admin_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
View headerView = navigationView.getHeaderView(0);
TextView name = (TextView)headerView.findViewById(R.id.username);
TextView email = headerView.findViewById(R.id.email);
name.setText(sharedPreferences.getString("name", ""));
email.setText(sharedPreferences.getString("email", ""));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.navigation_settings:
Intent settingsIntent = new Intent(AdminAddNewMerchantActivity.this, SettingsMerchantActivity.class);
startActivity(settingsIntent);
break;
case R.id.navigation_logout:
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
Intent logoutIntent = new Intent(AdminAddNewMerchantActivity.this, MainActivity.class);
Paper.book().write(Prevalent.RememberMeMerchant, "false");
Paper.book().write(Prevalent.emailKey, "UserEmail");
Paper.book().write(Prevalent.passwordKey, "UserPassword");
logoutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(logoutIntent);
finish();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
if(!sharedPreferences.getString(NAV_FRAG, "").equals("")){
if(sharedPreferences.getString(NAV_FRAG, "").equals("Details"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new TimeFragment()).commit();
navView.setSelectedItemId(R.id.navigation_merchant_details_admin);
}
else if(sharedPreferences.getString(NAV_FRAG, "").equals("Userview"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new UserViewFragment()).commit();
navView.setSelectedItemId(R.id.navigation_user_view);
}
else if(sharedPreferences.getString(NAV_FRAG, "").equals("Orders"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new OrdersAdminFragment()).commit();
navView.setSelectedItemId(R.id.navigation_orders_admin);
}
}
}
#Override
public void onBackPressed()
{
if(drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_merchant_details_admin:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new TimeFragment()).commit();
break;
case R.id.navigation_user_view:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new UserViewFragment()).commit();
break;
case R.id.navigation_orders_admin:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new OrdersAdminFragment()).commit();
break;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
}
DetailsPageAdapter.java
package com.vision.lateoclocktt;
import com.vision.lateoclocktt.ui.brief.BriefFragment;
import com.vision.lateoclocktt.ui.findFood.FindFoodAdminFragment;
import com.vision.lateoclocktt.ui.map.MapsMerchantFragment;
import com.vision.lateoclocktt.ui.options.OptionsFragment;
import com.vision.lateoclocktt.ui.price.PriceFragment;
import com.vision.lateoclocktt.ui.time.StartFragment;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class DetailsPageAdapter extends FragmentPagerAdapter {
private int numberOfTabs;
public FragmentManager mfm;
public DetailsPageAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
this.mfm = fm;
this.numberOfTabs = behavior;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FindFoodAdminFragment();
case 1:
return new MapsMerchantFragment();
case 2:
return new PriceFragment();
case 3:
return new StartFragment();
case 4:
return new OptionsFragment();
case 5:
return new BriefFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numberOfTabs;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}
Errors:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vision.lateoclocktt, PID: 4500
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vision.lateoclocktt/com.vision.lateoclocktt.Admin.AdminAddNewMerchantActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0a01a2 (com.vision.lateoclocktt:id/nav_host_fragment) for fragment TimeFragment{fa4480} (b1d4c74f-3fd0-4e61-9d0b-89212a0bd27a) id=0x7f0a01a2}
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0a01a2 (com.vision.lateoclocktt:id/nav_host_fragment) for fragment TimeFragment{fa4480} (b1d4c74f-3fd0-4e61-9d0b-89212a0bd27a) id=0x7f0a01a2}
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:315)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2629)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6696)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I figured it out after getting some sleep. In AdminAddNewMerchantActivity.java I changed R.id.nav_host_fragment to R.id.nav_host_admin_fragment and it worked! The view nav_host_fragment really did not exist. I copied it from another file, expected it to work and didn't read the error message properly.
For my academic project, I want create an application with 4 tabs. The first one will show recent games added to a list, the second one will be a search form, the third will show the search result, and the last one will show the details. I currently have created the code for TabView and the 4 tabs. The problem is that I want to perform a search to get the items I have in a list which meet the search criteria on fragment 2, but I don't know how to pass the data from fragment 2 (textView data and spinner) to fragment 3. My code is the following:
MainActivity.java:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
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.view.Menu;
import android.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_search_white_24dp);
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();
}
});
//TabLayout function call
configureTabLayout();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
return true;
case R.id.menu_settings:
Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Tab Layout function declaration
private void configureTabLayout() {
//Getting the tab layout
TabLayout tabLayout = findViewById(R.id.tab_layout);
//Adding Tabs
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));
//The TabPagerAdapter instance is then
//assigned as the adapter for the ViewPager and the TabLayout component added
//to the page change listener
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Finally, the onTabSelectedListener is configured on the TabLayout instance and
//the onTabSelected() method implemented to set the current page on the
//ViewPager based on the currently selected tab number.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
TabPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeScreenFragment();
case 1:
return new SearchFormFragment();
case 2:
return new SearchResultsFragment();
case 3:
return new DetailsScreenFragment();
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
SearchFormFragment.java
package gr.pliroforiki_edu.videogamedb;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchFormFragment extends Fragment {
private Button searchButton;
private EditText gameTitleEditText;
Spinner spinnerGenre;
public SearchFormFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);
searchButton = searchFormView.findViewById(R.id.searchButton);
gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);
spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
getActivity(),
R.array.game_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterGameTitle = gameTitleEditText.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);
Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();
}
});
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_search_form, container, false);
return searchFormView;
}
}
SearchResultsFragment.java
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.ListView;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);
return searchResultsView;
}
private void findViews()
{
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
I want to archive the following via the fragments:
ListActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ListActivity extends AppCompatActivity {
private TextView textViewInfo;
private ListView listViewBooks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// Animation when this Activity appears
overridePendingTransition(R.anim.pull_in_from_right, R.anim.hold);
// Get user filters from Intent
Intent intent = getIntent();
String filterAuthor = intent.getStringExtra("AUTHOR");
String filterTitle = intent.getStringExtra("TITLE");
int filterGenreId = intent.getIntExtra("GENREID", 0);
findViews();
// Show user filters for information
String message = String.format("Author: %s\nTitle: %s\nGenreId: %d",
filterAuthor, filterTitle, filterGenreId);
textViewInfo.setText(message);
DataStore.LoadBooks(filterAuthor, filterTitle, filterGenreId);
//Complex Object Binding
ListAdapter booksAdapter = new SimpleAdapter(
this,
DataStore.Books,
R.layout.list_item,
new String[]{DataStore.KEY_TITLE, DataStore.KEY_AUTHOR, DataStore.KEY_GENRENAME},
new int[]{R.id.book_item_title, R.id.book_item_author, R.id.book_item_genre}
);
listViewBooks.setAdapter(booksAdapter);
listViewBooks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent detailsIntent = new Intent(ListActivity.this, DetailsActivity.class);
detailsIntent.putExtra(DataStore.KEY_POSITION, position);
startActivity(detailsIntent);
}
});
}
#Override
protected void onPause(){
overridePendingTransition(R.anim.hold, R.anim.push_out_to_right);
super.onPause();
}
private void findViews(){
textViewInfo = findViewById(R.id.textViewInfo);
listViewBooks = findViewById(R.id.listViewBooks);
}
}
Mainactivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText textAuthor;
private EditText textTitle;
private EditText textGenre;
private Button buttonSearch;
private Spinner spinnerGenre;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataStore.Init(getApplicationContext());
textAuthor = findViewById(R.id.editTextAuthor);
textTitle= findViewById(R.id.editTextAuthor);
buttonSearch = findViewById(R.id.buttonSearch);
spinnerGenre = (Spinner) findViewById(R.id.spinnerGenre);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
this,
R.array.book_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterAuthor = textAuthor.getText().toString();
String filterTitle = textTitle.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("AUTHOR", filterAuthor);
intent.putExtra("TITLE", filterTitle);
intent.putExtra("GENREID", filterGenreId);
startActivity(intent);
}
});
}
}
Try this
pass value between two fragment using bundle
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeScreenFragment();
case 1:
return new SearchFormFragment();
case 2:
Fragment fragment = new SearchResultsFragment()
Bundle args = new Bundle();
args.putString("Key", "Value");
fragment.setArguments(args);
return fragment;
case 3:
return new DetailsScreenFragment();
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
in your onCreateView(....) of SearchResultsFragment
String value = getArguments().getString("Key");
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView =
inflater.inflate(R.layout.fragment_search_results, container, false);
String value = getArguments().getString("Key");
return searchResultsView;
}
private void findViews(){
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
hop its help you
There are many ways you can pass objects/values between fragments. In your case, the simplest solution would be to delegate those values to the holding Activity i.e MainActivity.
MainActivity:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
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.view.Menu;
import android.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//these will hold your values
String filterGameTitle;
int filterGenreId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_search_white_24dp);
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();
}
});
//TabLayout function call
configureTabLayout();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
return true;
case R.id.menu_settings:
Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Tab Layout function declaration
private void configureTabLayout() {
//Getting the tab layout
TabLayout tabLayout = findViewById(R.id.tab_layout);
//Adding Tabs
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));
//The TabPagerAdapter instance is then
//assigned as the adapter for the ViewPager and the TabLayout component added
//to the page change listener
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Finally, the onTabSelectedListener is configured on the TabLayout instance and
//the onTabSelected() method implemented to set the current page on the
//ViewPager based on the currently selected tab number.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
SearchFormFragment:
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchFormFragment extends Fragment {
private Button searchButton;
private EditText gameTitleEditText;
Spinner spinnerGenre;
public SearchFormFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);
searchButton = searchFormView.findViewById(R.id.searchButton);
gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);
spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
getActivity(),
R.array.game_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterGameTitle = gameTitleEditText.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
((MainActivity)getActivity()).filterGameTitle = filterGameTitle;
((MainActivity)getActivity()).filterGenreId = filterGenreId;
String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);
Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();
}
});
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_search_form, container, false);
return searchFormView;
}
}
SearchResultFragment:
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.ListView;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
String filterGameTitle;
int filterGenreId;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context)
{
filterGameTitle = ((MainActivity)getActivity()).filterGameTitle;
filterGenreId = ((MainActivity)getActivity()).filterGenreId;
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);
return searchResultsView;
}
private void findViews()
{
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
You can use interface to send your search string to your activity from fragment 2, and from their you can call all methods in your fragment 3 as fragment3 object will be available to you in your activity, you can make performSearch() in your fragment3 and call it from your activity.
Alternatively you can use something like event bus to avoid the boiler plate code needed to setup interface.
Have a look at this event bus repo https://github.com/greenrobot/EventBus
Register event bus where you want the search string, in your case register the event bus in Fragment3 like this
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
In your Fragment 3 create a function like this
#Subscribe
public void onSearchEvent(String searchString){
//you will get your search string here
}
Now comeback to fragment2 from where you want to send the searchString, you have to put below code from where you want to send searchString, and this posted searchString will be received by fragment 3 in its onSearchEvent method
EventBus.getDefault().post(searchString);
can I Serialize a text from my database to a text view? I'm trying to do it but it still don't get the userID from my database and It just prints Large Text as is what i dragged inside my app. Is it possible? Here is my code Thanks.
ownerhome.class
package com.example.kun.carkila;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
public class ownerhome extends AppCompatActivity {
final String TAG = this.getClass().getName();
int from_Where_I_Am_Coming = 0;
SharedPreferences pref;
SharedPreferences.Editor editor;
ListView lvPosts;
TextView userID1;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ownerhome);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
User User = (User)getIntent().getSerializableExtra("user");
userID1 = (TextView) findViewById(R.id.tvUserID);
pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
Log.d(TAG, pref.getString("username", ""));
Log.d(TAG, pref.getString("password", ""));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(ownerhome.this, InsertActivity.class);
startActivity(in);
}
});
try {
if (User != null) {
userID1.setText(User.userID);
}
}catch (Exception e){
System.out.println("Error in details " + e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater findMenuItems = getMenuInflater();
findMenuItems.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_logout){
editor = pref.edit();
editor.clear();
editor.commit();
Intent in = new Intent(ownerhome.this, MainActivity.class);
startActivity(in);
finish();
}
return super.onOptionsItemSelected(item);
}
}
User.class
package com.example.kun.carkila;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("userID")
public int userID;
}
Thanks guys for the help :)
So I am creating an app that I want the user to be able to decide if they want to use WiFi or 4G to fetch the data after logging in (I will make another question about implementing the decision later, unless anyone wants to add that here too). So currently I have a MainActivity.java that will be handling the logging in (which I have yet to implement) and I have a NavDrawerActivity.java for the Navigation Drawer. Now obviously once I do the "log in" it goes to the Nav Drawer. However, I want the user to be able to choose whether or not to use Wifi or Data before logging in as well as being able to choose once they log in. So I guess this is a two part question, how would you implement this as well as, is it a good idea to put that in the login screen? Or should I just default it to always use wifi unless they change it and if I detect WiFi isn't enabled, have them enable it?
MainActivity.java code
package com.example.jamessingleton.chffrapi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "USE_YOUR_OWN_API_KEY";
static final String API_URL = "https://api.fullcontact.com/v2/person.json?";
static final String ClientId= "";
static final String ClientSecret = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new RetrieveFeedTask().execute();
Intent intent = new Intent(context, NavDrawerActivity.class);
startActivity(intent);
}
});
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}
}
NavDrawerActivity.java code
package com.example.jamessingleton.chffrapi;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
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.view.Menu;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav_drawer, 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();
FragmentManager fragmentSettingsManager = getFragmentManager();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
fragmentSettingsManager.beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit();
setTitle(R.string.action_settings);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.GONE);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
setTitle(R.string.speed_graph);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).commit();
setTitle(R.string.drive_player);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ThirdFragment()).commit();
setTitle(R.string.google_maps);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_share) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Go Check Out All Driving Data in the Play Store!");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Let me know if there is anything else you guys need and thank you guys for all the help :)
Here is the WifivsDataDialog code
package com.example.jamessingleton.chffrapi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
/**
* Created by James Singleton on 8/9/2016.
*/
public class WifivsDataDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_box)
.setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
It's not entirely clear what you would like to achieve.
Is it mandatory to fetch the data? What if the user has both Wi-Fi and mobile network disabled on the device? What if they choose to use Wi-Fi, but have only mobile network enabled on the device?
I would create a Dialog at the start of the app that explains this stuff and let the user choose if they would like to allow fetching data on mobile network, or Wi-Fi only, with a "Do not show this dialog again" CheckBox.
If the user chooses with the CheckBox checked, then that will be the default behaviour on further launches (and can be changed in the Preferences/Settings).
You could show the Dialog from the onCreate() of your login Activity.
For example:
connection_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Would you like to allow fetching data on mobile network?"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No, allow Wi-Fi only"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:text="OK"/>
</LinearLayout>
ConnectionDialogFragment.java:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ConnectionDialogFragment extends DialogFragment {
public ConnectionDialogFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.connection_dialog, container, false);
// set up your View here
return view;
}
}
And in your Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// ...
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("show_dialog", true)) {
showDialog();
}
}
private void showDialog() {
ConnectionDialogFragment dialog = new ConnectionDialogFragment();
dialog.show(getSupportFragmentManager(), "connection_dialog");
}
Check out the developer's guide on Dialogs.
When the user has chosen whether they want to use Wi-Fi only, or allow mobile network also, you could check the available connection with something like this:
// this method will return either
// ConnectivityManager.TYPE_MOBILE
// or
// ConnectivityManager.TYPE_WIFI
// or -1 (if no connection is available)
private int checkAvailableConnectionType() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
int type = activeNetwork.getType();
if(activeNetwork.isConnected() && (type == ConnectivityManager.TYPE_MOBILE ||
type == ConnectivityManager.TYPE_WIFI)) {
return type;
}
return -1;
}
And do your stuff according to the user's choice and the currently active connection (advise the user to turn on Wi-Fi, for example).