I have developed an android application using java and android studio. But when I click the items in the navigation drawer, I expect it to display a dialog, but nothing happens. Also when I try to setText in the drawer, the application crashes. I'm new to android development. Please, I would greatly appreciate help.
Below is my code:
private TextView name;
public TextView email;
public TextView contact;
private DrawerLayout drawerLayout;
AlertDialog.Builder builder;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout=(DrawerLayout) findViewById(R.id.drawer);
builder=new AlertDialog.Builder(MainActivity.this);
name=(TextView) findViewById(R.id.myname);
email=(TextView) findViewById(R.id.myemail);
contact=(TextView) findViewById(R.id.mycontact);
actionBarDrawerToggle=new ActionBarDrawerToggle(this, drawerLayout,R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//RECEIVING THE INTENT
/* Get values from Intent
Intent intent = getIntent();
String myname = intent.getStringExtra("dname");
String myemail = intent.getStringExtra("demail");
String mycontact = intent.getStringExtra("dcontact");
name.setText(myname);
email.setText(myemail);
contact.setText(mycontact);
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, "+myname);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();*/
//name.setText(response);
/*try {
JSONObject jsonObject = new JSONObject(fname);
String fstname=jsonObject.getString("clockTym");
String lstname=jsonObject.getString("timediff");
String demail=jsonObject.getString("penalty");
String dcontact=jsonObject.getString("tot_penalty");
name.setText(fstname+" "+lstname);
email.setText(demail);
contact.setText(dcontact);
} catch (JSONException e) {
e.printStackTrace();
}*/
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.cin){
// Handle the camera action
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.db) {
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.permit) {
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.cout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You not initializing the navigation drawer which actually contains the list item though you already have onNavigationItemSelected listener so inside oncreate initialize the navigation view and attach the listener like
NavigationView navView = (NavigationView) findViewById(R.id.your_nav_id);
navView.setNavigationItemSelectedListener(this);
Related
Hi i'm trying to put an event Item click in my Navigation View from drawer it works fine, but the problem is the other items in my drawer stop working, it seems that putting an item click event on my navigation view affect my NavigationController
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bundy_clock);
dBhelper = new DBhelper(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.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 item) {
int id = item.getItemId();
if(id == R.id.nav_logout){
AlertDialog.Builder conDialog = new AlertDialog.Builder(BundyClock.this);
conDialog.setTitle("Confirm");
conDialog.setMessage("Are you sure you want to log out?");
conDialog.setCancelable(false);
conDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(BundyClock.this, MainActivity.class));
Toast.makeText(getApplicationContext(),"Successfully Logout",Toast.LENGTH_SHORT).show();
finish();
}
});
conDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog sdialog = conDialog.create();
sdialog.show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
You have to use NavigationUI.onNavDestinationSelected to handle this. Check below:
boolean handled = NavigationUI.onNavDestinationSelected(menuItem, navController);
if (!handled) {
if(id == R.id.nav_logout){
AlertDialog.Builder conDialog = new AlertDialog.Builder(BundyClock.this);
conDialog.setTitle("Confirm");
conDialog.setMessage("Are you sure you want to log out?");
conDialog.setCancelable(false);
conDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(BundyClock.this, MainActivity.class));
Toast.makeText(getApplicationContext(),"Successfully Logout",Toast.LENGTH_SHORT).show();
finish();
}
});
conDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog sdialog = conDialog.create();
sdialog.show();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return handled;
This question already has answers here:
AlertDialog OnBackPressed() Not Working Properly
(3 answers)
Closed 3 years ago.
I want to implement the Dialog box on Back-pressed Dialog Box on Navigation Drawer Back-pressed.
The Dialog Box Have Two Buttons and When I click on Ok It Exit The Application.
The Problem is the Dialog Box is not showing...
Here is my code of Navigation Drawer onBackpressed....
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
Toast.makeText(this, "BACK PRESSED", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Option");
builder.setMessage("Are You Sure To Exit??");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
dialog.cancel();
}
});
builder.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(DialogInterface dialog, int which) {
//go to Remove Item
finishAffinity();
dialog.cancel();
}
});
Try this code
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Exit Application?");
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
I am making an online food ordering app.My app was running good but when i add cart code it is showing abnormal behaviour like the cart button takes me to first screen i started.following is the cart.java code
public class Cart extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
TextView txtTotalPrice;
FButton btnPlace;
List<Order> cart=new ArrayList<>();
CartAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
//Firebase
database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//Init
recyclerView = (RecyclerView) findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
txtTotalPrice = (TextView) findViewById(R.id.total);
btnPlace =(FButton)findViewById(R.id.btnPlaceOrder);
btnPlace.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
showAlertDialog();
}
});
loadlistfood();
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("One more step!");
alertDialog.setMessage("Enter your Address: ");
final EditText edtAddress = new EditText(Cart.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edtAddress.setLayoutParams(lp);
alertDialog.setView(edtAddress);//add edt text to alert box
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
edtAddress.getText().toString(),
txtTotalPrice.getText().toString(),
cart
);
//submit to firebase
//we will use system.currntMill to key
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//Delete cart
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Thank you,Order placed", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void loadlistfood() {
cart=new Database(this).getCarts();
adapter=new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
//calculate price
int total=0;
for(Order order:cart)
total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
Locale locale=new Locale("en","US");
NumberFormat fmt=NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
}
Rest i had put a intent in where cart button is put and else i have cartAdapter class and request.java.If you need them i will edit the question.Please help me.
Here is code that take me to cart.java.
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
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 = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
//init firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartIntent = new Intent(getApplicationContext(),Cart.class);
startActivity(cartIntent);
}
});
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);
//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=(RecyclerView)findViewById(R.id.recycler_meu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
adapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>(Category.class,R.layout.menu_item,MenuViewHolder.class,category) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
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) {
//Get category id and send to new Activity
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) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
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_menu) {
// Handle the camera action
} else if (id == R.id.nav_cart) {
// Intent cartIntent = new Intent(Home.this,Cart.class);startActivity(cartIntent);
} else if (id == R.id.nav_orders) {
} else if (id == R.id.log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Thank you in advance
I am still trying to learn java android so I am sure this is easy but I am trying to save the text from an alert started from an onclicklistener using the edit text to rename a button (tabButton). Do I have to create a seperate layout or will this work? I am getting an error at
final EditText input = new EditText(this);
Like I said I am still learning so a good explanation is appreciated. Here is my src so far.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Tab buttons controlled
final Button getTabButton = (Button) findViewById(R.id.tab1);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
getTabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Tab1 button was clicked.
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable tabname = input.getText();
// Do something with value!
tabname =
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this way,hope this will help you to solve your problem.
public class MainActivity extends Activity {
private Button getTabButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getTabButton = (Button) findViewById(R.id.tab1);
getTabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Title");
alert.setMessage("Message");
final EditText input = new EditText(MainActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity.this,input.getText().toString(),Toast.LENGTH_SHORT).show();
((Button)view).setText(input.getText());
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try like below:
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
getTabButton.settext(input.getText().toString());
}
});
These are two activities which are linked between each other but those are not working
and i have provided method name in xml file as onClick="menu" for both the buttons and the method over here
public class Welcome extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
/**Intent i = new Intent(this,Menup.class);
finish();
startActivity(i);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.welcome, menu);
return true;
}
public void menu(View v)
{
finish();
Intent i = new Intent(this,Menup.class);
startActivity(i);
}
}
it will be moved to the next activity name and code below
public class Menup extends Activity {
Button route,map,ticket;
TextView bal;
String time,src,des,clas,journey,noa,noc,amount;
int itime,old=50,amt,camt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menup);
bal=(TextView)findViewById(R.id.textView1);
//getting the values
Intent i=getIntent();
time=i.getExtras().getString("time");
itime=Integer.valueOf(time);
src=i.getExtras().getString("src");
des=i.getExtras().getString("des");
clas=i.getExtras().getString("class");
journey=i.getExtras().getString("journey");
noa=i.getExtras().getString("noa");
noc=i.getExtras().getString("noc");
amount=i.getExtras().getString("amount");
camt=Integer.valueOf(amount);
route=(Button)findViewById(R.id.imageButton1);
map=(Button)findViewById(R.id.imageButton2);
ticket=(Button)findViewById(R.id.imageButton3);
route.getBackground().setAlpha(0);
map.getBackground().setAlpha(0);
ticket.getBackground().setAlpha(0);
amt=old-camt;
bal.setText("Current Balance "+amt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menup, menu);
return true;
}
public void toroute(View v)
{
Intent r = new Intent(Menup.this,Route.class);
startActivity(r);
}
public void tomap(View v)
{
Intent m = new Intent(Menup.this,Map.class);
startActivity(m);
}
public void toticket(View v)
{
Intent d=new Intent(Menup.this,Tick.class);
d.putExtra("noa",noa);
d.putExtra("noc",noc);
d.putExtra("src",src);
d.putExtra("des",des);
d.putExtra("class", "Class I");
d.putExtra("journey", "Single");
d.putExtra("amount", amount);
d.putExtra("time", itime);
startActivity(d);
}
#Override
public void onBackPressed()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit");
builder.setMessage("Are you sure , you want to exit Ticketwala?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
finish();
System.exit(0);
dialog.dismiss();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
}).show();
}
}
You don't have to "finish()" your activity Welcome before starting the next activity. But if you must, then put it after startActivity();