Saving Data from an android dialog - java

I am attempting to save data from an edit text field within a dialog to an ArrayList. I followed the methods of an answer to a similar question (found here How to store edit text data from an Android dialog?) however my code isn't exactly saving data. From my understanding I should be able to do the following(note it isnt the entire class, only the method in question):
public class StartNewGameActivity extends AppCompatActivity {
private ListView lv;
ArrayList<String> game_players = new ArrayList<String>();
public void addPlayerToGame(View view) {
DialogFragment newFragment = new CreatePlayerDialogFragment(
new CreatePlayerDialogFragment.MyMessageDialogListener(){
#Override
public void onClosed(String name) {
game_players.add(name);
}
});
newFragment.show(getSupportFragmentManager(), "players");
}
While using the following class:
public class CreatePlayerDialogFragment extends DialogFragment {
public interface MyMessageDialogListener {
public void onClosed(String name);
}
public AlertDialog onCreateDialog(final MyMessageDialogListener listener) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder.setView(input);
builder.setMessage(R.string.player_name_dialog)
.setPositiveButton(R.string.player_name_dialog_add, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Add Player
{
if(listener != null) {
listener.onClosed(input.getText().toString());
}
dialog.cancel();
}
}
})
.setNegativeButton(R.string.player_name_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
However with my code I get an error "CreatePlayerDialogFrament() in CreatePlayerDialogFragment cannot be applied to CreatePlayerDialogFrament.MyMessageDialogListener"
Is it possibly because I am trying to do everything in my OnCreate() method? Im not quite sure what the issue is or how to go about solving it.

Related

Calling the same method from different activities

I have searched for an answer to this issue and while there are many similar topics, none of the solutions suit my needs. I have this code in MainActivity and it works there but I need to call the same 'addPlayer' method in another activity.
I have also tried creating a new java class called 'AddPlayer.java' to call in both activities via buttons in each but I can't find a way to call it. Perhaps its in the way I've defined the .java class?
public class AddPlayer extends AppCompatActivity {
public void addPlayer (View view) {
// followed by same content as method in MainActivity - edited to correct contexts
MainActivity code
public class MainActivity extends AppCompatActivity {
public void addPlayer (View view) {
final ParseObject players = new ParseObject("Players");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog.Builder builderInBuilder = new AlertDialog.Builder(this);
final EditText nameInput = new EditText(this);
nameInput.setInputType(InputType.TYPE_CLASS_TEXT);
final EditText nickInput = new EditText(this);
nickInput.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setTitle("New Player Details")
.setMessage("Enter new player name...")
.setIcon(android.R.drawable.gallery_thumb)
.setView(nameInput)
.setPositiveButton("Add Player", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
builderInBuilder.setTitle("New Player Details")
.setMessage("Enter player Nickname...")
.setIcon(android.R.drawable.gallery_thumb)
.setView(nickInput)
.setPositiveButton("Add Nickname", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
players.add("nickname", nickInput.getText().toString());
players.add("username", nameInput.getText().toString());
players.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Player could not be added.\n" + e.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Player added successfully.", Toast.LENGTH_SHORT).show();
}
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Add New Player cancelled.", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Add New Player cancelled.", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.show();
}
I get no errors calling the method in MainActivity, I am just unsure of how best to call this method from 2 activities and the syntax required to call the separate java class - which has the correct package assignment.
I was expecting to be able to use
AddPlayer.addPlayer(); // or something similar
Perhaps the best way is just to have this code in both locations? Seems inefficient though...
create class todo the task and call it
class AddPlayer{
public void player(Context ctx,View view){
//do your work here
}
}
then call that method like this
AddPlayer addp = new AddPlayer ();
addp.player(context,view);
I think the concept is like that, if you don't want to create a new instance to call the method, you can declare the method as static

How to insert data from alertdialog to database

I'm trying to get the text from edt_nominal and input it into my database. but I don't know the code.
this is DonasiDetail.class code :
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(DonasiDetail.this);
alertDialog.setTitle("Melakukan Donasi");
alertDialog.setMessage("Masukan Nominal Donasi: ");
final EditText edt_nominal = new EditText(DonasiDetail.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edt_nominal.setLayoutParams(lp);
alertDialog.setView(edt_nominal); //Menambahkan edittest ke alertdialog
alertDialog.setIcon(R.drawable.ic_handshake);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new Database(getBaseContext()).addToDonasi(new Transaksi(
donasiId,
currentDonasi.getNama(),
edt_nominal.getText().toString()
));
Toast.makeText(DonasiDetail.this, "Data Telah Masuk ke Donasi", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
this is Transaksi.class code:
public class Transaksi {
private String Id_Donasi;
private String Nama_Donasi;
private String Nominal_Donasi;
public Transaksi(String id_Donasi, String nama_Donasi, String nominal_Donasi) {
Id_Donasi = id_Donasi;
Nama_Donasi = nama_Donasi;
Nominal_Donasi = nominal_Donasi;
}
public String getId_Donasi() {
return Id_Donasi;
}
public void setId_Donasi(String id_Donasi) {
Id_Donasi = id_Donasi;
}
public String getNama_Donasi() {
return Nama_Donasi;
}
public void setNama_Donasi(String nama_Donasi) {
Nama_Donasi = nama_Donasi;
}
public String getNominal_Donasi() {
return Nominal_Donasi;
}
public void setNominal_Donasi(String nominal_Donasi) {
Nominal_Donasi = nominal_Donasi;
} }
I want to set data from edt_nominal.getText().toString() to Nominal_Donasi at Transaksi.class
I'm fairly new to Android programming and I am still getting used to it, any help would be greatly appreciated! Thanks
You'll have to learn how to store data in android. Go through this article. Decide which option works for you the best. If you have less data, you can store it in SharedPreferences otherwise go for SQLite database.

Dialog fire non-static methods in main activity

I have a dialog that adds items to a listview, and when an item is added I need to reset the list adapter (because if not things get weird).
I read here that I can create an event listener and listen to it in the main activity. I tried doing so but it gives me errors.
AddMovieDialog.java:
public class AddMovieDialog extends DialogFragment {
private OnFinishListener onFinishListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setView(inflater.inflate(R.layout.add_movie_dialog, null))
.setTitle("Add a movie")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// stuff
if (!movieName.isEmpty()) {
// stuff
if (AddMovieDialog.this.onFinishListener != null)
AddMovieDialog.this.onFinisheListener.finish();
}
}
});
// Create the AlertDialog object and return it
return builder.create();
}
public void setOnFinishListener(OnFinishListener listener) {
this.onFinishListener = listener;
}
public interface OnFinishListener {
void finish();
}
}
In the MainActivity:
AddMovieDialog addMovieDialog = new AddMovieDialog();
addMovieDialog.setOnFinishListener(new OnFinishListener() {
public void finish() {
}
});
But it gives me a compilation error: "The method setOnFinishListener(new OnFinishListener(){}) is undefined for the type AddMovieDialog"
You need to call a method which is non-static using the object. You can't call it using just the class name.
Change to this
AddMovieDialog addMovieDialog = new AddMovieDialog();
addMovieDialog .setOnFinishListener(new OnFinishListener() {
public void finish() {
}
});
Also shouldn't
if (AddMovieDialog.this.onCloseListener != null)
AddMovieDialog.this.onCloseListener.finish();
be
if (AddMovieDialog.this.onFinishListener != null)
AddMovieDialog.this.onFinishListener.finish();
EDIT
Seem your import statement in MainActivity is wrong. It should be something like com.yourpackagename.AddMovieDialog.OnFinishListener

Custom Dialog with game score android

I've got a huge problem. When I had AlertBox everything was OK, but I would change it to custom dialog box with pretty good graphic.
With AlertBox it was displaying the current scores and highscore.
When I changed it to Custom Dialog box it's showing nothing.
CustomDialogClass.java
public class CustomDialogClass extends Dialog
{
public CustomDialogClass(Context context) {
super(context);
// TODO Auto-generated constructor stub
/** It will hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_dialog);
}
}
GameActivity.java (fragments with custom dialog box)
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
surfaceCreated = false;
stopDrawingThread();
}
public void customizeDialog() {
int highest = PrefUtil.getHighestScore(this);
String text = null;
if (currentPoint > highest) {
highest = currentPoint;
PrefUtil.setHighestScore(this, currentPoint);
} else {
}
text = "Current Points: " + currentPoint + "\nThe Best Score: " + highest;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Game Over");
builder.setMessage(text);
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
playSwooshing();
restart();
}
});
builder.setNegativeButton("Exit Game", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(GameActivity.this,Bye.class);
startActivity(intent);
playSwooshing();
finish();
}
});
builder.setCancelable(false);
alertDialog = builder.show();
}
and the other fragment:
private void onGameOver() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isFinishing()) {
soundPool.play(soundIds[SOUND_DIE], 0.5f, 0.5f, 1, 0, 1);
CustomDialogClass customizeDialog = new CustomDialogClass(GameActivity.this);
customizeDialog.show(); }
}
});
}
Where is a problem? Can someone fix it?
Now it's showing only my layout file, without any data.
Thanks!
It's not displaying your data because you're not setting your data. In your middle code fragment where you're creating your dialog using a Builder you're not using your custom dialog, so apparently that code is no longer being called. Likewise in your last fragment where you do create a custom dialog, you're not setting any the data.
See the documentation:
If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.
By default, the custom layout fills the dialog window, but you can still use AlertDialog.Builder methods to add buttons and a title.

alert dialog box having list of item

In my android application, when i click on text view, i want to display an alert dialog box which contain list of items. How is it possible. kindly guide.
i code it as:
cus_name_txt = (TextView)findViewById(R.id.cus_name_txta);
cus_name_txt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Onclick_click1(cus_name_txt);
// TODO Auto-generated method stub
}
});
contact_no_txt = (TextView)findViewById(R.id.contact_no_txta);
attend_by_txtbx = (EditText)findViewById(R.id.attend_by_txt);
attend_by_txtbx.setText(My_Task.attend_by_txt);
ticket_no_txt = (TextView)findViewById(R.id.ticket_no_txta);
task_detail_txt = (TextView)findViewById(R.id.task_detail_txt);
How can i get the alert box of list of items by clicking on textView. Please guide. I'll be thankful to u
If you want to show the progressBar Before loading of the List in alert dialog, then use AsyncTask for that.
e.g.:
private class LoadingTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(String... str) {
String response = "";
// Call Web Service here and return response
response = API.getDealsByCategory(str[0], str[1]);
// e.g.: above is my WebService Function which returns response in string
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("result is: "+result);
new Thread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
}).start();
// SHOW THE ALERT DIALOG HERE.....
}
}
Call AsyncTask as like below :
LoadingTask task = new LoadingTask();
task.execute("YOUR_PARAMETER","YOUR_PARAMETER");
//==============================
Just put below code in the Post Excution of the AsyncTask and you will get what you want.
final CharSequence[] items = {"","50","100","150","200","250","300","350","400","450","500","550","600","650","700","750","800","850","900","1000"};
AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
builder.setTitle("Select Country");
//builder.setI
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(getApplicationContext(), con.get(item).getCountrName(), Toast.LENGTH_SHORT).show();
selectDistanceTV.setText(items[item]);
System.out.println("Item is: "+items[item]);
/*CONTRY_ID = con.get(item).getCountryId();
stateET.requestFocus();*/
}
});
AlertDialog alert = builder.create();
alert.show();
Hope it will help you.
If you need more help on how to use AsyncTask then see here:Vogella
Comment me for any query.
Enjoy Coding... :)
Put following code in onClick of textView:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");
ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
builder.setView(modeList);
final Dialog dialog = builder.create();
dialog.show();
Or
Dialog dialog = new Dialog(**Your Context**);
dialog.setContentView(R.layout.**Your Layout File**);
dialog.show();
In this layout file you can make your layout as per your requirements. When you want to use ListView from your Dialog Layout file then you have to write
ListView listView = (ListView)**dialog**.findViewById(R.id.**Your ListView Id**)
You can pass list of items in an String Array and display it in AlertBox..
For Example:
private void SingleChoice() {
String[] selectFruit = new String[] {"Apple","orange","mango"};
Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Single your Choice");
builder.setItems(selectFruit, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,
selectFruit[which] + " Selected", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
}
});
builder.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
button.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
new AlertDialog.Builder(MainActivity.this)
.setSingleChoiceItems(arrClientName,0, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
name.setText(arrClientName[which]);
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
})
.show();
}
});

Categories

Resources