I am new in android learning. Using Android Studio. My app name is Design1
. I am learning events so created a event page with two buttons for testing two events, one is toast
and another is Alert dialog box
.The Toast is working fine but when I click ALERT
button to show the alert dialog then a message comes ie "Design1 has stopped".
If I remove the showAlert event from activity_events.xml and events.java files then my works perfect.
events.java
package com.example.borntoflirt.design1;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class events extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
}
public void showToast(View v) {
Context context = getApplicationContext(); // OR getBaseContext()
CharSequence text = "Hi Toast";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public void showAlert(View v) {
Context context1 = getApplicationContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context1);
builder.setMessage("Write your message here.");
builder.setCancelable(true);
builder.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
activity_events.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_light"
android:isScrollContainer="false"
android:orientation="vertical"
android:paddingLeft="15dp"
android:paddingRight="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight=".30"
android:background="@drawable/rounded_button"
android:text="Toast"
android:textColor="#000"
android:onClick="showToast"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:text="Alert"
android:textColor="#000"
android:background="@drawable/rounded_button"
android:layout_margin="2dp"
android:onClick="showAlert"/>
</LinearLayout>
</LinearLayout>