Get the click result in outer class AlertDialog - java

Good day to All! I'll try to describe my question. It's something in architecture scope...as I believe. So, let's start.
I have an activity where the user can create new player or click list and get the list of already created players. So in activity.java I create DatabaseHelper and SQLiteDatabase and use it for INSERT (if new player) or SELECT (if the player choose the existing one). To fill the list I use ListView and Adapter.
When user click (shortly) on the player name in the list, he get the AlertDialog with question "Do you want to proceed with player XXX?" If NO I simply cancel, if YES I take the name, create intent and start another activity with player name transferred intent.putExtra("name", LoginDialog.selectedName)) to that another activity. That's quite good. But now I want to allow user to delete player. The idea is - after a long click user get AlertDialog with question "Do you really want to delete player XXX?" NO - it's clear - cancel. But how to cope with YES?
Roughly - after YES I have to connect to DB and perform DELETE query. How I tried:
public class DeleteDialog {
AlertDialog.Builder ad;
public static Context context;
public static String selectedName;
public DatabaseHelper mDatabaseHelper;
public SQLiteDatabase mSqLiteDatabase;
public void dialogOfSelectedName(Context context, String selectedName) {
context = this.context;
selectedName = this.selectedName;
ad = new AlertDialog.Builder(context);
ad.setTitle("Удаление игрока");
ad.setMessage("Удалить игрока " + selectedName + "?");
ad.setCancelable(true);
mDatabaseHelper = new DatabaseHelper(context, "mydatabase.db", null, 1);
mDatabaseHelper.getReadableDatabase();
mSqLiteDatabase = mDatabaseHelper.getWritableDatabase();
ad.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mSqLiteDatabase.execSQL("DELETE FROM" + DatabaseHelper.DATABASE_TABLE + " WHERE " + DatabaseHelper.NAME_COLUMN + " LIKE '" + selectedName + "'");
}
});
ad.setPositiveButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = ad.create();
alert.show();
}
}
The problem is selectedName cannot be seen from overridden method onClick but I need it in the query. How to realize it? Or my approach is totally wrong? Please, help with advice.
Thanks!

Make the variable as final. You will be able to access it in the onClick method.
Change
public void dialogOfSelectedName(Context context, String selectedName)
to
public void dialogOfSelectedName(Context context, final String selectedName)

Related

Save text from Alertdialog EditText and show into Recyclerview and save it forever

I want to save text when user put text in edit text and click "ok" and show to recycler view. forever, not just one time.
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setTitle("story name");
final EditText editText = new EditText(getContext());
editText.setHint("Name your story");
final LinearLayout linearLayout1 = new LinearLayout(getContext());
linearLayout1.setPadding(10, 10, 10, 10);
linearLayout1.setOrientation(LinearLayout.VERTICAL);
builder1.setView(linearLayout1);
builder1.setView(editText);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString().trim();
if (TextUtils.isEmpty(text)){
Toast.makeText(getContext(), "Please write story name...", Toast.LENGTH_SHORT).show();
}
else {
// save text
}
}
});
builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder1.create().show();
}
}
});
And Adapter
#Override
public void onBindViewHolder(#NonNull StoryHolder holder, int position) {
String story_name = story.get(position).getStory_name();
String date = story.get(position).getDate();
holder.storyText.setText(story_name);
holder.storyDate.setText(date);
Please teach me how to do this. Good day to you.
As I understand with your question you want to save the text and show all the text in a RecyclerView. Just do two things
Create a database and table using SQLite OR you can use Room Library and save the text value in the database table.
Fetch all the values from the same database table and create an adapter to show the values in RecyclerView.
You can use the following link to understand the basic example of Room Room with RecyclerView

Dealing with userInput from AlertDialog on android Studio

Currently struggling to handle the user input from my AlertDialog box. Everything works fine, but I don't know what to do with the user input in order to save it and access it within another function.
private void promptUser() {
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText promptTitle = new EditText(this);
promptTitle.setHint("Title");
layout.addView(promptTitle);
userPrompt = new AlertDialog.Builder(this);
userPrompt.setView(layout);
userPrompt.setTitle("Enter map information").setView(layout);
userPrompt.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog", "Create button was hit");
Log.i("AlertDialog", "This is the text that was entered:" + promptTitle.getText().toString());
userInputs = promptTitle.getText().toString();
}
});
userPrompt.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog", "Cancel button was hit");
}
});
userPrompt.show();
}
and where I call the function:
public void onMapClick( LatLng point ) {
promptUser()
//Log.d(userInputs.get(0), "COOL");
}
The main error I'm encountering is that after calling my method promptUser(), everything runs but the next several lines of code don't wait for the user to click the PositiveButton. e.g, my Log shows "User inputs: null", since tempString isn't yet available. How can I make my function wait until the user has hit submit before running the next line of code?
Put the call to onMapClick inside the positive button callback.
userPrompt.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
userInputs = promptTitle.getText().toString();
onMapClick();
}
});
It's a bit hard to tell if this is exactly what you want since you haven't provided enough code, but this is what you asked for.

Permanently save intent from other activity (with two values) to listview

I'm trying to save two values from an activity (where the user can put in two different values, one String value and one integer value) in the listview from another activity. In the first activity, it shows a list with a course and the amount of points for that course in one listview, like this:
Course: English
Points: 4
Now, the problem is, everytime I want to put in another value using the add_course_actitivty, it overwrites the previous value. I've looked at different solutions, like with sharedpreferences (Add items to listview from other activity), but this uses only one value and if I try to work with sharedpreferences, it overwrites the other value in the sharedpreferences, but I want users to add multiple courses and corresponding points. Also on restart, it deletes the values in the listview (I read to prevent this you need to store it in sharedpreferences, but this doesn't work the way I need it to be)
KeuzeActivity.class (shows the listview):
public class KeuzeActivity extends AppCompatActivity {
private FloatingActionButton fab_add;
private String student_naam;
private ListView keuze_list;
boolean wantDelete;
private ArrayAdapter adapter;
private String vak;
private int ec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_keuze);
// setting title
student_naam = getIntent().getStringExtra("student");
setTitle("Keuzevakken en projecten van " + student_naam);
//initialzing elements
fab_add = (FloatingActionButton)findViewById(R.id.fab_add);
keuze_list = (ListView) findViewById(R.id.keuze_list);
//initializing list
final ArrayList<Course> courseItems = new ArrayList<Course>();
adapter = new ArrayAdapter<Course>(this, android.R.layout.simple_list_item_1, courseItems);
keuze_list.setAdapter(adapter);
// checks if intent has required values, put it in listview
if (getIntent().hasExtra("vak") && getIntent().hasExtra("ec")) {
vak = getIntent().getStringExtra("vak");
ec = getIntent().getIntExtra("ec", ec);
courseItems.add(new Course(vak, ec));
adapter.notifyDataSetChanged();
}
// make fab go to other activity
fab_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(KeuzeActivity.this, add_course_activity.class));
}
});
// long press deletes item
keuze_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
showDeleteDialog();
if (wantDelete) {
courseItems.remove(position);
adapter.notifyDataSetChanged();
}
return true;
}
});
}
private void showDeleteDialog() {
AlertDialog.Builder infobuilder = new AlertDialog.Builder(this);
infobuilder.setCancelable(false);
infobuilder.setTitle("Vak/project verwijderen");
infobuilder.setMessage("Weet je zeker dat je het vak of project wilt verwijderen?");
final TextView text = new TextView(this);
// action when pressed OK
infobuilder.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
wantDelete = true;
dialog.cancel();
}
});
infobuilder.setNegativeButton("Nee", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
wantDelete = false;
dialog.cancel();
}
});
infobuilder.show();
}
}
add_course_activity.class (let's users input course and points)
public class add_course_activity extends AppCompatActivity {
private EditText course_edit;
private EditText ec_edit;
private Button save_btn;
private String student_name;
private int ec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_course);
setTitle("Voeg vak of project toe");
final Context context = getApplicationContext();
// initializing elements
course_edit = (EditText) findViewById(R.id.edit_vak);
ec_edit = (EditText) findViewById(R.id.edit_ec);
save_btn = (Button) findViewById(R.id.save_button);
// action on savebutton
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (course_edit.getText().toString().trim().length() > 0 && ec_edit.getText().toString().trim().length() > 0 ) {
ec = Integer.parseInt(ec_edit.getText().toString());
Intent goBack = new Intent(add_course_activity.this, KeuzeActivity.class);
goBack.putExtra("vak", course_edit.getText().toString());
goBack.putExtra("ec", ec);
goBack.putExtra("student", PreferenceManager.getDefaultSharedPreferences(context).getString("student_name", student_name));
startActivity(goBack);
}
else {
Toast.makeText(context, "Voer juiste informatie in!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Course.java class (getters and setters + with toString method)
public class Course {
private String vak;
private int ec;
public Course(String vak, int ec) {
this.vak = vak;
this.ec = ec;
}
public String getVak() {
return vak;
}
public void setVak(String vak) {
this.vak = vak;
}
public int getEc() {
return ec;
}
public void setEc(int ec) {
this.ec = ec;
}
#Override
public String toString() {
return ("Vak: " + vak + "\n" + "Punten: " + ec);
}
}
Note that my code isn't clean or done, but to get further I need to fix this problem.
You have several way to do it. As other replies have suggested you can use an SQLLite database and add data to a course table and retrieve data from it.
If you find Db approach to complicated/heavy
You could also use SharedPreferences what you need to do is figure a way to store a string that represent a list of course. It is not the best way to approach it but it will work.
Lets say you choose to serialize your Course object with "vac-ec"
Then you just store a serialized list of course. Example "vac1-ec1,vac2-ec2"
When you need to add a course you juste grab the previous string split it to list, append the new course to the list and re-serialize the list to a string to encode it.
Other solution could be to use Realm.
You should used SQLiteDatabase and create a table with valid attributes and insert your new values into them
Okay, now things are clearer. As answered by #Dwijraj, when storing what potentially will be a large set of data, for maximum control it is best to use SQLite.
You can read more about the different Saving Data methods here:
https://developer.android.com/training/basics/data-storage/index.html
SharedPreferences are best used to store small amounts of information, like storing the settings of an application. [Mute] for example. Or a highscore in case of a game.
A Database is a better option when it comes to storing large pieces of data that you will potentially manipulate.
Your data structure can be something like this, Courses table containing Unique_ID , Course Name, Course Level, Course summary.
A table for English for example which will contain
Exams, Scores, Duration.
There are a lot of things you can do.
Try by storing the records in SQLite, and get it when you want to show.
By this, You can have a track of all added items. And you can show the items you want.

Assign value to variable using popup edit text on android studio

I'm trying to make a popup box with edit text field on Android Studio and would like to store the data entered by the user in a variable used in that class.
Something like this:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name = input.getText().toString(); //<---HERE !want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
This doesn't work, so how could I extract the value of name from my popup window to use it in the main code?
Do it this way:
final String[] name = new String[1];
final EditText input = new EditText(this);
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name[0] = input.getText().toString(); <---HERE! want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
Access it using name[0]
Clarification for the followup question by Jox in the comment below: To access the variable inside onClick it needs to be final. But, you cannot assign a value to a simple final variable. However, you can assign a value to a Array member. Hence, the array and not a string variable. Btw, Andriod Studio will do it for you this way itself, just follow the suggested fixes for erroring-out code.
You should declare the DialogInterface.OnCLickListener inside of your Activity. By either creating a listener and assingning it or having your activity implement the interface. And then you won't need to declare name as final.
The reason you have to declare name as final is because you're anonmously creating an object to listen to the click, which require a contract of anything external being used by this anonymous class must be declared as final.
I would recommend creating a listener in your Activity and then assign it to the setOnClickListener(x)
Try this, it works for me :
public class Activity extends AppCompatActivity implements DialogInterface.OnClickListener {
private EditText input;
private String str = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
input = new EditText(this);
}
public void onClickAlert(View v) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", this)
.setNegativeButton("Cancel", null)
.show();
//variable str still equal to "" here
}
#Override
public void onClick(DialogInterface dialog, int which) {
str = input.getText().toString(); /*<---HERE! want to use this variable*/
//use it here
Log.d("Activity", "User input : " + str);
}
}
Implement the OnClickListener in your Activity and read the value of the text field in the callback fonction.

AlertDialog.Builder cannot be resolved to a type

So I'm trying to build a popup window that displays 3 lines:
-The time
-The incident type
-The location
I then have two buttons, OK (This closes the popup) and Send to Map (This submits an explicit intent to Google Maps and sends the location to it, I have yet to write this code)
For some strange reason, I get an error in Eclipse where it says "AlertDialog.Builder cannot be resolved to a type." I assume I've imported it correctly, as well as cleaned it multiple times. I'm unsure how to proceed. Thank you for your assistance.
import android.R;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
public class AlertDialog
{
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Time: " + SMSReceiver.getTime() + "\nIncident: " +
SMSReceiver.getCallType() + "\nLocation: " + SMSReceiver.getAddress())
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
Its actually not an error, you have by mistake created a class name with AlertDialog which is actually already resides in the android Package. Now when you have created the class with AlertDialog and you are trying to access its Builder method it gives you an error, because your custom class doesnt have that method.
Simple solution for your question is just rename your AlertDialog class to some other class name and your problem will get solve.
Note : there is no other error in your code.
I suggest you to change your class name to any other name for example say MyAlertDialog, then your class code will be like below, ( also you need to change your file name according your public class as rule of Java File naming convention,
public class MyAlertDialog // See change is here
{
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Time: " + SMSReceiver.getTime() + "\nIncident: " +
SMSReceiver.getCallType() + "\nLocation: " + SMSReceiver.getAddress())
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
Because your class name is AlertDialog. In your onCreateDialog() function,
AlertDialog.Builder builder = new AlertDialog.Builder(this);
In this line, thie "AlterDialog" is actually reference to your self defined AlterDialog class. If you change to this, it should be work.
android.app.AlertDialog.Builder builter = new android.app.AlertDialog.Builder(this);

Categories