Update current activity if my Sqlite DataBase get updated - android

I'm working on updating my activity which should get updated if there is any update in my Sqlite DataBase .
Any way, My DataBase is successfully updated but I have this button that should be disabled if I update his state to True .
My code to update the Button state to True:
public void InsertEtatReject(String etatReject,int id,String userId)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(EtatReject,etatReject);
db.update(TABLE_NAME, values,"userID=? AND id=?",new String[]{userId,Integer.toString(id)});
db.close();
}
My button code :
//Verify if button state is True or False
etat = databaseHelper.getEtatReject(id,username);
if (etat.equals("False"))
{
rejete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
AlertDialog.Builder builder2 = new AlertDialog.Builder(DescriptionList.this);
// Set the dialog title
builder2.setTitle("Pourquoi cette annonce est inconvenable ?")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
})
// Set the action buttons
.setPositiveButton("Envoyer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
final String itemname = (String) items[selectedPosition];
final int finalId = id;
//Update Button state
databaseHelper.InsertEtatReject("True",finalId,username);
if(itemname.equals("Autre"))
{
Toast.makeText(DescriptionList.this, "Autre ", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DescriptionList.this, "Annonce rejetée :" + itemname, Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// removes the dialog from the screen
}
})
.show();
}
});
}
else{
rejete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(DescriptionList.this,"Vous avez déja rejeteé cette annonce",Toast.LENGTH_SHORT).show();
}
});
And to get data From my DataBase I'm using these method :
public String getEtatReject(int id,String userId)
{
SQLiteDatabase db = this.getWritableDatabase();
String etat = null ;
String SelectQuery = "SELECT * FROM "+TABLE_NAME +" WHERE userID=? AND id=?";
Cursor cursor = db.rawQuery(SelectQuery,new String[]{userId,Integer.toString(id)});
try {
if(cursor.moveToFirst())
{
do {
etat = cursor.getString(25);
}
while (cursor.moveToNext());
}
}
finally {
cursor.close();
db.close();
}
return etat;
}

There are many ways to do this, but I would recommend creating some sort of interface that you can pass into your database update method, then have that method call the interface's callback method, like so:
public interface MyButtonCallback {
void updateFromDb(String etat)
}
Add the callback as a parameter in your getEtatReject method, then call it's update method where you would normally return.
public void getEtatReject(int id,String userId, MyButtonCallback callback)
{
SQLiteDatabase db = this.getWritableDatabase();
String etat = null ;
String SelectQuery = "SELECT * FROM "+TABLE_NAME +" WHERE userID=? AND id=?";
Cursor cursor = db.rawQuery(SelectQuery,new String[]{userId,Integer.toString(id)});
try {
if(cursor.moveToFirst())
{
do {
etat = cursor.getString(25);
}
while (cursor.moveToNext());
}
}
finally {
cursor.close();
db.close();
}
callback.updateFromDb(etat);
}
Then implement the MyButtonCallback interface with the logic you already have in your button code.
//Verify if button state is True or False
#Override
public void updateFromDb(String etat)
{
if (etat.equals("False"))
{
rejete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
AlertDialog.Builder builder2 = new AlertDialog.Builder(DescriptionList.this);
// Set the dialog title
builder2.setTitle("Pourquoi cette annonce est inconvenable ?")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
})
// Set the action buttons
.setPositiveButton("Envoyer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
final String itemname = (String) items[selectedPosition];
final int finalId = id;
//Update Button state
databaseHelper.InsertEtatReject("True",finalId,username);
if(itemname.equals("Autre"))
{
Toast.makeText(DescriptionList.this, "Autre ", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DescriptionList.this, "Annonce rejetée :" + itemname, Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// removes the dialog from the screen
}
})
.show();
}
});
}
else{
rejete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(DescriptionList.this,"Vous avez déja rejeteé cette annonce",Toast.LENGTH_SHORT).show();
}
});
}
Make sure that the class that contains this button logic implements MyButtonCallback and when calling getEtatReject just put this as the parameter for MyButtonCallback like so:
getEtatReject (id, userId, this)
Hope this helps!
NOTE: If you could format your code before submitting it to Stack Overflow, that would make it a little bit easier for answerers to quickly solve your problem, getting you your answers faster.
If you are using Android studio the shortcuts to auto format your code are:
Option + Command + L
on macOS
or
Ctrl + Alt + L
on Windows/Linux

Related

How to write Shared preference Code that uses firebase for User authentication?

How do I write Shared-preference Code that is using Firebase for User authentication and the data that is saved by a user is only accessible for them?
My current application Saves a note and displays it which is the main thing needed in my project but when a user logs out and new user logs in he/she can also view the data so the data is not private. My sir suggested to make nodes for users using shared preference but i couldn't find any solutions
HomeActivity:
public class HomeActivity extends AppCompatActivity {
EditText Descriptionholder;
Button Savebtn;
DatabaseReference DatabaseNote;
ListView listViewNotes;
List<PrivateNote> privateNoteList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseNote = FirebaseDatabase.getInstance().getReference("privatenote");
Descriptionholder = findViewById(R.id.description2);
Savebtn = findViewById(R.id.buttonsave);
listViewNotes= findViewById(R.id.listViewPrivate);
privateNoteList = new ArrayList<>();
Savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addnote();
}
});
listViewNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
PrivateNote privateNote = privateNoteList.get(i); //confusion
showUpdateDialog(privateNote.getNoteId(),privateNote.getNoteDescription());
return false;
}
});
}
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.side, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.item1:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(new Intent(this, MainActivity.class)));
Toast.makeText(this, "Logged out ", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStart() {
super.onStart();
DatabaseNote.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
privateNoteList.clear();
for (DataSnapshot privateSnapshot: dataSnapshot.getChildren() ){
PrivateNote privateNote = privateSnapshot.getValue(PrivateNote.class);
privateNoteList.add(privateNote);
}
PrivateList adapter = new PrivateList(HomeActivity.this,privateNoteList);
listViewNotes.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUpdateDialog(final String noteId, String noteDescription){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogview = inflater.inflate(R.layout.update_dialouge,null);
dialogBuilder.setView(dialogview);
final EditText editDescription = dialogview.findViewById(R.id.editDescription);
final Button buttonUpdate = dialogview.findViewById(R.id.buttonUpdate);
final Button buttonDelete = dialogview.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Updating Note: " +noteDescription);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String description = editDescription.getText().toString().trim();
if (TextUtils.isEmpty(description)){
editDescription.setError(" New information required");
return;
}
updatePrivateNote(noteId,description);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePrivateNote(noteId);
}
});
}
private void deletePrivateNote(String noteId) {
DatabaseReference drPrivateNote = FirebaseDatabase.getInstance().getReference("privatenote").child(noteId);
drPrivateNote.removeValue();
Toast.makeText(this, " Note Deleted", Toast.LENGTH_SHORT).show();
}
private boolean updatePrivateNote(String id,String description){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("privatenote").child(id);
PrivateNote privateNote = new PrivateNote(id,description);
databaseReference.setValue(privateNote);
Toast.makeText(this, " Note Updated", Toast.LENGTH_SHORT).show();
return true;
}
private void addnote () {
String description = Descriptionholder.getText().toString().trim();
if (!TextUtils.isEmpty(description)){
//generated unique number for id
String id = DatabaseNote.push().getKey();
PrivateNote pNote = new PrivateNote(id, description);
DatabaseNote.child(id).setValue(pNote); //pNote value added in id
Toast.makeText(this, "Note added", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, " Please Enter a note ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FirebaseAuth.getInstance().signOut();
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Adapter:
public class PrivateList extends ArrayAdapter<PrivateNote> {
private Activity context;
private List<PrivateNote> privateNoteList;
public PrivateList(Activity context, List<PrivateNote> privateNoteList){
super(context, R.layout.list_layout,privateNoteList);
this.context =context;
this.privateNoteList=privateNoteList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout,null,true);
TextView textViewDescription = listViewItem.findViewById(R.id.TextViewDescription);
PrivateNote privateNote = privateNoteList.get(position);
textViewDescription.setText(privateNote.getNoteDescription());
return listViewItem;
}
}
PrivateNote:
public class PrivateNote {
public String noteId;
public String noteDescription;
public PrivateNote(){
}
PrivateNote(String noteId, String noteDescription){
this.noteId = noteId;
this.noteDescription=noteDescription;
}
String getNoteId()
{
return noteId;
}
String getNoteDescription()
{
return noteDescription;
}
}
In Firebase, there are two things,
FirebaseDatabase
FirebaseAuth
Usually, in almost all the apps, user data is stored in the FirebaseDatabase under the key, that is generated while creating a new user in your Firebase app.
So, for example, your database structure will look like this.
-Your_main_database
|____UserId_Of_FirebaseUser
|____stuff_related_to_user
|____More stuff related to user
So, you create a new user in FirebaseAuth, you can find more about it below:
Firebase Custom Auth.
Then, after creating a new user, you create child nodes under your database with the key=userId of your current logged in user.
eg. In your addNote function, the id variable will be equal to
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
Currently, you're using Push keys which are generated based on Timestamp, which you won't be able to associate with user unless you add a key inside your note object which stored current username, and then find all the child nodes that contain that username, but in that case, your data won't be organized at all.
Then, after you create a node with userId under your main database, you can then push new notes created by your user inside the userId with the push() function. So your database structure will look like below.
___
|
|__users
|__uniqueUserId
| |__note1
| |__note2
|__uniqueUserId2
|__note1
|__note2
|__note3
Next time whenever you want to fetch user created notes, you log in the user, get his ID, and then find the notes corresponding to that ID.
I don't see how you can fit SharedPreferences in there, before there is also function to cache data offline in Firebase once it is loaded.
Securing the notes:
If you implement the database like I said above, you'll be very easily able to secure your database.
Common Database Rules.
If you implement everything correctly like I told, you'll be able to secure your database with the fourth set of rules from above rules.
Since you are using firebase authentication, then you can retrieve the userId, and create the following database:
notes
userId
note : "todo"
description : "study"
Then you can do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("notes");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
ref.orderByKey().equalTo(userId).addValueEventListener(new ValueEventListener() {...}
This way you would retrieve the data of the currently logged in user only.

how to pass yes/no value from alertdialog to an Activity in android

i've recently started developing in android and am currently stuck at a point i need to receive values from a dialog box. I have a mainActivity which extends fragmentActivity and an AlertDialog Class.
1)i created a static method showDefalutDialog in AlertDialog class and its being called from mainActivity button click listener with parameters being passed to alertDialog.
2)In showDefalutDialog static method i created .setPositivebutton and .setNegativeButton with a Yes/No DialogInterface respectively.
now here's what i want to do.
1)When yes button on interface is clicked it should return a value to mainActivity
so i can implement it in an if statement to perform a certain function.
moving from windows c# programming doing so isn't a problem but i just don't know how to implement that in android below is relevant code snip
private void sendSms()
{
SharedPreferences pref = getApplicationContext().getSharedPreferences("Sms_MyPref", 0);
mail = pref.getString("email", null); // getting String
tel = pref.getString("receiver_tel", null); // getting String
layout = (LinearLayout)findViewById(R.id.linearLayout1);
from_dateEdit = (EditText) findViewById(R.id.date_edit);
to_dateEdit = (EditText) findViewById(R.id.date_edit_to);
snButton = (Button)findViewById(R.id.form_send_button);
from = (Button)findViewById(R.id.from);
to = (Button)findViewById(R.id.to);
spn = (Spinner)findViewById(R.id.form_spinner);
spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
spinnerV = (String) item;
if(pos == 0)
{
layout.setVisibility( pos == 0 ? View.VISIBLE : View.VISIBLE);
from_dateEdit.setText(DatePickerFragment.getYesteesDate());
from.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker();
}
});
to_dateEdit.setText(DatePickerFragment.getTodaysDate());
to.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker2();
}
});
new1 = null;
new2 = null;
from_dateEdit.setText(new1);
to_dateEdit.setText(new2);
}
else if(pos == 1)
{
layout.setVisibility( pos == 1 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
else if(pos == 2)
{
layout.setVisibility( pos == 2 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
else if(pos == 3)
{
layout.setVisibility( pos == 3 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
snButton.setOnClickListener(new OnClickListener() {
public void onClick(View view)
{
if(new1 == null && new2 == null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date range", false);
}
else if(new1 != null && new2 == null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date TO", false);
}
else if(new1 == null && new2 != null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date FROM", false);
}
else
{
gen = new1.toString()+","+new2.toString();
alert();
//i want to return a value from dialog yes/no click
if(/*dialog yes is clicked*/)
{
sms();
}
else if(/*dialog No is clicked*/)
{
return;
}
}
}
});
}
private void alert()
{
AlertDialogManager.showDefalutDialog(getApplicationContext(), spinnerV, mail, new1,new2);
}
public void sms()
{
String both = "{"+ spinnerV.toString() + ","+gen.toString()+","+ mail.toString()+"}";
sendSMS(tel,both);
}
and showDefaultDialog static method from AlertDialog class
#SuppressLint("InflateParams")
public static void showDefalutDialog(final Context context, String order, final String mail, String fromD, String toD) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle(R.string.finalmsg);
LayoutInflater li = LayoutInflater.from(context);
View view = li.inflate(R.layout.data_summary_view, null);
EditText EMAIL = (EditText)view.findViewById(R.id.Email);
EditText Selectedorder = (EditText)view.findViewById(R.id.order);
EditText Dfrom = (EditText)view.findViewById(R.id.edit_from);
EditText Dto= (EditText)view.findViewById(R.id.edit_to);
LinearLayout ll = (LinearLayout) view.findViewById(R.id.datelayout);
LinearLayout l2 = (LinearLayout) view.findViewById(R.id.datelayout2);
Selectedorder.setText(order);
EMAIL.setText(mail);
if(fromD.toString() != "a" && toD.toString() != "b")
{
ll.setVisibility(View.VISIBLE);
l2.setVisibility(View.VISIBLE);
Dfrom.setText(fromD);
Dto.setText(toD);
}
else if(fromD.toString() == "a" && toD.toString() == "b")
{
ll.setVisibility(View.GONE);
l2.setVisibility(View.GONE);
}
// set dialog message
alertDialogBuilder.setView(view);
//int msdt = data.toString().toCharArray().length;
//Toast.makeText(context, "MsData char count : " + msdt , Toast.LENGTH_SHORT).show();;
alertDialogBuilder
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
try {
Intent main = new Intent(context, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(main);
} catch (Exception e) {
Log.d(TAG, "Error while starting Main activity from Dialog ! ");
}
}
})
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(context,"Your Order will be sent to "+ mail +" please check your inbox for comfirmation." , Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.dismiss();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
You can define you custom interface simmilar to this one:
public interface MyDialogClickListener {
void onPositiveClicked(String value);
}
Then you create instance and pass to method, where you create dialog:
public static void showDeafultDialog(..., MyDialogClickListener listener) {
// ...
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
listener.onPositiveClicked("you can pass yout value here")
}
})
// ...
}
Handle result:
private void sendSms() {
AlertDialogManager.showDeafultDialog(..., new MyDialogClickListener() {
#Override
public void onPositiveClicked(String value) {
// do whatever you want with value
}
});

Passing String values from custom dialog to another activity

A custom dialog is being used to take in user input, and then these values are being passed to another activity using getter methods.
But when I pass the values to a method that outputs the string values to a CSV file, shipName, analystName etc the values appear as empty in the file like this, " " although I have entered the values in the dialog.
I debugged the problem by watching the String values in the debug menu's expression window, shipName and analystName but the values never update in the expression window.
I gather from this that the method i which the input is being passed over is not correct.
Does anyone know why the values being output are empty?
This the dialog class being used:
package ie.gmi.computing;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.renderscript.Sampler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MyMessageDialog {
private Context context;
private EditText shipText, scientistNameText , scientistEmailText , volumeText , colourText ;
private String shipString, scientistNameString , scientistEmailString , volumeString , colourString ;
public AlertDialog displayMessage(Context context, String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
LayoutInflater inflater = LayoutInflater.from(context);
final View v = inflater.inflate(R.layout.custom_view, null);
builder.setView(v);
shipText = (EditText)v.findViewById(R.id.shipNameEditText);
scientistNameText = (EditText)v.findViewById(R.id.scientistEditText);
scientistEmailText = (EditText)v.findViewById(R.id.emailEditText);
volumeText = (EditText)v.findViewById(R.id.volumeEditText);
colourText = (EditText)v.findViewById(R.id.colourEditText);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog= builder.create();
dialog.show();
Button tb = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
tb.setOnClickListener(new CustomListener(dialog));
return dialog;
}
//getter/setters to allow access to string values
//in SearchResult class
public EditText getShipText() {
return shipText;
}
public void setShipText(EditText shipText) {
this.shipText = shipText;
}
public EditText getScientistNameText() {
return scientistNameText;
}
public void setScientistNameText(EditText scientistNameText) {
this.scientistNameText = scientistNameText;
}
public EditText getScientistEmailText() {
return scientistEmailText;
}
public void setScientistEmailText(EditText scientistEmailText) {
this.scientistEmailText = scientistEmailText;
}
public String getShipString() {
return shipString;
}
public void setShipString(String shipString) {
this.shipString = shipString;
}
public String getScientistNameString() {
return scientistNameString;
}
public void setScientistNameString(String scientistNameString) {
this.scientistNameString = scientistNameString;
}
public String getScientistEmailString() {
return scientistEmailString;
}
public void setScientistEmailString(String scientistEmailString) {
this.scientistEmailString = scientistEmailString;
}
public String getVolumeString() {
return volumeString;
}
public void setVolumeString(String volumeString) {
this.volumeString = volumeString;
}
public String getColourString() {
return colourString;
}
public void setColourString(String colourString) {
this.colourString = colourString;
}
public EditText getVolumeText() {
return volumeText;
}
public void setVolumeText(EditText volumeText) {
this.volumeText = volumeText;
}
public EditText getColourText() {
return colourText;
}
public void setColourText(EditText colourText) {
this.colourText = colourText;
}
#SuppressLint("NewApi")
class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
if(shipText.getText().toString().isEmpty() && !shipText.getText().toString().equals(null)){
shipText.setError("The Field is required");
}else if(scientistNameText.getText().toString().isEmpty() && !scientistNameText.getText().toString().equals(null)){
scientistNameText.setError("The Field is required");
}else if(scientistEmailText.getText().toString().isEmpty() && !scientistEmailText.getText().toString().equals(null)){
scientistEmailText.setError("The Field is required");
}else if(volumeText.getText().toString().isEmpty() && !volumeText.getText().toString().equals(null)){
volumeText.setError("The Field is required");
}else if(colourText.getText().toString().isEmpty() && !colourText.getText().toString().equals(null)){
colourText.setError("The Field is required");
}else{
shipText.setError(null);
scientistNameText.setError(null);
scientistEmailText.setError(null);
volumeText.setError(null);
colourText.setError(null);
shipString = shipText.getText().toString();
scientistNameString = scientistNameText.getText().toString();
scientistEmailString = scientistEmailText.getText().toString();
volumeString = volumeText.getText().toString();
colourString = colourText.getText().toString();
Toast.makeText(dialog.getContext(), "The Values you get from : " +
"\n Ship name value: " + shipText.getText().toString() +
"\n Scientist name value: " + scientistNameText.getText().toString() +
"\n email value: " + scientistEmailText.getText().toString() +
"\n sample volume value: " + volumeText.getText().toString() +
"\n sample colour value: " + colourText.getText().toString() , Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
}
}
And this is how I'm retrieving the values in my SearchResult class, when i select the settings button:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
MyMessageDialog dialog =new MyMessageDialog();
dialog.displayMessage(SearchResult.this, "Sample Info", "Required");
// store / use the values here
shipName = dialog.getShipString();
analystName = dialog.getScientistNameString();
analystEmail = dialog.getScientistEmailString();
sampleVolume = dialog.getVolumeString();
sampleColour = dialog.getColourString();
longitudeValue = String.valueOf(lng);
latitudeValue = String.valueOf(lat);
sampleMaterial = message;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Your dialog showing is asynchronous; that is, code execution in onOptionsItemSelected() does not pause after the call to dialog.displayMessage(), so the getters are returning the initial values for those fields, which is null in all cases. You should create an interface that the Activity implements to receive a callback after those fields are set in the onClick() method of your CustomListener, and update the Activity's variables then.
In the dialog class, we create an interface. For example:
public class MyMessageDialog {
public interface DialogCallback {
public void onValuesSet();
}
...
}
Be sure to save a reference to the Context:
public AlertDialog displayMessage(Context context, String title, String message){
this.context = context;
...
}
And at the end of the onClick() method, after the fields' values are set:
((DialogCallback) context).onValuesSet();
The Activity needs to implement the interface we created, the dialog should be a class member, and the fields will be set in the interface's callback method:
public class SearchResult extends Activity
implements MyMessageDialog.DialogCallback {
...
MyMessageDialog dialog;
#Override
public void onValuesSet()
{
shipName = dialog.getShipString();
analystName = dialog.getScientistNameString();
...
}
...
}
Does anyone know why the values being output are empty?
Because all statements from getting data from dialog class is executing after dialog.displayMessage on menu option section.
How to get data from MyMessageDialog on Ok button click ?
1. Instead of getting EditText from MyMessageDialog change all getter/setter method return type to String..
2. Create a event Listener using interface for getting event of Alert close on Ok button click in Activity. you can create event listener as:
Android Custom Event Listener
3. call all setter method on Ok button click of Alert. after calling all setter method call event listener method to execute event in Activity after Alert finish.:
#Override
public void onClick(DialogInterface dialog, int which) {
setShipText(shipText.getText().toString());
setScientistNameText(shipText.getText().toString());
....
//..close alert and call event listener method
}
Your getters don't seem to actually call the getText() method on each EditText view. Modify them do that they do (e.g., scientistNameText.getText()).
PS And, yes, Mike M may indeed write about asyncronicity contributing to the problem. Another approach around that would be to add something like this to the code for each EditText view:
myEditTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
//Set the variable here that you call in your getter. Use `getText()` to get the string (e.g., myGetterVariable = myEditTextView.getText().
}
}

Delete Item from ParseQueryAdapter

I'm a little new to Parse and Android development, so please excuse me if this question is trite or annoying. I've looked all over the Parse forums for a good way to delete items from a ParseQueryAdapter and haven't found anything satisfactory.
What I want is when a user confirms an item to be deleted/added, that item is immediately deleted/added to the ListView and updates the Parse server in the background. Help?
final ParseUser currentUser = ParseUser.getCurrentUser();
final ParseQueryAdapter<ParseObject> mainAdapter =
new ParseQueryAdapter<ParseObject>(this, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery<ParseObject> create() {
// Here we can configure a ParseQuery to our heart's desire.
ParseQuery query = new ParseQuery("todo");
//query.whereEqualTo("user", currentUser);
return query;
}
});
mainAdapter.setTextKey("title");
// Set the ListActivity's adapter to be the PQA
final ListView list = getListView();
list.setAdapter(mainAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final int pos = position;
new AlertDialog.Builder(thisactivity)
.setTitle("Confirmation Dialog")
.setMessage("Do you really want to delete it?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
ParseObject toBeDeleted = mainAdapter.getItem(pos);
toBeDeleted.deleteInBackground();
mainAdapter.loadObjects();
}})
.setNegativeButton(android.R.string.no, null).show();
}
});
final EditText todoName = (EditText)findViewById(R.id.todoName);
Button adder= (Button) findViewById(R.id.addTodo);
adder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTodo(todoName.getText().toString(), currentUser);
todoName.setText("");
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(todoName.getWindowToken(), 0);
mainAdapter.loadObjects();
}
});
Perhaps I can help you with this problem.
The following removal procedure:
private void delItem(Basket object) {
final ParseItems finalitem = object.getParseItem();
ParseQuery<Basket> query = Basket.getQuery();
query.setMaxCacheAge(TimeUnit.SECONDS.toMillis(1));
query.setCachePolicy(ParseQuery.CachePolicy.NETWORK_ELSE_CACHE);
//query.fromLocalDatastore();
query.whereEqualTo("parseItem", finalitem);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.whereNotEqualTo("sent", true);
query.getFirstInBackground(new GetCallback<Basket>() {
#Override
public void done(final Basket basket, ParseException e) {
if (basket != null) {
basket.increment("quantity", -1);
basket.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
SuperToast superToast = new SuperToast(context);
superToast.setDuration(SuperToast.Duration.VERY_SHORT);
superToast.setText("del: " + finalitem.getName() + "-1=" + basket.getQuantity());
superToast.setIcon(R.drawable.del, SuperToast.IconPosition.LEFT);
superToast.show();
}
});
if (basket.getQuantity() <= 0) {
basket.deleteEventually(new DeleteCallback() {
#Override
public void done(ParseException e) {
SuperToast superToast = new SuperToast(context);
superToast.setDuration(SuperToast.Duration.VERY_SHORT);
superToast.setText("remove: " + finalitem.getName());
superToast.setIcon(R.drawable.del, SuperToast.IconPosition.LEFT);
superToast.show();
}
});
}
}
}
});

Using smsmanagaer is not working in alertbox

smsmanager is not working,its not showing any error also,it function is not working at all,dialog dismiss only working.
Mainactivity.java
public class MainActivity extends Activity implements FetchDataListener,OnClickListener
{
private static final int ACTIVITY_CREATE=0;
private ProgressDialog dialog;
ListView lv;
private List items;
private Button btnGetSelected;
//private ProjectsDbAdapter mDbHelper;
//private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
//mDbHelper = new ProjectsDbAdapter(this);
//mDbHelper.open();
//fillData();
//registerForContextMenu(getListView());
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
initView();
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://dry-brushlands-3645.herokuapp.com/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
//mDbHelper.open();
//Cursor projectsCursor = mDbHelper.fetchAllProjects();
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
//String[] from = new String[]{ProjectsDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
//int[] to = new int[]{R.id.text1};
/* Now create a simple cursor adapter and set it to display
SimpleCursorAdapter projects =
new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
setListAdapter(projects);
*/
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
/*dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, ProjectEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data)
{
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
StringBuffer sb = new StringBuffer();
// Retrive Data from list
for (Application bean : items) {
if (bean.isSelected()) {
sb.append(Html.fromHtml(bean.getContent()));
sb.append(",");
}
}
showAlertView(sb.toString().trim());
}
#SuppressWarnings("deprecation")
private void showAlertView(String str) {
AlertDialog alert = new AlertDialog.Builder(this).create();
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
String strContactList = str.substring(0, str.length() - 1);
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//sendSMS();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
dialog.dismiss();
}
});
In my code i am using sms manager for sending sms which are the thing getting from my listview,it has to send sms,but after clicking the ok button,nothing is work, dialog dismiss only working,not sms manager is not working.
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
"phoneNo" in this place specify the number for which you want to send sms
ok what is that selected data does that contain the phone numbers or the some text data that needs to be sent as a message. see "phoneNo" is string what you are passing. In your phone in place of number if you type phoneNo how will it send to which number will it send. that 1st parameter is the phone number to which you want to send sms. if you are selecting the phone number from the list get that to a variable and put that variable in place of "phoneNo"
if you want to enter the number when the alert is shown then here is the code
private void showAlertView(String str) {
final EditText input = new EditText(YOURACTIVITYNAME.this);
AlertDialog alert = new AlertDialog.Builder(YOURACTIVITYNAME.this)
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
String strContactList = str.substring(0, str.length() - 1);
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
String value;
#Override
public void onClick(DialogInterface dialog, int which) {
//sendSMS();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(input.getText().toString(), null, "sms message", null, null);
dialog.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();

Categories

Resources