fragment activity give error in alertdialog - android

i create an activity with fragment; then add an OnClickListener() for a button ;every thing work fine. but when i try to add an OnClickListener() for positivebutton to alertdialog eclipse give error before i can run program
it's piece of code that have error and i do not now why :(
AlertDialog.Builder exitDialog=new AlertDialog.Builder(getActivity());
exitDialog.setTitle("Alert");
exitDialog.setMessage("Exit Program");
exitDialog.setPositiveButton("Yes", new OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
// TODO Auto-generated method stub
System.exit(1);
}
});
exitDialog.setNegativeButton("NO", null);
exitDialog.show();
and it's whole code of my activity
package com.TB.mylistprojct;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class ActFooter extends Fragment
{
View EMyView =null;
Button BtnExit =null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
InitialUI();
}
#Override
public View onCreateView(LayoutInflater Inflater,ViewGroup Container,Bundle SavedInstanceState)
{
View MyView=Inflater.inflate(R.layout.actfooter, Container,false);
EMyView=MyView;
return MyView;
}
public void InitialUI()
{
BtnExit=(Button)EMyView.findViewById(R.id.Btn_exit);
BtnExit.setOnClickListener(BtnExit_OnClick);
}
public OnClickListener BtnExit_OnClick=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
AlertDialog.Builder exitDialog=new AlertDialog.Builder(getActivity());
exitDialog.setTitle("Alert");
exitDialog.setMessage("Exit Program");
exitDialog.setPositiveButton("Yes", new OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
System.exit(1);
}
});
exitDialog.setNegativeButton("NO", null);
exitDialog.show();
}
};
}
anybody can help about this error

Replace new OnClickListener() in your alert dialogs positive button click with: new DialogInterface.OnClickListener()

Please call InitialUI Method in onActivityCreated instead of onCreate Method.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
InitialUI();
}
May be it'll helpful to you. Yeah and replace OnClickListerner with DialogInterface.OnClickListener

Related

How to add Back Button from an Activity to a Fragment

I'm using a fragment because I used a nav drawer menu. After I click "Category" menu it will take me to "Category" fragment and in that fragment, I have added a floating action bar that will take you to "Add category" activity.
Since fragments can't be viewed in AndroidManifest.xml file, I can't make a fragment as a parent. What I want is to add a "Back Button" from "Add category" activity, display a toast message (If sure to leave without saving changes..etc) and will go back to "Category" fragment.
I have tried using "onBackPressed()" and "getSuppoerActionBar()" that will show a toast but when running the app, the toast message will just show up in a few seconds and will go back to "Category" fragment.
Please help. Thanks!
Here is my code.
CategoriesFragment.java
package com.example.devcash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class CategoriesFragment extends Fragment {
public CategoriesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_categories, container, false);
//add floating action button
FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
categories_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// when add fab is pressed, go to add product activity
Intent addprod = new Intent(getActivity(), AddCategoryActivity.class);
startActivity(addprod);
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Categories");
}
}
AddCategoryActivity.java
package com.example.devcash;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
AddCategoryActivity.super.onBackPressed();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
super.onBackPressed();
}
}
You need to remove below code from onBackPressed() as it is calling super class method and eventually destroying activity.
super.onBackPressed();
To handle toolbar back add following code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
onBackPressed();
default:
return super.onOptionsItemSelected(item);
}
}
Your AddCategoryActivity should be like this
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
quitActivity();
}
private void quitActivity() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
quitActivity();
return true;
} else
return super.onOptionsItemSelected(item);
}
}
you can use EventBus.
class Activity{
fun backToFragment(){
EventBus.postEvent(BackToFragmentEvent())
}
}
class HomeActivity{
EventBus.register{
fragmentmanager.replace(CategoriesFragment)
}
}

Error in Alert dialog

There is an error in 'return view' at listview.setOnItemLongClickListener method. The error says cannot return a value from a method with void result type. I am trying to create an alert dialog where it will notify the user whether it wants to delete.
package com.example.user.swen;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.example.user.swen.DB.RecordsDataSource;
import com.example.user.swen.Model.Records;
public class Record extends ListActivity {
public Button NewButton;
public RecordsDataSource Recordsdatasource;
ArrayAdapter<Records> RecordAdapter;
List<Records> records;
ListView listview;
Records selectedRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Addrecords();
//Referencing the Database
Recordsdatasource = new RecordsDataSource(this);
Recordsdatasource.open();
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//set the listView to use the custom List Adapter
records = (List<Records>) Recordsdatasource.getAll();
RecordAdapter = new RecordAdapter(this, 0, (ArrayList<Records>) records);
listview = (ListView) findViewById(android.R.id.list);
listview.setAdapter(RecordAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Duty: " + selectedRecord.getType())
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Information</font>"));
alert.show();
}
});
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteItem(selectedRecord);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Alert!!</font>"));
alert.show();
return true;
}
});
return view;
}
public void Addrecords() {
NewButton = (Button) findViewById(R.id.NewButton);
NewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addrecords = new Intent(Record.this, NewRecord.class);
startActivity(addrecords);
}
});
}
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
private void deleteItem(Records selectedRecord) {
Recordsdatasource.removeRecords(selectedRecord);
showToast(this, "Usage deleted");
RecordAdapter.notifyDataSetChanged();
RecordAdapter.notifyDataSetInvalidated();
refreshDisplay();
}
private void refreshDisplay() {
records = Recordsdatasource.getAll();
RecordAdapter.clear();
RecordAdapter.addAll(records);
}
}
You are trying to return a View from your Activity's onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//...
return view;
}
As you can see, onCreate() in an Activity has a void return type, meaning you shouldn't be returning anything in this method.
From the looks of your code, you are attempting to use this layout as the Activity's layout, but you are confusing the View inflation code with that used in a Fragment's onCreateView() method, which does indeed require you to return a View.
In an Activity, you need to call setContentView() to set the layout. You can either set the layout using the resource ID via setContentView(R.layout.activity_record), or if you want to inflate the View yourself you can call setContentView(view).
The call return view is actually located in onCreate. The function onCreate is declared to return nothing (void). Therefore, you cannot return an instance of View. You just have to remove that line or replace it with return; Also, onItemLongClick must return a boolean. So you can't move return view there either.

Button issue eclipse

I want to create a simple app in eclipse with a button. I want to make it so that after the button is pushed 10 times a message will pop up. The problem is that when I start the app and push the button 10 times , nothing happens. Could you please tell me what I've done wrong?
Here's my activity file:
package com.example.dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class Game extends Activity implements android.view.View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Button gamebutton = (Button) findViewById(R.id.gamebutton);
}
#Override
public void onClick(View v){
//TODO Auto-generated method stub
int clicked = 0;
clicked++;
if( clicked==10){
AlertDialog.Builder gamebuild = new AlertDialog.Builder(Game.this);
gamebuild.setMessage("Good");
gamebuild.setCancelable(false);
gamebuild.setPositiveButton("Quit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Game.this.finish();
}
});
gamebuild.setNegativeButton("One more!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
}
}
}
Thanks for response! I've edited the activity file this way:
package com.example.dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class Game extends Activity implements android.view.View.OnClickListener{
int clicked = 0;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Button gamebutton = (Button) findViewById(R.id.gamebutton);
}
#Override
public void onClick(View v){
//TODO Auto-generated method stub
clicked++;
if( clicked==10){
AlertDialog.Builder gamebuild = new AlertDialog.Builder(Game.this);
gamebuild.setMessage("Good");
gamebuild.setCancelable(false);
gamebuild.setPositiveButton("Quit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Game.this.finish();
}
});
gamebuild.setNegativeButton("One more!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
}
}
}
Still it's not working in a proper way. Sorry for dumb questions: I'm new to android.
new edit:
package com.example.dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class Game extends Activity implements android.view.View.OnClickListener{
int clicked = 0;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Button gamebutton = (Button) findViewById(R.id.gamebutton);
gamebutton.setOnClickListener(this);
}
#Override
public void onClick(View v){
//TODO Auto-generated method stub
clicked++;
if( clicked==10){
AlertDialog.Builder gamebuild = new AlertDialog.Builder(Game.this);
gamebuild.setMessage("Good");
gamebuild.setCancelable(false);
gamebuild.setPositiveButton("Quit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Game.this.finish();
}
});
gamebuild.setNegativeButton("One more!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
}
}
}
You put the counter inside the onClick function, causing it to reset every time. So, move
int clicked = 0;
from inside the onClick to before your onCreate such as:
int clicked = 0;
#Override
protected void onCreate....
This will make it set to 0 once, then stay equal to whatever it's last value was as long as the app is open and not killed.
Problem is that variable clicked is declared inside onClick. So it's always zero. You have to declare it globally, inside class Game.

I want to add alert dialog within if else statement in android

I want to alert dialog to display if the password and login id doesn't match. I tried the following code, but when i run if the text are same then it executes, but in the case if the password and Login Id doesn't match an alert is supposed to be display but instead the process exits saying unfortunately your project is ended.
I have attached my code below
package com.example.explicitintent;
import java.security.PublicKey;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1, b2,b3;
EditText e1, e2;
String username="saras", password="greek";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText0001);
e2 = (EditText) findViewById(R.id.editText0002);
b1 = (Button) findViewById(R.id.button0002);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if (username.equals(e1.getText().toString()) && (password.equals(e2.getText().toString())))
{
Intent b = new Intent(MainActivity.this,Contacts.class);
String s = e1.getText().toString();
String s1 = e2.getText().toString();
b.putExtra("d1", s);
b.putExtra("d2", s1);
startActivity(b);
}
else
{
AlertDialog.Builder alt = new AlertDialog.Builder(getApplicationContext());
alt.setIcon(R.drawable.ic_launcher);
alt.setTitle("WARNING");
alt.setMessage("Do u want to re-enter password");
alt.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
}
});
alt.setNegativeButton("NO",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
Toast.makeText(getApplicationContext(),"OK", Toast.LENGTH_SHORT).show();
}
});
alt.show();
}
}
});
b2 = (Button) findViewById(R.id.button0003);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent c = new Intent(MainActivity.this, Reset.class);
startActivity(c);
}
});
b3 = (Button) findViewById(R.id.button1);
b3.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(),"Password Saved", Toast.LENGTH_LONG).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;
}
}
Change this line
AlertDialog.Builder alt = new AlertDialog.Builder(getApplicationContext());
to
AlertDialog.Builder alt = new AlertDialog.Builder(arg0.getContext());
and you should change arg0 to something meaningful like view or v. If that doesn't work then please post the logcat so we can see what error you are getting. You need to use the appropriate Context for the situation and here you want the AlertDialog to use the Activity Context which is the same Context that your Button (or arg0) uses.
Note MainActivity.this will do the same thing here as argo.getContext() but I was recently informed that it is bad practice for reasons such as if you want to re-use this code then you have to change the activity name part of the code. Its a less dynamic way of accessing the Context.
Here is a good SO answer that addresses the issue of Context. It can be a tricky concept to grasp at first so you may want to read over it a few times and keep it close by.

AlertDialog crashes application

Can someone explain to me why this AlertDialog crashes?
package com.clicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Clicker extends Activity
{
public int clickerNumber = 0;
private TextView clickerText;
private Button clickerButton;
private Button resetButton;
// Called when the activity is first created.
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare each of the layout objects
clickerText = (TextView)findViewById(R.id.clickerText);
clickerButton = (Button)findViewById(R.id.clickerButton);
resetButton = (Button)findViewById(R.id.resetButton);
clickerText.setText("0");
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
resetQuestion.setMessage("Are you sure you want to reset the counter?");
resetQuestion.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
clickerNumber = 0;
clickerText.setText("0");
}
});
resetQuestion.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
clickerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clickerNumber++;
clickerText.setText(Integer.toString(clickerNumber));
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
resetQuestion.show();
}
});
};
};
This is a great fail:
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
You are trying to use a null object, and that (of course) will throw a NullPointerException
This is how I create dialogs (and I think it's the best way to do it):
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.dialogo_layout, null);
final AlertDialog.Builder resetQuestion = new AlertDialog.Builder(YourActivity.this)
// do whatever you want with the resetQuestion AlertDialog
Here, R.layout.dialogo_layout represent a file called dialogo_layout.xml in the res/layout dir that contains the dialog layout.

Categories

Resources