(Android Studio Java) FAB OnClick Alert Dialog makes app crash - java

Here is activity_main code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:gravity="center"
android:textSize="36sp"
android:textColor="#color/colorPrimary"
android:text="To Do"
android:layout_marginTop="45dp"
android:fontFamily="#font/montserratlight"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"
android:layout_marginTop="126dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp">
</ListView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="50dp"
android:src="#drawable/plussymbol" />
</RelativeLayout>
Here is my MainActivity Java Code:
package com.geoff.productivitywatch;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
int clickCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.listView);
final ArrayList<String> todo = new ArrayList<>();
todo.add("Swipe Up");
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.tododesign, todo);
list.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here is where the pop-up box code goes
final EditText todoEditText = new EditText(getApplicationContext());
AlertDialog dialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("New Task")
.setMessage("What next?")
.setView(todoEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Add Task to listview
String task = String.valueOf(todoEditText.getText());
todo.add("" + task);
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
});
}
}
I tried to write a method in which clicking the floating action button brought up a dialog alert box where you could edit text and then add it to a listview. Android Studio does not see an error in my code, however when I test the app on my android device, as soon as the Floating Action Button is clicked, the app crashes. However, I know it is not an issue with my device since I have tested it successfully numerous times before, it only began crashing when I added the AlertDialog method. I think I may have gone wrong with the contexts, however I have changed them to all the variants I can think of and it has not helped.

IDK what is the actual reason causing the crash as you didn't shared the logcat but I have noticed whatever you trying to achieve is something that is possible with the Dialog and not by the AlertDilaog
here is my explanation :
create a separate .xlm layout file for the dialog. with you edit text and some ok and cancel button.
inside the onClick of the fab create/inflate and show the dialog
// Create a custom dialog object
final Dialog dialog = new Dialog(MainActivity.this);
// Include dialog.xml file
dialog.setContentView(R.layout.your_dialg_layout);
// Set dialog title
dialog.setTitle("Custom Dialog");
// set values for custom dialog components - text, image or button
EditText todoEditText = dialog.findViewById(R.id.your_edit_text);
Button mPositivButton = dialog.findViewById(R.id.your_yes_button);
Button mNegativeButton = dialog.findViewById(R.id.your_cancle_button);
mPositivButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = String.valueOf(todoEditText.getText());
todo.add("" + task);
dialog.dismiss();
}
});
mNegativeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Also this post can help you
How to make a edittext box in a dialog

Related

Why are the buttons not working when i run the app?

My app doesn't response when i type
Android app project that has two (2) text fields and one (1) button. The button will
compare the input from the text fields and display a response (SAME if values are the same
and NOT THE SAME if they are not) if it is clicked. You may need to create a new activity
for this.
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button checkbtn = (Button)findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
Here is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/checkButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/firsttextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="" tools:targetApi="o" />
<EditText
android:id="#+id/secondtextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:importantForAutofill="no"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firsttextEditText" />
<Button
android:id="#+id/checkBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/secondtextEditText" />
</androidx.constraintlayout.widget.ConstraintLayout>
first of all, you can't compare two EditText references together to get the result of text values equality.
you can get the text wrote in the editText using getText() method
then start to compare both strings values.
also, I suggest declaring EditText out of scope setOnClickListener so that not declare new instances every time the user click button.
so your final java code can be like :
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
Button checkbtn = (Button) findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstValue = firstttextEditText.getText().toString();
String secondValue = secondtextEditText.getText().toString();
if (firstValue.equals(secondValue)) {
Intent sameTextIntent = new Intent(getApplicationContext(), SameText.class);
startActivity(sameTextIntent);
} else {
Intent notsameTextIntent = new Intent(getApplicationContext(), NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
I suggest you learn more about EditText from here
you are comparing the EditText, not the text inside the edit text. maybe change your codes to something like this.
String firstttextEditText = findViewById(R.id.firsttextEditText)).getText().toString();
String secondtextEditText = findViewById(R.id.secondtextEditText).getText().toString();
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}

how to create button on android platform

I created a button in my Android project, but it's not working.
Here is my application (based on 'hello world'):
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="#+id/button_roy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
and this is my java roy.java
package aa.aa.aaaaaaa.royb;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by royb on 05/11/13.
*/
public class roy extends Activity {
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button createBtn = (Button) findViewById(R.id.button_roy);
createBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v)
{
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
}
When I run it on my android device and click the button it doesn't do anything.
How can I make the toast display?
public class Roy extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button createBtn = (Button) findViewById(R.id.button_roy);
createBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v)
{
Toast.makeText(getApplicationContext,"HelloToast",Toast.LENGTH_SHORT).show();
}
}
}

The method getText() is undefined for the type ListView

I am trying to implement a popup window where you type text and it adds it to the ListView however I am getting the following error:
The method getText() is undefined for the type ListView
My MainActivity.java code is as follows:
package com.mkyong.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
final Context context = this;
private Button button;
private ListView result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// components from main.xml
button = (Button) findViewById(R.id.buttonPrompt);
result = (ListView) findViewById(R.id.listView1);
// add button listener
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final ListView userInput = (ListView) promptsView
.findViewById(R.id.ListTitleDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Create",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to result
// edit text
result.setText(userInput.getText());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
}
Thanks for your assistance.
EDIT: The code for the for prompts.xml where the ListTitleDialogUserInput is defined is as follows;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Title: "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/ListTitleDialogUserInput"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>
You cannot put text directly in a ListView - the purpose of a ListView is to contain other Views.
Put a text-compatible view such as a TextView within your ListView, and call setText() on that.
If you really wanted a ListView that could directly display text, you'd have to make your own subclass which extends ListView and does some odd overlay or substitution magic to let you display text directly on it.

Show/Hide webview issue

I'm working in an application that has in the same view a set of buttons and a web view(GONE), when the app starts it shows only the buttons from where at a click it shows the web view and loads a url (the layout where the buttons are is set to GONE) that contains a flash media player and a single button that when is click it makes the web view invisible again and shows the first layout that contains the buttons to be able to choose a different website, the problem is that when the web view goes invisible the flash media players stays stuck on the screen and blocks the buttons, how can I fix this? It would be ok if the media player stays behind the buttons but I cannot find an answer, any help will be highly appreciated, Thank you.
Update with Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:layout_height="wrap_content" android:id="#+id/linearLayout1" android:layout_width="match_parent" android:orientation="vertical">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Web 1" android:id="#+id/buttonWeb1"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/buttonWeb2" android:text="Web 2"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Web 3" android:id="#+id/buttonWeb3"></Button>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content" android:id="#+id/linearLayout2" android:layout_width="match_parent" android:orientation="vertical">
<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/buttonBack" android:text="Back to Buttons"></Button>
<WebView android:layout_height="match_parent" android:layout_width="match_parent" android:id="#+id/webView"></WebView>
</LinearLayout>
And the main Activity
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
public class FlashejemploActivity extends Activity {
WebView wv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
final LinearLayout buttons = (LinearLayout) findViewById(R.id.linearLayout1);
final LinearLayout webV = (LinearLayout) findViewById(R.id.linearLayout2);
final Button web1 = (Button) findViewById(R.id.buttonWeb1);
final Button web2 = (Button) findViewById(R.id.buttonWeb2);
final Button web3 = (Button) findViewById(R.id.buttonWeb3);
final Button back = (Button) findViewById(R.id.buttonBack);
wv = (WebView) findViewById(R.id.webView );
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginsEnabled(true);
wv.setWebViewClient(new WebViewClient());
wv.setInitialScale(1);
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setUseWideViewPort(true);
final Activity PActivity = this;
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
PActivity.setTitle("Cargando....");
PActivity.setProgress(progress * 100);
if(progress == 100)
PActivity.setTitle(R.string.app_name);
}
});
webV.setVisibility(View.GONE);
web1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttons.setVisibility(View.GONE);
webV.setVisibility(View.VISIBLE);
wv.loadUrl("http://los40.com.mx/Player.htm");
}});
web2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttons.setVisibility(View.GONE);
webV.setVisibility(View.VISIBLE);
wv.loadUrl("http://www.beat1009.com.mx/n2/paginas/radio.php");
}});
web3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttons.setVisibility(View.GONE);
webV.setVisibility(View.VISIBLE);
wv.loadUrl("http://besame.com.mx/Player.htm");
}});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttons.setVisibility(View.VISIBLE);
webV.setVisibility(View.GONE);
}});
}
}
I know its been a while but I have just solved a similar problem by getting the webview to empty
wv.loadUrl("about:blank");

Changing the position of the thumb of the SeekBar using a different Button

I'm trying to move the position of the seekbar using a button. Basically I have a seekbar from 0 to 100. and I have button presents set up at arbitrary values (40,50,60 etc). When I try to set the progress on the seekbar via button, I get a fault.. I've already initialized the seekBar in the onCreate() method.
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar1);
currentProgress = 40;
seekBar.setMax(100);
seekBar.setProgress(currentProgress);
button40.setOnClickListener(button40Listener);
But when use the below, it crashes.
private OnClickListener button40Listener = new OnClickListener() {
public void onClick(View v) {
currentProgress = 40;
seekBar.setProgress(currentProgress);
}
}
This seems straight-forward. Any ideas?
You shouldn't need to put up another Seekbar. The initial one should be fine. Without the exception message and stack trace I'm not sure what is causing the crash. However, I just coded an example and works as you would expect. Perhaps by looking at my example you can identify your issue.
SeekbarTest.java:
package com.example.seekbartest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
public class SeekbarTest extends Activity {
/** Called when the activity is first created. */
private SeekBar seekBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seekBar = (SeekBar)findViewById(R.id.seekBar1);
Button fortyPctButton = (Button)findViewById(R.id.buttonFortyPct);
fortyPctButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
seekBar.setProgress(40);
}
});
Button sixtyPctButton = (Button)findViewById(R.id.buttonSixtyPct);
sixtyPctButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
seekBar.setProgress(60);
}
});
Button eightyPctButton = (Button)findViewById(R.id.buttonEightyPct);
eightyPctButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
seekBar.setProgress(80);
}
});
}
}
And here is the main.xml it is referencing for the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:text="#string/hello"
android:id="#+id/textView1"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBar1"
android:layout_below="#+id/textView1"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView1"/>
<Button
android:layout_width="wrap_content"
android:text="40%"
android:id="#+id/buttonFortyPct"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar1"
android:layout_alignLeft="#+id/seekBar1"/>
<Button
android:layout_width="wrap_content"
android:text="60%"
android:id="#+id/buttonSixtyPct"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/buttonFortyPct"
android:layout_alignTop="#+id/buttonFortyPct"
android:layout_alignBottom="#+id/buttonFortyPct"/>
<Button
android:layout_width="wrap_content"
android:text="80%"
android:id="#+id/buttonEightyPct"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/buttonSixtyPct"
android:layout_alignTop="#+id/buttonSixtyPct"
android:layout_alignBottom="#+id/buttonSixtyPct"/>
</RelativeLayout>
Just create a new android app and replace the generated code + layout with the example above. It should work for you.
Good luck,
Craig

Categories

Resources