I have implemented navigation drawer on my mobile application and whenever i open the drawer and click on the drawer, the drawer closes itself. It used to work perfectly until I implemented another function and I am puzzled about how I should fix this.
Here's my main activity code. I am unable to navigate using the navigation drawer now.
package com.example.admin.calendlist;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
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.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
DatabaseHelper dbHelper;
ArrayAdapter<String> mAdapter;
ListView lstTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
dbHelper = new DatabaseHelper(this);
lstTask = (ListView)findViewById(R.id.lstTask);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView nvDrawer = (NavigationView)findViewById(R.id.nav_view);
setupDrawerContent(nvDrawer);
loadTaskList();
}
private void loadTaskList() {
ArrayList<String> taskList = dbHelper.getTaskList();
if(mAdapter==null){
mAdapter = new ArrayAdapter<String>(this, R.layout.row,R.id.task_title,taskList);
lstTask.setAdapter(mAdapter);
}
else{
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
{
switch (item.getItemId()) {
case R.id.action_add_task:
final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add New Task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
dbHelper.insertNewTask(task);
loadTaskList();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
switch (item.getItemId()) {
case R.id.td:
Intent newIntent = new Intent(this,MainActivity.class);
return true;
}
switch (item.getItemId()) {
case R.id.tt:
Intent newIntent = new Intent(this,Timetable.class);
return true;
}
switch (item.getItemId()) {
case R.id.ep:
Intent newIntent = new Intent(this,EventPage.class);
return true;
}
}
return super.onOptionsItemSelected(item);
}
private void selectItemDrawer(MenuItem item) {
int id = item.getItemId();
if (id ==R.id.ep) {
Intent newItent = new Intent (this, EventPage.class);
startActivity(newItent);
}
else if (id == R.id.td) {
Intent newIntent = new Intent (this,MainActivity.class);
startActivity(newIntent);
}
else if (id == R.id.tt) {
Intent newIntent = new Intent (this,Timetable.class);
startActivity(newIntent);
}
DrawerLayout drawer = findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
private void setupDrawerContent (NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener (new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.listmenu,menu);
Drawable icon =menu.getItem(0).getIcon();
icon.mutate();
icon.setColorFilter(getResources().getColor(android.R.color.black), PorterDuff.Mode.SRC_IN);
return super.onCreateOptionsMenu(menu);
}
public void deleteTask(View view){
View parent = (View)view.getParent();
TextView taskTextView = (TextView)findViewById(R.id.task_title);
String task = String.valueOf(taskTextView.getText());
dbHelper.deleteTask(task);
loadTaskList();
}
}
If you don't want navigation to close with each click, write like this :
NavigationView navigationView = findViewById(R.id.navigationView);
navigationView.bringToFront();
you can use it after switch
switch(id){
}
//Set menuItem checked and title
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
return false;
its obvious in Default drawerlayout on your click it has to be close,if you wana get command on your drawerlayot , hen you have to use custom drawerlayout, or you can add the library, don't forget to import the library manually not in your gradle, then you can edit the library, and chose the functions .
try this Library
Related
Hello friend please help me i am using Recylerview and implemented searchfilter but problem is that after searching the item in recylerview when i click on item it always return 0 position of the item i want actual position of list item please me help here is my code how get actual position recylerview after searching item in recylerview
here is my code
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
private ListView listView;
private ArrayList<String> books;
private ArrayList<String> bookid;
private ListViewAdapter adapter;
private DatabaseHelper mDBHelper = null;
private SQLiteDatabase mDb = null;
BookRecyclerAdopter bookRecyclerAdopter;
//life is awesome
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
setData();
RecyclerView bookanme = findViewById(R.id.list);
bookanme.setLayoutManager(new LinearLayoutManager(this));
bookRecyclerAdopter = new BookRecyclerAdopter(this, books);
bookanme.setAdapter(bookRecyclerAdopter);
/* adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
listView.setAdapter(adapter);*/
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booknumber=position;
String bookname=bookid.get(position);
Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();
*//* Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booknumber);
intent.putExtra("bookname",bookname);
startActivity(intent);*//*
}
});
}
*/
}
#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 onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_voice_btn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
searchView.setOnQueryTextListener(this);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite) {
Intent intent = new Intent(this, Favourite.class);
startActivity(intent);
} 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;
}
private void setData() {
books = new ArrayList<>();
bookid = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
books.add(cursor.getString(1));
bookid.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
String userinput = newtext.toLowerCase();
List<String> newlist = new ArrayList<>();
for (String name : books) {
if (name.toLowerCase().contains(userinput)) {
newlist.add(name);
}
}
bookRecyclerAdopter.updatelist(newlist);
return true;
}
}
package bible.swordof.God;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.context=context;
}
public class Booksholder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView bookname;
public Booksholder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
bookname = (TextView) itemView.findViewById(R.id.text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public Booksholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_listview, viewGroup, false);
return new Booksholder(view);
}
#Override
public void onBindViewHolder(#NonNull Booksholder booksholder, final int i) {
booksholder.bookname.setText(bookname.get(i));
//get first letter of each String item
String firstLetter = String.valueOf(bookname.get(i).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(bookname.get(i));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
booksholder.imageView.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return bookname.size();
}
public void updatelist(List<String>newlist){
bookname=new ArrayList<>();
bookname.addAll(newlist);
notifyDataSetChanged();
}
}
You will need to maintain a separate list of bookname. Let's call it filteredBookname. Initially set it as bookname.
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
private List<String> filteredBookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.filteredBookname = bookname
this.context=context;
}
...
// other pieces of code.
and instead of using bookname to populate RecyclerView items, use filteredBookname
and your update list method will be,
public void updatelist(List<String>newlist){
filteredBookname=new ArrayList<>();
filteredBookname.addAll(newlist);
notifyDataSetChanged();
}
Using the above approach, you can always find the proper position of your item in the original list bookname
The reason is that you are picking the wrong list, pick your data from filtered adapter list/model.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Books booksdata= (Books)adapterName.bookname.get(position);
Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booksdata.booknumber);
intent.putExtra("bookname",booksdata.bookname);
startActivity(intent);
}
});
}
holder.cardView_title.setOnClickListener {
when (holder.tv_number.text) {
"1" -> {
(context as Activity).startActivity(Intent(context, Ma1::class.java))
}
"2" -> {
(context as Activity).startActivity(Intent(context, Ma2::class.java))
}
"3" -> {
(context as Activity).startActivity(Intent(context, Ma3::class.java))
}
}
}
I want to Implement Onclick Item in recyclerView To open new activity I can pass data from one to another activity but in the code cannot figure out where to Implement on click onclicklistener if anyone is free to help me edit and give intent to Details.class
as I am getting data from firebase its first time to work on firebase any help would be appreciated.
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
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.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.dekhou.provissionstore.model.Movie;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FloatingActionButton fab;
ScaleAnimation shrinkAnim;
private RecyclerView mRecyclerView;
private StaggeredGridLayoutManager mLayoutManager;
private TextView tvNoMovies,tvNoMovies1;
private Context context;
//Getting reference to Firebase Database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseReference = database.getReference();
private static final String userId = "01";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
//Initializing our Recyclerview
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
tvNoMovies = (TextView) findViewById(R.id.tv_no_movies);
//tvNoMovies1 = (TextView) findViewById(R.id.addresstxt);
//scale animation to shrink floating actionbar
shrinkAnim = new ScaleAnimation(1.15f, 0f, 1.15f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
if (mRecyclerView != null) {
//to enable optimization of recyclerview
mRecyclerView.setHasFixedSize(true);
}
//using staggered grid pattern in recyclerview
mLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
//Say Hello to our new FirebaseUI android Element, i.e., FirebaseRecyclerAdapter
FirebaseRecyclerAdapter<Movie,MovieViewHolder> adapter = new FirebaseRecyclerAdapter<Movie, MovieViewHolder>(
Movie.class,
R.layout.movie_board_item,
MovieViewHolder.class,
//referencing the node where we want the database to store the data from our Object
mDatabaseReference.child("users").child(userId).child("shops").getRef()
) {
#Override
protected void populateViewHolder(MovieViewHolder viewHolder, final Movie model, final int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvMovieName.setText(model.getMovieName());
viewHolder.address.setText(model.getAddress());
viewHolder.phone.setText(model.getPhone());
viewHolder.lit.setText(model.getLit());
viewHolder.lon.setText(model.getLon());
Picasso.with(MainActivity.this).load(model.getMoviePoster()).into(viewHolder.ivMoviePoster);
// all your stuff
}
};
mRecyclerView.setAdapter(adapter);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_container, new AddMovieFragment())
.addToBackStack(null)
.commit();
//animation being used to make floating actionbar disappear
shrinkAnim.setDuration(400);
fab.setAnimation(shrinkAnim);
shrinkAnim.start();
shrinkAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//changing floating actionbar visibility to gone on animation end
fab.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
}
#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.menu_map) {
Intent intent = new Intent(this, MapsActivity.class);
this.startActivity(intent);
}
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_slideshow) {
Intent cinemaIntent = new Intent(this, MapsActivity.class);
startActivity(cinemaIntent);
} else if (id == R.id.nav_manage) {
Intent cinemaIntent = new Intent(this, Get_Data.class);
startActivity(cinemaIntent);
} else if (id == R.id.nav_share) {
try {
//try to open page in facebook native app.
String uri = "fb://page/" + "293069792077"; //Cutsom URL
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
}catch (ActivityNotFoundException ex){
//facebook native app isn't available, use browser.
String uri = "http://touch.facebook.com/pages/x/" + "293069792077"; //Normal URL
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
} else if (id == R.id.nav_send) {
Intent cinemaIntent = new Intent(this, About_Us.class);
startActivity(cinemaIntent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//ViewHolder for our Firebase UI
public static class MovieViewHolder extends RecyclerView.ViewHolder{
TextView tvMovieName,address,phone,lit,lon;
ImageView ivMoviePoster;
public MovieViewHolder(View v) {
super(v);
tvMovieName = (TextView) v.findViewById(R.id.tv_name);
address = (TextView) v.findViewById(R.id.address1);
phone = (TextView) v.findViewById(R.id.tv_phone);
lit = (TextView) v.findViewById(R.id.geo);
lon = (TextView) v.findViewById(R.id.geo2);
ivMoviePoster = (ImageView) v.findViewById(R.id.iv_movie_poster);
}
}
}
Add onClickListener to the itemView for your ViewHolder in populateViewHolder and start the Activity. like the below example.
#Override
protected void populateViewHolder(MovieViewHolder viewHolder, final Movie model, final int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvMovieName.setText(model.getMovieName());
viewHolder.address.setText(model.getAddress());
viewHolder.phone.setText(model.getPhone());
viewHolder.lit.setText(model.getLit());
viewHolder.lon.setText(model.getLon());
Picasso.with(MainActivity.this).load(model.getMoviePoster()).into(viewHolder.ivMoviePoster);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
//intent.putExtra("model", model);
intent.putExtra("latitude", model.getLit());
intent.putExtra("longitude", model.getLon());
startActivity(intent);
}
});
// all your stuff
}
try this add onClickListener in your populateViewHolderlike this
#Override
protected void populateViewHolder(MovieViewHolder viewHolder, final Movie model, final int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvMovieName.setText(model.getMovieName());
viewHolder.address.setText(model.getAddress());
viewHolder.phone.setText(model.getPhone());
viewHolder.lit.setText(model.getLit());
viewHolder.lon.setText(model.getLon());
Picasso.with(MainActivity.this).load(model.getMoviePoster()).into(viewHolder.ivMoviePoster);
viewHolder.tvMovieName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
startActivity(intent);
}
});
}
I got a navigation drawer, and when i click one of the items in it, it should open an other activity. so i made a switch, and don't get any errors. Still when i launch the application it keeps crashing. Need any help i can get!!!
Java is below
package com.gfo.enexis;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.id;
import static android.R.attr.start;
import static android.R.id.edit;
import static android.R.id.list;
import static com.gfo.enexis.R.id.button;
import static com.gfo.enexis.R.id.lv1;
import static com.gfo.enexis.R.id.nav_acount;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
registerClickCallBack();
OnNavigationItemSelected();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Weet u zeker dat u wilt uitloggen?")
.setPositiveButton("Log uit", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
finish();
//close();
}
})
.setNegativeButton("Nee", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
EditText NotitieEt;
ListView ListNote;
ArrayList<String> lv = new ArrayList<>();
public void NoteAdd(View view) {
ListNote = (ListView) findViewById(lv1);
NotitieEt = (EditText) findViewById(R.id.notitie);
String note1 = NotitieEt.getText().toString();
if (lv.contains(note1)) {
Toast.makeText(this, "Notitie bestaat al", Toast.LENGTH_LONG).show();
} else if (note1 == null || note1.trim().equals("")) {
Toast.makeText(this, "Imput can't be empty", Toast.LENGTH_LONG).show();
} else {
lv.add(note1);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, lv);
ListNote.setAdapter(adapter);
((EditText) findViewById(R.id.notitie)).setText("");
}
}
private void registerClickCallBack() {
ListNote = (ListView) findViewById(lv1);
ListNote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paret, View viewClicked, int position, long id) {
lv.remove(position);
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, lv);
ListNote.setAdapter(adapter);
}
});
}
MenuItem item;
public boolean OnNavigationItemSelected() {
int id = item.getItemId();
switch (id) {
case R.id.nav_acount:
Intent i = new Intent(MainActivity.this, DashBoard1.class);
startActivity(i);
break;
case R.id.nav_dashboard:
Intent o = new Intent(MainActivity.this, Dashboard2.class);
startActivity(o);
}
return true;
}
}
these are the errors i'm getting:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gfo.enexis/com.gfo.enexis.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.view.MenuItem.getItemId()' on a null object reference
and
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.view.MenuItem.getItemId()' on a null object reference
You are not initializing the
MenuItem item;
so it's NULL! And i think your are implementing "OnNavigationItemSelected" in the wrong way. Why are you calling "OnNavigationItemSelected();" in "onCreate()" method?
Just follow the official tutorial and you will be ok:
https://developer.android.com/training/implementing-navigation/nav-drawer.html
I think your problem is that you haven't registered the Navigation Drawer in the onCreate().
Use this:
NavigationView navigationView = (NavigationView) findViewById(R.id.yourIdHere);
navigationView.setNavigationItemSelectedListener(this);
Also, to handle navigation drawer clicks, override the method:
onNavigationItemSelected(MenuItem item)
Someone who can help me to fix this problem. (NoSuchMethodError) I really don't understand this error.
I have found similar problems on the web, but none of the posted solutions appear to work. Someone who can help me.
EDIT: I AM already working on Android Studio.
My screenshot
Other
package com.example.android.xxxxxxxxxxy;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class MainActivity extends AppCompatActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
// The firstbutton (song).
assert adView != null;
adView.loadAd(adRequest);
final MediaPlayer happy_birthday_to_me = MediaPlayer.create(this, R.raw.happy_birthday_to_me);
Button playsongmeow = (Button) this.findViewById(R.id.play_song_meow);
assert playsongmeow != null;
playsongmeow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
happy_birthday_to_me.start();
}
});
// The secondbutton (song).
assert adView != null;
adView.loadAd(adRequest);
final MediaPlayer birthday = MediaPlayer.create(this, R.raw.birthday);
Button playsongmeoww = (Button) this.findViewById(R.id.play_song_meoww);
assert playsongmeoww != null;
playsongmeoww.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
birthday.start();
}
});
// The thirdbutton (song).
assert adView != null;
adView.loadAd(adRequest);
final MediaPlayer happy = MediaPlayer.create(this, R.raw.happy);
Button playsongmeowww = (Button) this.findViewById(R.id.play_song_meowww);
assert playsongmeowww != null;
playsongmeowww.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
happy.start();
}
});
// The fourthbutton (song).
assert adView != null;
adView.loadAd(adRequest);
final MediaPlayer original = MediaPlayer.create(this, R.raw.original);
Button playsongmeowwww = (Button) this.findViewById(R.id.play_song_meowwww);
assert playsongmeowwww != null;
playsongmeowwww.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
original.start();
}
});
}
private void addDrawerItems() {
String[] osArray = {"Songs", "Photos", "Videos", "About"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
switch (position) {
case 0: //Log History
Intent MainActivity = new Intent(MainActivity.this, MainActivity.class);
startActivity(MainActivity);
break;
case 1: //Log History
Intent Photos = new Intent(MainActivity.this, Photos.class);
startActivity(Photos);
break;
case 2: //Log History
Intent Videos = new Intent(MainActivity.this, Videos.class);
startActivity(Videos);
break;
case 3: //Log History
Intent About = new Intent(MainActivity.this, About.class);
startActivity(About);
default:
}
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("List Menu");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
// Inflate your main_menu into the menu.
int id = item.getItemId();
switch (id){
case R.id.about:
Intent About = new Intent(MainActivity.this, About.class);
startActivity(About);
break;
}
switch (id) {
case R.id.rate:
// Open this Uri.
Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=com.exafmpflle.android.happybirthdayyyy&hl=en"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
break;
}
switch (id){
case R.id.privacy:
// Open this Uri.
Uri uri = Uri.parse("https://docs.google.com/document/d/1DEBh3j3LG5WaF9nT9Gl2hpswa3yD-36MfPhVo3S_p08/edit"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
break;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The error seems to be saying that one of the methods that you are overriding is nonexistent. Try double checking the spellings of the methods that you are overriding.
If this helps, please consider marking this post as an answer.
i am creating an android app that uses a Navigation Drawer. Since i will have more than one Option in the drawer, i had to create a method passing the activity that i want to implement the navigation and the Activity Toolbar.
The problem is, i am receiving a Null Pointer when i declare the NavigatioDrawer method in the activities. let me show you:
HERE IS MY NAVIGATION DRAWER METHOD(WHICH I WILL INSTANTIATE IN THE ACTIVITY):
package studio.brunocasamassa.ajudaaqui.helper;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import studio.brunocasamassa.ajudaaqui.MainActivity;
import studio.brunocasamassa.ajudaaqui.PerfilActivity;
import studio.brunocasamassa.ajudaaqui.R;
import studio.brunocasamassa.ajudaaqui.ConfiguracoesActivity;
import studio.brunocasamassa.ajudaaqui.ChatActivity;
import studio.brunocasamassa.ajudaaqui.GruposActivity;
import studio.brunocasamassa.ajudaaqui.PedidosActivity;
import studio.brunocasamassa.ajudaaqui.SobreActivity;
/**
* Created by bruno on 24/04/2017.
*/
public class NavigationDrawer {
//NAVIGATION DRAWER
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//private static Activity setClasse = new Activity();
private static MainActivity main;
private static User usuario = main.user;
public void createDrawer(final Activity classe, Toolbar toolbar) {
//setClasse = classe;
//Itens do Drawer
PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.menu_pedidos);
PrimaryDrawerItem item2 = new PrimaryDrawerItem().withIdentifier(2).withName(R.string.menu_chats);
PrimaryDrawerItem item3 = new PrimaryDrawerItem().withIdentifier(3).withName(R.string.menu_grupos);
PrimaryDrawerItem item4 = new PrimaryDrawerItem().withIdentifier(4).withName(R.string.menu_perfil);
PrimaryDrawerItem item5 = new PrimaryDrawerItem().withIdentifier(5).withName(R.string.menu_configuracoes);
PrimaryDrawerItem item6 = new PrimaryDrawerItem().withIdentifier(6).withName(R.string.menu_sobre);
// Create the Navigation Drawer AccountHeader
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(classe)
.withHeaderBackground(R.color.colorPrimary)
.addProfiles(
new ProfileDrawerItem().withName("User").withEmail("user#example.com").withIcon(usuario.getProfileImageURL())
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
//Definition Drawer
Drawer drawer = new DrawerBuilder()
.withActivity(classe)
.withToolbar(toolbar)
.withAccountHeader(headerResult)
.addDrawerItems(
item1,
new DividerDrawerItem(),//Divisor
item2,
new DividerDrawerItem(),//Divisor
/*DIVISAO COM MENSAGEM new SectionDrawerItem().withName(R.string.section),//Seção*/
item3,
new DividerDrawerItem(),//Divisor
item4,
new DividerDrawerItem(),//Divisor
item5,
new DividerDrawerItem(),//Divisor
item6
//Divisor
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
StartActivity a = new StartActivity() ;
a.verifyActivity(classe, position);
return false;
}
})
.withSelectedItemByPosition(0)
.build();
}
}
class StartActivity extends AppCompatActivity {
public void verifyActivity(Activity classe, int position) {
if (position == 1) {
// HERE I AM TRYING USING DIFFERENT FORMS TO START THE ACTITIVIES
startActivity(new Intent(classe, PedidosActivity.class));
}
if (position == 3) {
startActivity(new Intent(classe, ChatActivity.class));
}
if (position == 5) {
startActivity(new Intent(classe, GruposActivity.class));
}
if (position == 7) {
startActivity(new Intent(classe, PerfilActivity.class));
}
if (position == 9) {
startActivity(new Intent(classe, SobreActivity.class));
}
}
}
HERE IS MY PedidosActivity(i call the navigator here):
package studio.brunocasamassa.ajudaaqui;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import com.facebook.login.LoginResult;
import studio.brunocasamassa.ajudaaqui.helper.NavigationDrawer;
import studio.brunocasamassa.ajudaaqui.helper.PedidosTabAdapter;
import studio.brunocasamassa.ajudaaqui.helper.SlidingTabLayout;
import studio.brunocasamassa.ajudaaqui.helper.User;
/**
* Created by bruno on 24/04/2017.
*/
public class PedidosActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListView listview_nomes;
private ViewPager viewPager;
private SlidingTabLayout slidingTabLayout;
public int posicao;
private LoginResult loginResult;
private MainActivity main;
private User usuario;
private static NavigationDrawer navigator = new NavigationDrawer();
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
toolbar = (Toolbar) findViewById(R.id.toolbar_principal);
toolbar.setTitle(getResources().getString(R.string.menu_pedidos));
//toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimaryDark));
setSupportActionBar(toolbar);
/*
loginResult = MainActivity.lr;
Profile profile = Profile.getCurrentProfile();
System.out.println("PROFILE: "+ profile);
String userid = loginResult.getAccessToken().getUserId();
String name = message(profile);
user.setName(name);*/
usuario = main.user;
System.out.println("USER: " + usuario.getName());
String username = usuario.getName();
loginResult=main.lr;
String userImg = usuario.getProfileImg();
listview_nomes = (ListView) findViewById(R.id.ListContatos);
viewPager = (ViewPager) findViewById(R.id.vp_pagina);
slidingTabLayout = (SlidingTabLayout) findViewById(R.id.stl_tabs);
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this, R.color.colorAccent));
PedidosTabAdapter pedidosTabAdapter = new PedidosTabAdapter(getSupportFragmentManager());
viewPager.setAdapter(pedidosTabAdapter);
slidingTabLayout.setViewPager(viewPager);
navigator.createDrawer(PedidosActivity.this, toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_exit:
//logoutUser();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
If someone could help, it will be very grateful
ITS WORKED, tks #MikeM, it was that what you said. Here is the answer
this method i call inside the Drawer onClickListener;
private void verifyActivity(Activity classe, int position) {
if (position == 1) {
// HERE I AM TRYING USING DIFFERENT FORMS TO START THE ACTITIVIES
classe.startActivity(new Intent(classe, PedidosActivity.class));
}
if (position == 3) {
classe.startActivity(new Intent(classe, ChatActivity.class));
}
if (position == 5) {
classe.startActivity(new Intent(classe, GruposActivity.class));
}
if (position == 7) {
classe.startActivity(new Intent(classe, PerfilActivity.class));
}
if (position == 9) {
classe.startActivity(new Intent(classe, SobreActivity.class));
}
here i call that, for each activity:
NavigationDrawer navigator = new NavigationDrawer();
navigator.createDrawer(PerfilActivity.this, toolbar);