My program opens a DialogFragment class while running in MainActivity.java
I want to be able to click on the "neutral button" of that dialog and open a new activity, SensorDataDisplay.java
I am having trouble finding the right way to reference the Context in my button's onClick.
package com.august.customtisensortagclient;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import java.util.ArrayList;
public class GetInfoDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String thisWhichGetInfoDialog = ((MainActivity)getActivity()).getWhichGetInfoDialog();
final ArrayList<String> thisScannedDevicesArrayList =
((MainActivity)getActivity()).getScannedDevicesArrayList();
final int thisIsInLeftConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInLeftConnectedDeviceDisplay();
final int thisIsInRightConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInRightConnectedDeviceDisplay();
int thisIsInThisConnectedDeviceDisplay = 0;
if (thisWhichGetInfoDialog == "Left") {
thisIsInThisConnectedDeviceDisplay = thisIsInLeftConnectedDeviceDisplay;
} else if (thisWhichGetInfoDialog == "Right")
thisIsInThisConnectedDeviceDisplay = thisIsInRightConnectedDeviceDisplay;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(thisWhichGetInfoDialog + " Sensor Info");
builder.setMessage("MAC Address: " + thisScannedDevicesArrayList.get(thisIsInThisConnectedDeviceDisplay));
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(?????, SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
?????.startActivity(myIntent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
}
DialogFragment has getActivity() and getContext() methods (which it inherits from Fragment), both will work in your case. If you're having trouble accessing these methods from the anonymous class (which shouldn't be the case), you can use the GetInfoDialog.this.getActivity() syntax.
getActivity() returns the Activity the fragment is attached to
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(getActivity(), SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
getActivity().startActivity(myIntent);
}
});
Related
I used an alert dialog box for confirmation of delete, I make a recycler view in which two methods are applied 1.swipe for delete method, 2. menu bar delete method. In swipe method when I swipe the view it removed the list and show alert dialog when clicking no then it replaces not original space but another space that creates a space between them kindly guide me what issue it is?
package com.example.framelayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerClickListener, RecyclerActionClick {
private RecyclerView recyclerView;
private detailAdapt adapt;
private List<detailModel> modelList = new ArrayList<>();
detailModel modelData, swipeData;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
final int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.LEFT) {
swipeData = modelList.get(position);
showDialogBox(position, true);
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_details);
populateList();
}
private void populateList() {
for (int i = 0; i < 10; i++) {
int img = R.drawable.ic_person;
String person = "Person " + i;
String name = "Person Name " + i;
String msg = "Person Last Message " + i;
detailModel model = new detailModel(person, name, msg, img);
modelList.add(model);
}
addRecycle(modelList);
}
private void addRecycle(List<detailModel> modelList) {
adapt = new detailAdapt(this, modelList, this, this);
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setSmoothScrollbarEnabled(true);
recyclerView.setAdapter(adapt);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layout);
ItemTouchHelper helper = new ItemTouchHelper(simpleCallback);
helper.attachToRecyclerView(recyclerView);
}
#Override
public void onDeleteCLick(Object obj, int position) {
showDialogBox(position, false);
}
private void showDialogBox(final int position, final boolean isSwiped) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirmation");
builder.setMessage("Are you sure to delete this Item");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
deleteItem(position);
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (isSwiped) {
modelList.add(position, swipeData);
adapt.notifyItemInserted(position);
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void deleteItem(final int position) {
modelData = modelList.get(position);
modelList.remove(position);
adapt.notifyItemRemoved(position);
Snackbar snackbar = Snackbar.make(recyclerView, "item removed at position " + position, Snackbar.LENGTH_LONG);
snackbar.setAction("undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
modelList.add(position, modelData);
adapt.notifyItemInserted(position);
}
});
snackbar.show();
}
#Override
public void onUndoCLick(Object obj, int position) {
}
#Override
public void onSingleClick(Object obj, int position) {
detailModel model = (detailModel) obj;
Toast.makeText(this, "click at " + position, Toast.LENGTH_SHORT).show();
}
}
Please remove below
modelList.add(position, swipeData);
adapt.notifyItemInserted(position);
from the cancel button of the alert dialog, as you already didn't remove the item yet, so no need to insert it again. instead replace them with notifyItemChanged(position); like below
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (isSwiped) {
adapt.notifyItemChanged(position);
}
}
});
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();
}
Currently, I have a popup dialogue that shows when I press the currency button, this dialogue contains a set of radio buttons that users can select one of them. I'm trying to get the selected radio button's state to be saved when the user pressed "OK". So that when they press the "Currency" button again, the radio button selection was the one the user chose prior to pressing "OK".
Currently, my code is this:
CurrencyChoiceDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;
public class CurrencyChoiceDialog extends DialogFragment {
final CharSequence[] currencies = {"CAD", "USD", "EURO", "POUNDS"};
String selectedCurrency;
public int selectedElement = -1;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstance){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose the default currency").setSingleChoiceItems(currencies, selectedElement, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i){
case 0:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 1:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 2:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 3:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
default:
break;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The chosen currency is: "+ selectedCurrency, Toast.LENGTH_LONG);
}
});
return builder.create();
}
}
Settings.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Settings extends AppCompatActivity implements View.OnClickListener {
Button confirm;
Switch useDefault;
boolean toggle;
private CardView currency;
private CardView tipPercentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
confirm = findViewById(R.id.saveButton);
useDefault = findViewById(R.id.switch1);
currency = findViewById(R.id.currencyButton);
tipPercentage = findViewById(R.id.tipPercentageButton);
confirm.setOnClickListener(this);
currency.setOnClickListener(this);
tipPercentage.setOnClickListener(this);
final SharedPreferences sharedPreferences = getSharedPreferences("Press", 0);
toggle = sharedPreferences.getBoolean("Switch", false);
useDefault.setChecked(toggle);
useDefault.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle = !toggle;
useDefault.setChecked(toggle);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("Switch", toggle);
editor.apply();
}
});
}
#Override
public void onClick(View view) {
Intent i;
switch (view.getId()) {
case R.id.saveButton:
i = new Intent(this, MainActivity.class);
startActivity(i);
break;
// TODO: Save the state once the OK button is clicked for the currency.
case R.id.currencyButton:
setCurrency(view);
break;
// TODO: Finish implementing the changes in the seekbar and reflecting it with the percentage text, and saving that state in the application
case R.id.tipPercentageButton:
showDialog();
break;
default:
break;
}
}
public void setCurrency(View view) {
CurrencyChoiceDialog currencyChoiceDialog = new CurrencyChoiceDialog();
currencyChoiceDialog.show(getSupportFragmentManager(), "CurrencySelection");
}
public void showDialog() {
final Dialog yourDialog = new Dialog(this);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_tippercentage, (ViewGroup) findViewById(R.id.your_dialog_root_element));
Button yourDialogButton = (Button) layout.findViewById(R.id.your_dialog_button);
SeekBar yourDialogSeekBar = (SeekBar) layout.findViewById(R.id.your_dialog_seekbar);
yourDialog.setContentView(layout);
yourDialog.show();
yourDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yourDialog.dismiss();
}
});
}
}
I've tried numerous solutions here but none worked. So any help would be much appreciated. This is my first time trying to make a setting's page for an application. So please make sure your answers are thorough as possible. Thanks in advance.
As I understood the problem, you have to change the variable type of selectedElement from public int to public static int. Furthermore, a quick look to your first listing shows that all switch (i) cases in the function onCreateDialog are applying the same logic, so they are redundant and you can have the same logic by just one case.
Two way to fix this:
Using SharedPreferences: set/get your selectedElement using SharedPreferences
(It will store for long time, after exit from the app also)
OR
Make selectedElement as public static in your in CurrencyChoiceDialog like:
(It will store only when you are on the screen)
public static int selectedElement = -1;
Removed the switch cases and simplified it into one case. As well as had the selectedElement to be static. so it becomes:
public class CurrencyChoiceDialog extends DialogFragment {
final CharSequence[] currencies = {"CAD", "USD", "EURO", "POUNDS"};
String selectedCurrency;
public int selectedElement = -1;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstance){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose the default currency").setSingleChoiceItems(currencies, selectedElement, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
selectedCurrency = (String)currencies[i];
selectedElement = i;
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The chosen currency is: "+ selectedCurrency, Toast.LENGTH_LONG);
}
});
return builder.create();
}
}
The -1 in (int cheched) here is the default selected item index (-1 means do not select any default). use this parameter to set the default selected.
AlertDialog.Builder builder=new AlertDialog.Builder(this);
String[] items={"item1","item2"};
SharedPreferences prefs=getPreferences(MODE_PRIVATE);
// If you open the dialog again, we'll put the previously saved option here..
int checked = prefs.getInt("checked", -1);
builder.setTitle("your Title")
.setCancelable(false)
.setSingleChoiceItems(languages, checked , (dialog, which) -{
if (which==0) {
// if selected first item ~ code..
}else if (which==1){
// if selected second item ~ code..
}
// then put your selected item in Shared Preferences to save it..
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("checked",which);
editor.apply();
})
.setNegativeButton(Cancel,null)
.setPositiveButton(OK, (dialog, which) -> {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
Edit: I've made some updates to this ever since I got responses to this thread. Here's the new thread:
I've been making an Android application where you would save your favorite websites. Here is what I got for the code in the file 'MainActivity.java' so far:
package cory.assignment.favoritewebsitesapp;
import java.util.ArrayList;
import java.util.Collections;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends ListActivity {
private static final String SEARCHES = "searches";
private EditText queryEditText;
private EditText tagEditText;
private SharedPreferences savedSearches;
private ArrayList<String> tags;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queryEditText = (EditText) findViewById(R.id.queryEditText);
tagEditText = (EditText) findViewById(R.id.tagEditText);
savedSearches = getSharedPreferences(SEARCHES, MODE_PRIVATE);
tags = new ArrayList<String>(savedSearches.getAll().keySet());
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, tags);
setListAdapter(adapter);
ImageButton saveButton = (ImageButton) findViewById(R.id.saveButton);
saveButton.setOnClickListener(saveButtonListener);
getListView().setOnItemClickListener(itemClickListener);
getListView().setOnItemLongClickListener(itemLongClickListener);
}
public OnClickListener saveButtonListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
if (queryEditText.getText().length() > 0 && tagEditText.getText().length() > 0)
{
addTaggedSearch(queryEditText.getText().toString(), tagEditText.getText().toString());
queryEditText.setText("");
tagEditText.setText("");
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(tagEditText.getWindowToken(), 0);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.missingMessage);
builder.setPositiveButton(R.string.OK, null);
AlertDialog errorDialog = builder.create();
errorDialog.show();
}
}
};
private void addTaggedSearch(String query, String tag)
{
SharedPreferences.Editor preferencesEditor = savedSearches.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
if (!tags.contains(tags))
{
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
OnItemClickListener itemClickListener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String tag = ((TextView) view).getText().toString();
String urlString = getString(R.string.searchURL) + Uri.encode(savedSearches.getString(tag, ""), "UTF-8");
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));
startActivity(webIntent);
}
};
OnItemLongClickListener itemLongClickListener =
new OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
final String tag = ((TextView) view).getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(getString(R.string.shareEditDeleteTitle, tag));
builder.setItems(R.array.dialog_items, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case 0:
shareSearch(tag);
break;
case 1:
tagEditText.setText(tag);
queryEditText.setText(savedSearches.getString(tag, ""));
break;
case 2:
deleteSearch(tag);
break;
}
}
}
);
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
}
);
builder.create().show();
return true;
}
};
private void shareSearch(String tag)
{
String urlString = getString(R.string.searchURL) + Uri.encode(savedSearches.getString(tag, ""), "UTF-8");
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shareSubject));
shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.shareMessage, urlString));
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, getString(R.string.shareSearch)));
}
private void deleteSearch(final String tag)
{
AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(this);
confirmBuilder.setMessage(getString(R.string.confirmMessage, tag));
confirmBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
}
);
confirmBuilder.setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
tags.remove(tag);
SharedPreferences.Editor preferencesEditor = savedSearches.edit();
preferencesEditor.remove(tag);
preferencesEditor.apply();
adapter.notifyDataSetChanged();
}
}
);
confirmBuilder.create().show();
}
}
However, I have got the errors for the code with certain lines:
Line 79: OK cannot be resolved or is not a field
Line 146: cancel cannot be resolved or is not a field
Line 177: cancel cannot be resolved or is not a field
Line 186: delete cannot be resolved or is not a field
The link below shows what I have for activity_main.xml:
Click here for the image
What could be wrong with those lines? Something isn't right with those lines as they are related to the info on this page.
I am also using the proram Eclipse Java EE IDE for Web Developers to make this as well in case you wanted to know what program I was using. I'm also using API 18 to work on this as well.
If you want to take a look at the other files, then let me know.
I know that some of them are strings that I need to make for the strings.xml file, but would their values have to be messages like "This file is missing", or would they have to be special integers?
They need to be in res/values/strings.xml, yes.
Those values are compiled into "special integers" for you and are accessible by R.string.xxxxx.
I imagine that solves the majority of the errors saying "cannot be resolved or is not a field".
DialogInterference cannot be resolved to a type
Did you mean DialogInterface?
The method deleteSearch(string) from the type MainActivity refers to the missing type string
Look at this line. What is string?
private void deleteSearch(final string tag)
So upon examination, I found out that the other lines did need strings after all despite what it said about certain R.string codes on this page for 'cancel' and 'OK'. So why did 'cancel' and 'OK' need their own strings in strings.xml?
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.