call method of dialog from other activity - java

i have problem that i cannot call dialog method from another activity, the dialog get user input into sharedprefrnces
here my activity that i want check if theres stored sharedprefernce if not exist i want the dialog appear to get the user input and after i click ok its continue running the main activity
here the main
public class main extends Activity {
private Button button;
private EditText CardNumber;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkid();
}
});
}
public void checkid(){
File f = new File(
"/data/data/com.example.ahmed_samir.enjaz/shared_prefs/MyPrefs.xml");
if (f.exists())
Toast.makeText(OpreatorMobily.this, "exist:", Toast.LENGTH_LONG).show();
else {
NationalId na= new NationalId();
na.dialogmethod();
}
}
}
and here my second activity of dialog
public class NationalId extends Activity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
final Context context = this;
private Button button;
private TextView result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_national_id);
dialogmethod();
// components from main.xml
button = (Button) findViewById(R.id.button1);
result = (TextView) findViewById(R.id.tv1);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// add button listener
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialogmethod();
}
});
}
public void dialogmethod(){
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String n = userInput.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
// edit text
result.setText(userInput.getText());
Toast.makeText(NationalId.this, "saved:" + n, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}

You should not do this. A possible solution is to create a separate class which contains a static method for your dialog.
So in your activity you can call it like this:
Dialog myDialog = CustomDialog.createDialog(this);
myDialog.show();
Inside the static method:
public static Dialog createDialog(Context context) {
Dialog dialog = new Dialog(this);
//do all the initialization stuff
//return the dialog
return dialog;
}

Related

Save items added to scroll view android studios

I have created and been able to label items that have been added to a scroll view. I want to find a way to save and store the items created so that when the user clicks off the page they still remain there.
I wanted to do this through the use of sharedprefs however I am not sure how and where the best place would be to add code. Would appreciate any suggestions.
public class Editscreen extends AppCompatActivity {
// https://codevedanam.blogspot.com/2021/04/dynamic-views-in-android.html
Button add;
AlertDialog dialog;
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editscreen);
add = findViewById(R.id.button7);
layout = findViewById(R.id.container);
buildDialog();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
private void buildDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.dialog,null);
EditText name = view.findViewById(R.id.nameEdit);
name.getText().clear();
builder.setView(view);
builder.setTitle("Enter Quiz name");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
addCard(name.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog = builder.create();
}
private void addCard(String name) {
View view = getLayoutInflater().inflate(R.layout.cardlayout,null);
TextView nameView = view.findViewById(R.id.name);
Button delete = view.findViewById(R.id.deletequiz);
nameView.setText(name);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.removeView(view);
}
});
layout.addView(view);
}
I believe you can add this file to your project and you can call this static functions to save your data to pref. This is the compact way.
public class PrefUtil {
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(context.getPackageName() + "_preferences",Context.MODE_PRIVATE);
}
public static void setStringPref(Context context,String key,String deger){
getPrefs(context).edit().putString(key,deger).apply();
}
public static String getStringPref(Context context,String key){
return getPrefs(context).getString(key,"");
}
public static void setIntPref(Context context,String key,int deger){
getPrefs(context).edit().putInt(key,deger).apply();
}
public static int getIntPref(Context context,String key){
return getPrefs(context).getInt(key, -1);
}
}

Android alert dialog won't open in emulator

I have been trying to debug the issue of an alert dialog not opening on click of an image button when certain options in a spinner are selected.
The below is my MainActivity.java file which includes the relevant code for the alert dialog (left out code for the spinner as this is working as intended), any help would be much appreciated!
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialise Inputs & Fields
this.UnitSelector();
Spinner spinner = (Spinner) findViewById(R.id.options_spinner);
// UI Relationships
ImageButton tapeButton = (ImageButton)findViewById(R.id.imageButton_tape);
Log.d("SpinnerValue", spinner.getSelectedItem().toString());
EditText editText = (EditText) findViewById(R.id.value);
String message = editText.getText().toString();
// Listeners & Actions
tapeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String spinnerValue = spinner.getSelectedItem().toString();
// float messageFloat = Float.parseFloat(message);
Log.d("Button Clicked", spinnerValue);
if (spinnerValue == "Kilogram" || spinnerValue == "Celsius"){
createDialog("Nah mate", "Okay", MainActivity.this);
}
}
});
}
void createDialog( String title, String msg, Context context){
AlertDialog.Builder builder
= new AlertDialog
.Builder(context);
// Set the message show for the Alert time
builder.setMessage(msg);
// Set Alert Title
builder.setTitle(title);
// Set Cancelable false
// for when the user clicks on the outside
// the Dialog Box then it will remain show
builder.setCancelable(true);
builder.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
// Create the Alert dialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
I think you forgot to set the adapter
Spinner spinner = (Spinner) findViewById(R.id.options_spinner);
String[] values = {"Kilogram","Celsius","other"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,values);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
ImageButton tapeButton = (ImageButton)findViewById(R.id.imageButton_tape);
tapeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String spinnerValue = spinner.getSelectedItem().toString();
if (spinnerValue.equals("Kilogram") || spinnerValue.equals("Celsius")){
createDialog("Nah mate", "Okay", MainActivity.this);
}
}
});

Can't receive data from button Listener

I want to make button when I click on it a dialog appears and I read data from that dialog. In the dialog I have only EditText for data. My data is numbers.
Here is my code:
Button mSaveButton = (Button) findViewById(R.id.saveButton);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ReportActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_for_percent , null);
EditText savingsDialog = (EditText) mView.findViewById(R.id.percentEditText);
mBuilder.setView(mView)
.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Context context = getApplicationContext();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = mBuilder.create();
dialog.show();
//if (savingsDialog.getText().toString().length() > 0) { I tried this if, but I receive empty data
SharedPreferences savings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = savings.edit();
editor.putString("percent", savingsDialog.getText().toString());
editor.commit();
updateSavingsView(Integer.parseInt(savingsDialog.getText().toString()));// here I want to put my data in method which update my TextView
//}
}
});
Method(if you need it)
public void updateSavingsView(int savings){
TextView savingsTextView = (TextView) findViewById(R.id.saverTextView);
savingsTextView.setText("Save " + savings + "% per month");
TextView monthlySavings = (TextView) findViewById(R.id.savingsMoney);
if(savings == 0 || Integer.parseInt(income.getText().toString()) == 0 ) {
monthlySavings.setText("0");
}
else{
monthlySavings.setText(Integer.toString((Integer.parseInt(income.getText().toString()) * savings) / 100));
}
So the problem is that when I run program without if statement I have an error java.lang.NumberFormatException: For input string: "" . It is because it reads empty string and want to parse it. Then I add if statement to avoid this problem but it doesn't work.
And my question is. How I can rewrite this listener to avoid these problems and to store correct data?
Put your code inside the positive listener
Button mSaveButton = (Button) findViewById(R.id.saveButton);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ReportActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_for_percent , null);
final EditText savingsDialog = (EditText) mView.findViewById(R.id.percentEditText);
mBuilder.setView(mView)
.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Context context = getApplicationContext();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
SharedPreferences savings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = savings.edit();
editor.putString("percent", savingsDialog.getText().toString());
editor.commit();
updateSavingsView(Integer.parseInt(savingsDialog.getText().toString()));
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
});

How to Pass Value In Activity to Dialog and Display it in Android Studio [duplicate]

This question already has answers here:
passing argument to DialogFragment
(6 answers)
Closed 6 years ago.
Hello i have an Activity that i want to pass values from it to a Dialog and Display That value in a Dialog Textview.
The following is the activity that contains EditText that i want to pass to the Dialog.
p.java.
public class piku_daily extends AppCompatActivity {
private LayoutInflater inflater;
String total = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_piku_daily);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void Onclick(View v){
Button button = (Button)v;
String str = button.getText().toString();
total+=str;
EditText edit = (EditText)findViewById(R.id.piku_weka);
edit.setText(total);
}
public void Onclear(View v){
EditText edit = (EditText)findViewById(R.id.piku_weka);
total="";
edit.setText("");
}
public void Onplay(View v){
Mydialog dialog = new Mydialog();
dialog.show(getFragmentManager(), "Confirmation_Dialog");
}}
The Dialog codes are
public class Mydialog extends DialogFragment {
LayoutInflater inflater;
View v;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState){
inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.pikupop, null);
TextView textview = (TextView) v.findViewById(R.id.piku_value);
textview.setText(""+700);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("Ndio", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("Hapana", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}}
Can i please get an help on how i can do that
Make a static method on you dialog like this :
public static MyDialog myDialog(Value what u need){
MyDialog myDialog = new MyDialog();
return myDialog;
}
After that you can call this method on your activity. It will return with your dialog, and you can use .show on it. On the static method you can save your value.

Button crashes on second click, removeView() exception

When I click the calculate button for the first time it works fine but on the second click after the Result Dialog has been dismissed the app crashes.logcat shows the error The specified child already has a parent. You must call removeView on the child's parent first. What should I do now? and how do I add the removeView?
public class MainActivity extends Activity {
float Remaining,Departure,TotUplift,SG,DiscResult;
int CalUpliftResult;
TextView RemainingTV,DepartureTV,UpliftTV,SGtv,CalcUpliftTV,DiscrepancyTV,resultOne,resultTwo;
EditText RemainingET,DepartureET,TotUpliftET,SGet,CalcUpliftET,DiscrepancyET;
Button calculateButton,okButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupView();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.dialog,null);
resultOne=(TextView)textEntryView.findViewById(R.id.resultOne); //resultone is a textview in xml dialog
resultTwo=(TextView)textEntryView.findViewById(R.id.resultTwo);
alert.setTitle("RESULT");
alert.setIcon(R.drawable.ic_launcher);
alert.setView(textEntryView);
alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(validationET())
{
getETvalue();
evaluation();
CalcUpliftTV.setText(String.valueOf(CalUpliftResult));
DiscrepancyTV.setText(String.valueOf(DiscResult));
resultOne.setText("Calc. Uplift (KG)= "+String.valueOf(CalUpliftResult));
resultTwo.setText("Discrepancy(%)= "+String.valueOf(DiscResult));
alert.show();
}
else
Toast.makeText(getApplicationContext(), "please give all inputs", Toast.LENGTH_SHORT).show();
}
});
}
I fixed it, the alertdialog must be created inside the onclick of the calculate button, so that each time I click it, the dialog gets created all over again thus preventing interference from previous dialog values. here's the corrected code segment:
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(validationET())
{
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
LayoutInflater factory = LayoutInflater.from(context);
final View textEntryView = factory.inflate(R.layout.dialog,null);
resultOne=(TextView)textEntryView.findViewById(R.id.resultOne); //resultone is a textview in xml dialog
resultTwo=(TextView)textEntryView.findViewById(R.id.resultTwo);
alert.setTitle("RESULT");
alert.setIcon(R.drawable.ic_launcher);
alert.setView(textEntryView);
alert.setNeutralButton("OK",null);
getETvalue();
evaluation();
CalcUpliftTV.setText(String.valueOf(CalUpliftResult));
DiscrepancyTV.setText(String.valueOf(DiscResult));
resultOne.setText("Calc. Uplift (KG)= "+String.valueOf(CalUpliftResult));
resultTwo.setText("Discrepancy(%)= "+String.valueOf(DiscResult));
AlertDialog alertD = alert.create();
alertD.show();
}
else
Toast.makeText(getApplicationContext(), "please give all inputs", Toast.LENGTH_SHORT).show();
}
});

Categories

Resources