I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the value of the EditText parameter to the parent class, without get a NullPointerException.
My DialogHost class, this constructs, returns and links the parent to its buttons.
package jo.app.co;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class DialogHost extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
#override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
#override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_add, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#override
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogHost.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DialogHost.this.getDialog().cancel();
}
});
return builder.create();
}
}
This is my MainActivity class showing the dialog
package jo.app.co;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends FragmentActivity implements DialogHost.NoticeDialogListener {
#override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showNoticeDialog();
}
public void showNoticeDialog() {
DialogFragment dialog = new DialogHost();
dialog.show(getFragmentManager(), "DialogHost");
}
#override
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
#override
public void onDialogNegativeClick(DialogFragment dialog) {
Log.d ("INMAIN", "REACHED NEG");
}
}
Thisthe layout of my Dialog for reference.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/item_added"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/hint_add_item" />
</LinearLayout>
There seems to be problem with the way you are referring to the edit text. You need to get it from the view you inflated Please try the below code which adds all functionality in your main activity itself. If you want you can adapt to your case with a separate class:
public void showNoticeDialog() {
public String inputvalue;
LayoutInflater inflater = LayoutInflater.from(this);
final View textenter = inflater.inflate(R.layout.dialog_add, null)
final EditText userinput = (EditText) textenter.findViewById(R.id.item_added);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(textenter)
.setTitle("Your title");
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#override
public void onClick(DialogInterface dialog, int id) {
inputvalue = userinput.getText().toString();
// Do something with value in inputvalue
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
builder.show();
}
For alert dialog , you need to inflate an xml, only if you are planning to have multiple views like more than 1 edittext in that dialog. If you plan to have only 1 edittext as in your example, you dont need an xml and you can directly define an edittext and set it as the view of the alert dialog.
final EditText userinput = new EditText(context);
builder.setView(userinput);
Related
I'm a beginner in Android Studio and Java, and I'm building an app, which contains a dialog, built using DialogFragment. Here's the code for dialog.java:
package com.dkapps.shownamenow;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
public class datatype1 extends AppCompatDialogFragment {
String type = "";
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setNeutralButton("Regular Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "frac";
}
});
builder.setNeutralButton("Whole Number", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "whole";
}
});
builder.setNeutralButton("Mixed Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "mixed";
}
});
return builder.create();
}
}
Now, I have a textview in my activity_main with the id 'type'. I want this dialog to set the text of that textview to the value of the string type. How do I do that?
I'd be grateful if you'd provide me some code.
You could create a method inside your activity to change the TextView's content, and call it in each of the buttons onClick methods.
Here is a code sample:
// inside you activity
public setText(String text){
findViewById(R.id.type).setText(text);
}
// onClick methods
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).setText("whole")
// change "whole" with the value of the string suitable for each button
}
You can get rid of the variable type, if you do not need it elsewhere
You could get the textView of your activity with findViewById()
private TextView typeFromActivity;
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
typeFromActivity = (TextView) findViewById(R.id.type);
type = typeFromActivity.getText().toString();
...
return builder.create();
}
I am trying to make a small Android App for personal stuff and have two problem with my code now:
The code should execute the following until
isAlarm == false;
do {
(new BTask(context)).execute();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (isAlarm);
But it only does this once.
I want it to close the dialog box only it the correct password is entered, but it closes it everytime and not executing the command:
isAlarm = false;
I know, the code is not very beautiful, but I'm still learning. =)
package top.sysop.myapplication;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.ToneGenerator;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "";
public static Button btn1;
public static Button btn2;
public static Button btn3;
private MediaPlayer mMediaPlayer;
boolean isAlarm;
private String m_Text = "";
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.context=this;
setContentView(R.layout.activity_main);
dialogevent3();
}
public void dialogevent3() {
int i=1;
btn3 = (Button) findViewById(R.id.dial3);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Diebstahl!");
// Set up the input
final EditText input = new EditText(MainActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
if (m_Text.equals("pass"))
{
//end
isAlarm = false;
}
else
{
//repeat
dialog.dismiss();
dialogevent3();
}
}
});
do {
(new BTask(context)).execute();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (isAlarm);
// alert.show();
builder.show();
}
});
}
}
You're not initialzing the value of isAlarm so its containing the default value that is false.
there are some changes like
initialize boolean isAlarm = true
change while (isAlarm) to while (!isAlarm)
Hope this helps
You can achieve this continuous checking using TextWatcher and runnable.
custom_layout_for_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Password..."/>
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="40dp"
android:ems="10"
android:inputType="textPassword"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="Password here"
/>
</LinearLayout>
call this method to open a custom dialog from your Activity
public void customDialog()
{
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_layout_for_dialog);
dialog.setCancelable(true);
EditText edt_password= (EditText) dialog.findViewById(R.id.editText);
edt_password.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
//write all your operations here
String m_Text=s.toString();
if (m_Text.equals("pass"))
{
//end
isAlarm = false;
}
else
{
//repeat
dialog.dismiss();
dialogevent3();
}
}
});
//This handler checks for isAlarm for every 300ms
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (isAlarm){
(new BTask(context)).execute();
}
}
},300);
dialog.show();
}
Thanks guys
I've solved it using the following code:
MainActivity.java
package top.sysop.myapplication;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.ToneGenerator;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "";
public static Button btn1;
public static Button btn2;
public static Button btn3;
private MediaPlayer mMediaPlayer;
public static boolean isAlarm;
private String m_Text = "";
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.context=this;
setContentView(R.layout.activity_main);
dialogevent1();
dialogevent2();
dialogevent3();
}
public void dialogevent1() {
btn1 = (Button) findViewById(R.id.dial1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder altdial = new AlertDialog.Builder(MainActivity.this);
altdial.setMessage("Bitte geben Sie mich bei der Kasse ab.").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = altdial.create();
alert.setTitle("xxx");
alert.show();
}
});
}
public void dialogevent2() {
btn2 = (Button) findViewById(R.id.dial2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder altdial = new AlertDialog.Builder(MainActivity.this);
altdial.setMessage("Bitte geben Sie mich sofort bei der Kasse ab!").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = altdial.create();
alert.setTitle("xxx");
alert.show();
}
});
}
public void dialogevent3() {
isAlarm = true;
btn3 = (Button) findViewById(R.id.dial3);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buildDialog();
/* AlertDialog.Builder altdial = new AlertDialog.Builder(MainActivity.this);
altdial.setMessage("Sie begehen Diebstahl!").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
isAlarm = false;
dialogInterface.cancel();
}
});
AlertDialog alert = altdial.create();
alert.setTitle("xxx");*/
// alert.show();
}
});
}
private void buildDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Diebstahl!");
// Set up the input
final EditText input = new EditText(MainActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
if (m_Text.equals("pass"))
{
//end
isAlarm = false;
}
else
{
//repeat
dialog.dismiss();
buildDialog();
input.setText("");
}
}
});
(new BTask(context)).execute();
builder.show();
}
}
and
BTask.java
package top.sysop.myapplication;
import android.content.Context;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.AsyncTask;
import android.os.Vibrator;
/**
* Created by Szalewicz on 22.11.2017.
*/
public class BTask extends AsyncTask {
Context context;
public BTask() {
}
public BTask(Context context) {
this.context = context;
}
#Override
protected Object doInBackground(Object[] objects) {
final Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
final ToneGenerator toneGen1 = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
do {
v.vibrate(500);
toneGen1.startTone(ToneGenerator.TONE_CDMA_MED_SSL, 500);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (MainActivity.isAlarm);
//for (int faktor = 1; faktor <= 10; faktor ++) {
v.vibrate(500);
toneGen1.startTone(ToneGenerator.TONE_CDMA_MED_SSL, 500);
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//}
return false;
}
}
Now it's doing what I want =)
I am trying to open a dialog when clicking on a TextView. I have some code installed and I receive an error as shown below. Unfortunately I cannot resolve this on my own and thus need your help please.
The TextView
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:fontFamily="casual"
android:gravity="center"
android:onClick="openOptions"
android:padding="4dp"
android:text="#string/optionsText"
android:textAllCaps="true"
android:textColor="#000"
android:textSize="14sp" />
MainActivity.java:
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView subtotal1, subtotal2, subtotal3, totalScore;
EditText[] editTexts = new EditText[30];
int[] allNumbers = new int[30];
int tempID, sumSub1, sumSub2, sumSub3, totalSum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
subtotal1 = (TextView) findViewById(R.id.subtotal1);
subtotal2 = (TextView) findViewById(R.id.subtotal2);
subtotal3 = (TextView) findViewById(R.id.subtotal3);
totalScore = (TextView) findViewById(R.id.Total);
for (int i = 0; i < editTexts.length; i++) {
tempID = getResources().getIdentifier("field" + (i+1), "id", getPackageName());
editTexts[i] = (EditText) findViewById(tempID);
editTexts[i].addTextChangedListener(allTextWatcher);
}
}
public void openOptions() {
DialogFragment newFragment = new OptionsDialogFragment();
newFragment.show(getSupportFragmentManager(), "options");
}
}
OptionsDialogFragment.java:
import android.app.AlertDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
/**
* Created by lukas on 14.07.2017.
*/
public class OptionsDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog_message)
.setItems(R.array.options_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
return builder.create();
}
}
When clicking on the TextView, I get the following error message:
08-05 09:22:21.952 31036-31036/com.example.lukas.dicepokersheet E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lukas.dicepokersheet, PID: 31036
Theme: themes:{default=overlay:com.cyngn.hexo, iconPack:com.cyngn.hexo, fontPkg:com.cyngn.hexo, com.android.systemui=overlay:com.cyngn.hexo, com.android.systemui.navbar=overlay:com.cyngn.hexo}
java.lang.IllegalStateException: Could not find method openOptions(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatTextView with id 'Title'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Use your function like below code;
public void openOptions(View v) {
DialogFragment newFragment = new OptionsDialogFragment();
newFragment.show(getSupportFragmentManager(), "options");
}
use below code in onClickListener
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Are you sure?");
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
Process.killProcess(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();
public void openOptions(View view) {
DialogFragment newFragment = new OptionsDialogFragment();
newFragment.show(getSupportFragmentManager(), "options");
}
You need to keep the onclick method signature as public void method(View view) then only Textview onClick can detect and call it.
I have an alert dialog that allows user to edit a TextView. Currently, once the alert dialog closes, the user has to hit the back button and then re-enter the activity for the TextView to update. I've tried many solutions on SO but none seem to work. When the user clicks 'Save Changes', the TextView should update.
Calling activity:
package com.group1.workouttracker;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class DayActivity extends Activity {
//does not extend ListActivity, so list functions must be called by myList object
private String buttonClicked;
private String thisSummary;
private Intent intent;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_day);
db = DatabaseHelper.getInstance(getApplicationContext());
intent = getIntent();
buttonClicked = intent.getStringExtra("Day");
Button buttonCreateExercise = (Button) findViewById(R.id.buttonAddExercise);
buttonCreateExercise.setOnClickListener(new OnClickListenerCreateExercise(buttonClicked));
}
#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;
}
public void readSummary(String buttonClicked) {
TextView textViewSummary = (TextView) findViewById(R.id.textViewSummary);
textViewSummary.setOnLongClickListener(new OnLongClickListenerEditSummary(buttonClicked));
}
#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);
}
#Override
public void onResume() {
super.onResume();
thisSummary = db.readSummary(buttonClicked).getSummary();
TextView summary = (TextView) findViewById(R.id.textViewSummary);
summary.setOnLongClickListener(new OnLongClickListenerEditSummary(buttonClicked));
summary.setText(thisSummary);
}
}
Alert Dialog that activates on a long press:
package com.group1.workouttracker;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
public class OnLongClickListenerEditSummary implements View.OnLongClickListener {
Context context;
String dayClicked = "";
#Override
public boolean onLongClick(View view) {
context = view.getContext();
final DatabaseHelper db = DatabaseHelper.getInstance(context);
ObjectDay objectDay = db.readSummary(dayClicked);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.edit_summary_form, null, false);
final long dayId = objectDay.getId();
final String dName = objectDay.getDayName();
final EditText editTextSummary = (EditText) formElementsView.findViewById(R.id.editTextSummary);
final CharSequence[] items = { "Edit", "Delete" };
new AlertDialog.Builder(context).setTitle("Exercise");
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Edit Summary for " + dayClicked + ":")
.setPositiveButton("Save Changes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ObjectDay objectDay = new ObjectDay();
objectDay.setId(dayId);
objectDay.setDayName(dName);
objectDay.setSummary(editTextSummary.getText().toString());
boolean updateSuccessful = DatabaseHelper.getInstance(context).updateSummary(objectDay);
if(updateSuccessful) {
Toast.makeText(context, "Summary was updated.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Unable to update summary.", Toast.LENGTH_SHORT).show();
}
//dialog.cancel();
dialog.dismiss();
}
}).show();
return false;
}
public void editRecord(final String dName) {
final DatabaseHelper db = DatabaseHelper.getInstance(context);
ObjectDay objectDay = db.readSummary(dName);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.edit_summary_form, null, false);
final EditText editTextDay = (EditText) formElementsView.findViewById(R.id.editTextSummary);
final EditText editTextSummary = (EditText) formElementsView.findViewById(R.id.editTextSummary);
editTextSummary.setText(objectDay.getSummary());
}
public OnLongClickListenerEditSummary(String dayClicked) {
this.dayClicked = dayClicked;
}
}
Edit: I was able to get this working correctly by adding the following code:
Activity:
public void passThrough(ObjectDay objDay) {
textViewSummary.setText(objDay.getSummary());
}
In .setpositive button:
((DayActivity) context).passThrough(objectDay);
Opening a dialog wont trigger the Activity's onPause/onResume (I'm not sure if that's true for dialog fragments). Instead you can apply an onDismissListener (which can be a member variable of the Activity or anonymous) to the dialog.
When the dialog is closed (by any means) you'll get some information and you can update your textfield. Alternatively you could do the same from the positive click listener.
Either
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//UPDATE FROM HERE (call a method or manipulate an Activity member var)
}
});
OR
alert.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
//UPDATE FROM HERE (Check DialogInterface for positive if you want)
}
});
Edit, for your example:
class Whatever extends Activity {
private TextView mTextView;
private MyPassThroughListener mPassThroughListener = new MyPassThroughListener() {
#Override
public function passThrough(ObjectDay objDay) {
mTextView.setText(objDay.getSummary());
}
}
protected void onCreate(Bundle savedInstanceState) {
....
buttonCreateExercise.setOnClickListener(new OnClickListenerCreateExercise(mPassThroughListener ));
}
}
class OnLongClickListenerEditSummary {
MyPassThroughListener mPassThroughListener;
...
public OnLongClickListenerEditSummary (MyPassThroughListener passThroughListener) {
mPassThroughListener = passThroughListener;
}
#Override
public boolean onLongClick(View view) {
....
new AlertDialog.Builder(context)
.setPositiveButton("Save Changes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ObjectDay objectDay = new ObjectDay();
objectDay.setId(dayId);
objectDay.setDayName(dName);
objectDay.setSummary(editTextSummary.getText().toString());
mPassThroughListener.passThrough(objectDay);
dialog.dismiss();
}
...
}
}
public interface MyPassThroughListener {
public function passThrough(ObjectDay objDay);
}
I just picked up the android SDK and eclipse and decided to write a simple dialog that pops up when you click a button, however I found out that the showDialog() method has been deprecated and that the DialogFragment was the best way to go about making one, so here it is:
package net.learn2develop.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class DialogWindow extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
class MyDialog extends DialogFragment {
FragmentManager fm = getFragmentManager();
public MyDialog() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
MyDialog md = new MyDialog();
md.show(md.fm, "dialog");
}
});
}
}
The Debugger shows the error at:
md.show(md.fm, "dialog");
On further inspection, the fm variable is null according to the variables tab in the debugger, why is this so and is there a more efficient solution to this? I am seriously new to android, sorry if this is an easy question.
You should use an AlertDialog in this case, not a DialogFragment. Here is how I would do it:
public class DialogWindow extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog.show();
}
});
}
public Dialog createDialog() {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//getBaseContext() is not advised (I can't remember why right now but I know I read it. You may want to read more that method but for now getActivity will work for your Toast.
//Toast.makeText(getActivity(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getActivity(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
DialogFragments should be used in conjunction with other Fragments, in the case of a single activity it would be best to use an AlertDialog.