Navigation Items not clicking - java

Nothing happens when I click on the items "Orders" and "Logout" from my navigation drawer:
Here's my code for the navigation drawer:
public class Home extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
FirebaseDatabase database;
DatabaseReference category;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartIntent = new Intent(Home.this, Cart.class);
startActivity(cartIntent);
}
});
final DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
menuItem.setChecked(true);
drawer.closeDrawers();
int id = menuItem.getItemId();
if (id == R.id.nav_menu) {
Toast.makeText(Home.this, "menu Clicked", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_cart) {
Intent cartIntent = new Intent(Home.this, Cart.class);
startActivity(cartIntent);
} else if (id == R.id.nav_orders) {
// Toast.makeText(Home.this, "Order Clicked", Toast.LENGTH_SHORT).show();
Intent orderIntent = new Intent(Home.this, OrderStatus.class);
startActivity(orderIntent);
} else if (id == R.id.nav_logout) {
//Logout
Intent signIn=new Intent(Home.this,SignIn.class);
signIn.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(signIn);
}
return true;
}
});
//set name for user
View headerView = navigationView.getHeaderView(0);
txtFullName = (TextView) headerView.findViewById(R.id.txtFullName);
txtFullName.setText(Common.currentUser.getName());
//load menu
recycler_menu = findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
private void loadMenu() {
FirebaseRecyclerOptions<Category> options = new FirebaseRecyclerOptions.Builder<Category>()
.setQuery(category, Category.class)
.build();
adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_item, parent, false);
return new MenuViewHolder(itemView);
}
#Override
protected void onBindViewHolder(#NonNull MenuViewHolder viewHolder, int position, #NonNull Category model) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem = model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent foodList = new Intent(Home.this, FoodList.class);
foodList.putExtra("CategoryId", adapter.getRef(position).getKey());
startActivity(foodList);
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#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.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
super.onSupportNavigateUp();
}
}
I've tried to add toast in the nav_orders to check when I click orders it toast up but didn't work too, Code I've tried is :
else if (id == R.id.nav_orders) {
Toast.makeText(Home.this, "Order Clicked", Toast.LENGTH_SHORT).show();
}

If you have orders and logouts as items not under groups in drawer_menu you can create onClickListner for them. Don't call them by using if condition. You can directly place them under public boolean onNavigationItemSelected(#NonNull MenuItem item).
This sholud look like:
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
toolbar.setTitle("Ongoing Events");
break;
case R.id.nav_category:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HistoryFragment()).commit();
toolbar.setTitle("History");
break;
case R.id.Orders:
Toast.makeText(MainActivity.this, "Orders", Toast.LENGTH_SHORT).show();
case R.id.nav_logout:
AlertDialog.Builder builder = new AlertDialog.Builder(
(MainActivity.this));
builder.setTitle("Logout?");
builder.setMessage("Are you sure you want to sign out?");
builder.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
builder.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
logout();
restart();
}
});
builder.show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}

Related

Error to retrieve image from firebase for recycler view in fragment

I want to retrieve image for recycler view in fragment
code of MovieActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);
setupViewFragment();
}
setupToolbar();
setupBottomNavigation();
}
private void setupViewFragment() {
// show discover movies fragment by default
DiscoverMoviesFragment discoverMoviesFragment = DiscoverMoviesFragment.newInstance();
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), discoverMoviesFragment, R.id.fragment_container);
}
private void setupBottomNavigation() {
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_home:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), HomeFragment.newInstance(),
R.id.fragment_container);
//startActivity(new Intent(getApplicationContext()
//,HomeActivity.class));
return true;
case R.id.action_discover:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), DiscoverMoviesFragment.newInstance(),
R.id.fragment_container);
return true;
case R.id.action_favorites:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), FavoritesFragment.newInstance(),
R.id.fragment_container);
return true;
}
return false;
}
});
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
`
code for HomeFragment :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);
setupViewFragment();
}
setupToolbar();
setupBottomNavigation();
}
private void setupViewFragment() {
// show discover movies fragment by default
DiscoverMoviesFragment discoverMoviesFragment = DiscoverMoviesFragment.newInstance();
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), discoverMoviesFragment, R.id.fragment_container);
}
private void setupBottomNavigation() {
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_home:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), HomeFragment.newInstance(),
R.id.fragment_container);
//startActivity(new Intent(getApplicationContext()
//,HomeActivity.class));
return true;
case R.id.action_discover:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), DiscoverMoviesFragment.newInstance(),
R.id.fragment_container);
return true;
case R.id.action_favorites:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), FavoritesFragment.newInstance(),
R.id.fragment_container);
return true;
}
return false;
}
});
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
code for HomeAdapter :
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;
public HomeAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.centerInside()
.fit()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
doWhatever.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onWhatEverClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onWhatEverClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
this is the error :
`C:\Users\User\Desktop\PopularMovies\app\src\main\java\com\ajdi\yassin\popularmovies\ui\movieslist\home\HomeFragment.java:65: error: incompatible types: HomeFragment cannot be converted to Context
mAdapter = new HomeAdapter(HomeFragment.this, mUploads);`
Please use getApplicationContext() ,because HomeFragment.this is consider as an Activity and in your HomeAdapter constructor you have passed Context.
Replace:
mAdapter = new HomeAdapter(HomeFragment.this, mUploads);
To:
mAdapter = new HomeAdapter(getApplicationContext(), mUploads);

my intent in navigation drawer is not working

When I tap on any item of in navigation drawer ,instead of going to new activity , the drawer toggles.
MainActivity :
public class MainActivity extends AppCompatActivity {
LinearLayoutManager mLayoutManager; //for sorting
SharedPreferences mSharedPreferences; //for saving sort setting
DrawerLayout drawerLayout;
ActionBarDrawerToggle toggle;
NavigationView navigationView;
Toolbar toolbar;
RecyclerView mRecyclerView;
List<FoodData> myFoodList;
FoodData mFoodData;
MyAdapter myAdapter;
SearchView searchView;
private boolean ascending = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setUpToolbar();
// getSupportActionBar().hide();
toolbar =(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//menu hooks
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.navigation_menu);
toggle = new ActionBarDrawerToggle(this, drawerLayout,toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
searchView = findViewById(R.id.srch);
mSharedPreferences= getSharedPreferences("SortSettings", MODE_PRIVATE);
String mSorting =mSharedPreferences.getString("Sort","newest"); // where if no setting is selected newest will be default
if(mSorting.equals("newest")){
mLayoutManager = new LinearLayoutManager(this);
//this will load the items from bottom means newest first
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
}else if(mSorting.equals("oldest")){
mLayoutManager = new LinearLayoutManager(this);
//this will load the items from bottom means oldest first
mLayoutManager.setReverseLayout(false);
mLayoutManager.setStackFromEnd(false);
}
//for setting company name in the navigation drawer
// navigationView=(NavigationView)findViewById(R.id.navigation_menu);
//navigationView.setNavigationItemSelectedListener(this);
// View header = navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_favourite:
Intent intent = new Intent(MainActivity.this, favourite.class);
startActivity(intent);
// drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_about_us:
Intent intent1 = new Intent(MainActivity.this , About_us.class);
startActivity(intent1);
// drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_rate_us:
Intent intent2 = new Intent(MainActivity.this , RateUs.class);
startActivity(intent2);
// drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_share:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "http://play.google.com/store/apps/detail?id=" + getPackageName();
String shareSub = "Try now";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
//drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_setting:
Intent intent3 = new Intent(MainActivity.this , SettingsActivity.class);
startActivity(intent3);
// drawerLayout.closeDrawer(GravityCompat.START);
break;
}
return true;
}
});
GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this,1);
mRecyclerView.setLayoutManager(mLayoutManager);
myFoodList = new ArrayList<>();
mFoodData = new FoodData("Rawa Kesar",R.drawable.rawa,"INGREDIENTS");
mFoodData = new FoodData("Jalebi",R.drawable.jalebi,"INGREDIENTS");
mFoodData = new FoodData("Rasmalai",R.drawable.rasmlai,"INGREDIENTS");
mFoodData = new FoodData("Kaju Katli",R.drawable.kajuktli,"INGREDIENTS");
myAdapter = new MyAdapter(MainActivity.this,myFoodList);
mRecyclerView.setAdapter(myAdapter);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
myAdapter.getFilter().filter(s.toString());
return false;
}
});
}
// public void btn_uploadActivity(View view) {
//
// startActivity(new Intent(this,Upload_Recipe));
// }
// public void setUpToolbar() {
// drawerLayout = findViewById(R.id.drawerLayout);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
// drawerLayout.addDrawerListener(actionBarDrawerToggle);
// actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.black));
// actionBarDrawerToggle.syncState();
//
// }
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id=item.getItemId();
if(id==R.id.sort){
//display alert dialogue to choose sorting
showSortDialogue();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showSortDialogue() {
//options to display in dialogue
String[] sortOptions = {"Newest","Oldest"};
//create alert dislogue
AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setTitle("Sort By").setIcon(R.drawable.sort_2).setItems(sortOptions,new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
SharedPreferences.Editor editor=mSharedPreferences.edit();
editor.putString("Sort","newest");
editor.apply();
recreate();
}else if(which==1){
SharedPreferences.Editor editor=mSharedPreferences.edit();
editor.putString("Sort","oldest");
editor.apply();
recreate();
}
}
}
);
builder.show();
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu,menu);
// MenuItem menuItem=menu.findItem(R.id.search);
// //SearchView searchView=(SearchView) menuItem.getActionView();
// searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// #Override
// public boolean onQueryTextSubmit(String s) {
// return false;
// }
//
// #Override
// public boolean onQueryTextChange(String s) {
// myAdapter.getFilter().filter(s.toString());
// return false;
// }
// });
// return super.onCreateOptionsMenu(menu);
// }
#Override
public void onBackPressed() {
Intent a =new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
}
this is my mainActiviy.xml code where i have usedNavigation View
I have checked my code many times but not able to find the mistake...it would be great help if someone helps me in this
Thanks in advance.
add navigation view below linear layout, it will work. In drawer layout , content should be first then navigation view.

How to implement the saving of night mode in multiple activities?

I tried using an Inflater to check whether the Switch responsible for activating and deactivating night mode in my Settings activity is enabled or not. The MainActivity doesn't remember the night mode state after relaunching the app.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Switch night_mode_sw;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMMode";
SharedPreferences sharedpreferences;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.getOverflowIcon().setColorFilter(16777215, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(toolbar);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.activity_settings, null);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
night_mode_sw = findViewById(R.id.night_mode);
checkNightModeActivated();
view.findViewById(R.id.night_mode);
night_mode_sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (sharedpreferences.getBoolean(KEY_ISNIGHTMODE,false)) {
night_mode_sw.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
night_mode_sw.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.settings) {
Intent myintent = new Intent(MainActivity.this, Settings.class);
startActivity(myintent);
return false;
}
if (id == R.id.aboutapp) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About this app")
.setCancelable(false)
.setNeutralButton("GOT IT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setTitle("About this app")
.setMessage("awsd");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
}
Settings.java:
public class Settings extends AppCompatActivity {
private Switch night_mode_sw;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(final Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.getOverflowIcon().setColorFilter(16777215, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(toolbar);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
night_mode_sw = findViewById(R.id.night_mode);
checkNightModeActivated();
night_mode_sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (sharedpreferences.getBoolean(KEY_ISNIGHTMODE,false)) {
night_mode_sw.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
night_mode_sw.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu1,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.calculator) {
Intent myintent = new Intent (Settings.this, MainActivity.class);
startActivity(myintent);
return false;
}
if (id == R.id.aboutapp) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About this app")
.setCancelable(false)
.setNeutralButton("GOT IT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setTitle("About this app")
.setMessage("awsd");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
}
I'm not sure what the reason for this is.

I lost my View Pager Data When I Back From next tab

I am having four tab in my View pager I have search in google but I can,t found any solution when Swipe my view pager it work fine like 1-2-3-4 but when I try to swipe reverse 4-3-2-1 than my data get lost or you can say my adapter get lost.My View Pager is inside Activity.My Data is lost when I go to next page and back then back my data is lost.
My Main Activity is:
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
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.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
My Fragment is
public class ImageListFragment extends Fragment {
String category_Name, Category_ID, Product_ID, Product_Name,
Product_Image, Product_Price, Product_Sale, Cart;
public static final String STRING_IMAGE_URI = "ImageUri";
public static final String STRING_IMAGE_POSITION = "ImagePosition";
private static MainActivity mActivity;
ArrayList<SingleItemModel> singleItemModels;
RecyclerView recyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCategoryone();
Fresco.initialize(getContext());
mActivity = (MainActivity) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
recyclerView = (RecyclerView) inflater.inflate(R.layout.layout_recylerview_list, container, false);
return recyclerView;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder> {
// private String[] mValues;
private ArrayList<SingleItemModel> mValues;
private RecyclerView mRecyclerView;
public static class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final SimpleDraweeView mImageView;
public final LinearLayout mLayoutItem;
public final ImageView mImageViewWishlist;
TextView iTemName, itemDescription, itemPrice;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (SimpleDraweeView) view.findViewById(R.id.image1);
mLayoutItem = (LinearLayout) view.findViewById(R.id.layout_item);
mImageViewWishlist = (ImageView) view.findViewById(R.id.ic_wishlist);
iTemName = (TextView) view.findViewById(R.id.itemName);
itemDescription = (TextView) view.findViewById(R.id.itemDescription);
itemPrice = (TextView) view.findViewById(R.id.itemPrice);
}
}
public SimpleStringRecyclerViewAdapter(RecyclerView recyclerView, ArrayList<SingleItemModel> items) {
mValues = items;
mRecyclerView = recyclerView;
}
#Override
public ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder(view);
}
#Override
public void onViewRecycled(ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder) {
if (holder.mImageView.getController() != null) {
holder.mImageView.getController().onDetach();
}
if (holder.mImageView.getTopLevelDrawable() != null) {
holder.mImageView.getTopLevelDrawable().setCallback(null);
//
}
}
#Override
public void onBindViewHolder(final ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder, final int position) {
SingleItemModel singleItemModel = mValues.get(position);
holder.iTemName.setText(singleItemModel.getCategory_Name());
final Uri uri = Uri.parse(singleItemModel.getProduct_Image());
holder.mImageView.setImageURI(uri);
holder.itemPrice.setText(singleItemModel.getProduct_Price());
holder.itemDescription.setText(singleItemModel.getProduct_Sale());
}
#Override
public int getItemCount() {
return mValues.size();
}
}
public void getCategoryone() {
final RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://proaudiobrands.com/app/feature.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("shabina shopping response", response);
try {
singleItemModels = new ArrayList<>();
JSONObject mainObj = new JSONObject(response);
Log.d("shabina ", response);
JSONArray Feature_product = mainObj.getJSONArray("Feature_product");
for (int i = 0; i < Feature_product.length(); i++) {
JSONObject Feature_Product = Feature_product.getJSONObject(i);
String Category_Namee = Feature_Product.getString("Category_Namee");
String Category_IDs = Feature_Product.getString("Category_IDs");
JSONArray Product_List = Feature_Product.getJSONArray("Product_List");
for (int j = 0; j < Product_List.length(); j++) {
JSONObject Category_Name = Product_List.getJSONObject(j);
if (Category_Name.getString("Category_Name").equals("Microphones")) {
category_Name = Category_Name.getString("Category_Name");
Category_ID = Category_Name.getString("Category_ID");
Product_ID = Category_Name.getString("Product_ID");
Product_Name = Category_Name.getString("Product_Name");
Product_Image = Category_Name.getString("Product_Image");
Product_Price = Category_Name.getString("Product_Price");
Product_Sale = Category_Name.getString("Product_Sale");
Cart = Category_Name.getString("Cart");
Log.e("sushil Category_Name", category_Name + " " + Category_ID + " " + Product_ID + " " + Product_Name + " " + Product_Image + " " + Product_Price + " " + Product_Sale + " " + Cart);
SingleItemModel singleItemModel1 = new SingleItemModel(category_Name, Category_ID, Product_ID, Product_Name, Product_Image, Product_Price, Product_Sale, Cart);
singleItemModels.add(singleItemModel1);
}
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new ImageListFragment.SimpleStringRecyclerViewAdapter(recyclerView, singleItemModels));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("method", "feature");
params.put("userId", "PRO1");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
}
Replace your MainActivity with below
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
viewPager.setOffscreenPageLimit(4);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
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.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}

App will not run the first time but when item in menu is clicked it runs

I read data from json file to an adapter and in the main.java under oncreate, when I try runing it,it doest show anything.
I tried the same code under menu onclick and it works, I want it to appear when the app is first runed.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String url = "myjsonurl.php";
JSONArray jArray;
ProgressDialog dialog;
ListView mycustomlist = null;
WebView mywebview =null;
CustomAdapter myadapter = null;
ArrayList<news> mydatalist = new ArrayList<news>();
ArrayList<news> maşetData = new ArrayList<news>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
dialog = new ProgressDialog(this);
dialog.setMessage("Loading....");
dialog.show();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
parseJsonData(string);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
dialog.cancel();
}
});
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
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();
}
});
*/
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);
}
public void parseJsonData(final String jsonString) {
try {
jArray = new JSONArray(jsonString);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
news news1 = new news();
news1.setTitle(jObject.getString("title"));
news1.setContent(Html.fromHtml(jObject.getString("content")));
news1.setDate(jObject.getString("date"));
news1.setImage("http://www.bolgegundem.com/d/news/" + jObject.getString("image").concat(".jpg"));
news1.setId(jObject.getString("id"));
news1.setCategory(jObject.getString("category"));
news1.set__comment_count(jObject.getString("__comment_count"));
news1.setHeadline(jObject.getString("headline"));
mydatalist.add(news1);
// http://www.bolgegundem.com/d/gallery/81_2.jpg
/* images.add("http://www.bolgegundem.com/d/gallery/" + id + "_" + imgUrl.replace(",", ".jpg") );*/
// al.add(title);
//imagelinks[i] = "http://www.bolgegundem.com/d/gallery/" + id + "_" + i + ".jpg";
}
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1, al);
//listview.setAdapter(adapter);
// listview.setBackgroundColor(rgb(0, 255, 255));
/* listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i < links.length){
Uri uri = Uri.parse(links[i]);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
});*/
if (dialog.isShowing()){
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
dialog.dismiss();
}
}
#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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.manşet) {
// Handle the camera action
} else if (id == R.id.Anasayfa) {
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
} else if (id == R.id.ajansTv) {
} else if (id == R.id.foto) {
} else if (id == R.id.gundem) {
} else if (id == R.id.siyaset) {
}else if (id ==R.id.Ekonomi ){
}else if (id ==R.id.spor ){
}else if (id ==R.id.saglik ){
}else if (id ==R.id.nav_share ){
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My adapter class is here
public class CustomAdapter extends BaseAdapter {
Context mycontext = null;
ArrayList<news> mydatalist;
public CustomAdapter(Context mycontext, ArrayList<news> mydatalist)
{
this.mycontext = mycontext;
this.mydatalist = mydatalist;
}
#Override
public int getCount() {
return this.mydatalist.size();
}
#Override
public Object getItem(int position) {
return this.mydatalist.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myinflater = (LayoutInflater)mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder myholder = null;
if(convertView == null)
{
convertView = myinflater.inflate(R.layout.customlayout, null);
myholder = new ViewHolder();
myholder.mytextview1 = (TextView)convertView.findViewById(R.id.mytextview1);
myholder.mytextview2 = (TextView)convertView.findViewById(R.id.mytextview2);
myholder.mytextview3 = (TextView)convertView.findViewById(R.id.mytextview3);
myholder.myimageview1 = (ImageView)convertView.findViewById(R.id.imageView);
convertView.setTag(myholder);
}
else
{
myholder = (ViewHolder)convertView.getTag();
}
myholder.mytextview1.setText(mydatalist.get(position).getTitle());
myholder.mytextview2.setText(mydatalist.get(position).getContent());
myholder.mytextview3.setText(mydatalist.get(position).getDate());
myholder.myimageview1.setImageResource(R.drawable.bolgegundem);
new DownloadImageTask(myholder.myimageview1).execute(mydatalist.get(position).getImage());
return convertView;
}
static class ViewHolder
{
public TextView mytextview1;
public TextView mytextview2;
public TextView mytextview3;
public ImageView myimageview1;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
How can I solve this?
Put the three lines
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
in this method:
#Override
public void onResponse(String string) {
parseJsonData(string);
// put them here
}
This will work because it populates the list after the data is parsed add then adds it to the adapter. If you add the list to the adapter in OnCreate, the onResponse method will run later (when the data is returned) and the list will be empty.
you need to create fragments for every item which you declare in navigation and do parsing and all thing in it and that fragment is called from onNavigationItemSelected and if you want which is always show first than you have to call it in also from onCreate() method.

Categories