Delete Item from ParseQueryAdapter - android

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();
}
});
}
}
}
});

Related

Data fetched from FirebaseDatabase is getting shown in 3 separate AlertDialogs instead of one

I'm fetching some data from FirebaseDatabase and then putting them into an array and then trying to show them in a List which is in a custom AlertDialog.
Here's the code:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
String names[] = l.toArray(new String[0]);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialog.show();
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
}
});
Here's the database structure:
app
-child
-anotherChild
-yetAnotherChild
-inaccessibleChild
-someChild: "value"
-lol: "value"
I can't use valueEventListener() here as I have no access to inaccessibleChild. The inaccessibleChild here is the uid of the other users who followed a particular user. How can I access there uid?
The problem is that data is getting fetched but instead of getting shown in a list in one AlertDialog, it is getting shown one-by-one in 3 separate AlertDialog.
What is going wrong here?
Please let me know.
Firebase transactions are asynchronous so your initial line to add the 3 children happens after you set your listener, therefore your callback is called 3 times. (making 3 dialogs).
Move this line outside of the on click:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
Then when you add the below listener (inside the on click) it should be ok
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Put limit when you are using valueEventListener or addChildEventListener. like this,
int limit = 100;
databaseRef.child("chats").limitToLast(limit).addValueEventListener(listener);
And always remove listener when you've done with your work related to firebase. like this,
databaseRef.child("chats").limitToLast(limit).removeEventListener(listener);
Thanks.
Create and show the AlertDialog before you call .addChildEventListener()
Then use inside addChildEventListener call notifyDatasetChanged() after you downloaded the appropriate data. Do not create the AlertDialog inside the addChildEventListener
You can use Firebase Queries to limit the data that is downloaded by a listener.
query.orderByChild("someChild").limitToLast(1).addChildEventListener(...
#Blundell has the insight of solving your problem. I just want to suggest you a similar approach with addValueEventListener.
The value event listener will fire once for the initial state of the
data, and then again every time the value of that data changes.
You need to move out the firebase query from onClick function. So your query might look like this..
// Declare the variable names as public
private String names[];
private void addFirebaseListener() {
ref = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
ref. userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
names[] = l.toArray(new String[0]);
// Call notifyDataSetChanged each time your array gets updated
adapter.notifyDataSetChanged();
}
#Override public void onCancelled(FirebaseError error) { }
});
}
Now write a function to show the ListView in the AlertDialog
// Declare the adapter as public and initialize it with null
private ArrayAdapter<String> adapter = null;
private void showListInDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
if(adapter == null)
adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
// Now set the adapter
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
Now inside your onCreate function you need to set the Firebase listener first and then set the onClick function like this.
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showListInDialog();
}
});
#Hammad Try this modified code basing on your requirement.
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
AlertDialog alertDialog;
ArrayList<String> l;
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
if(l == null) {
l = new ArrayList<String>();
}
l.add(newD.get("lol").substring(30));
String names[] = new String[l.size()];
for(int length=0; length < l.size(); l++) {
names[length] = l.get(length);
}
if(alertDialog == null) {
alertDialog = new AlertDialog.Builder(Activity.this).create();
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
} ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
if(!alertDialog.isShowing()) {
alertDialog.show();
}
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
}
});
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
/**
Retrieve lists of items or listen for additions to a list of items. This callback is triggered once for each existing child and then again every time a new child is added to the specified path. The DataSnapshot passed to the listener contains the new child's data.
**/
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
ref.addChildEventListener(childEventListener);
Usining ChildEventListener onChildAdded are call per child you have in that node. Means your code runs 3 time so dialog appers 3 time.
This is the problem
So the solution is:
While using a ChildEventListener is the recommended way to read lists of data, there are situations where attaching a ValueEventListener to a list reference is useful.
Attaching a ValueEventListener to a list of data will return the entire list of data as a single DataSnapshot, which you can then loop over to access individual children.
Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
inaccessibleChild.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
//here you can access the each child of that node.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
Well, none of the above answers really helped, though Linxy's answer is correct, I saw it after solving the probelm.
Moving all the code out and writing just this line: alertDialog.show(); inside setOnClickListener() improving my code to this:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
String names[] = l.toArray(new String[0]);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert11.show();
}
});
Anyway, I would like to thank all those who answered this question.
Peace.

ListView is not updating immediately inside Fragment

I have an activity with multiple EditText, after entered data and click button SAVE for save them in Database(Mysql) it open Fragment which have ListView populated with this data from database.
PROBLEM:
ListView isn't showing new data that I have entered in activity!!!, even the new data is added im my ArrayList correctly.
But when I start this Fragment for the second time it shows the Listview with new data correctly.
My Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_liste_symbole_monetaire, container, false);
symbolMonList.clear();
lv = (SwipeMenuListView) rootView.findViewById(R.id.lv_liste_symboleMon);
adapter = new SymbMoneLvAdapter(getActivity());
FloatingActionButton btn = (FloatingActionButton) rootView.findViewById(R.id.btnAjoutAjoutSymboleMon);
btn.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(), AjouterSymbMoneActivity.class);
startActivity(intent);
}
});
deleteItemLv();
getListSymbolMon();
return rootView;
}
public void deleteItemLv(){
SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.GRAY));
// set item width
openItem.setWidth(dp2px(90));
// set item title
openItem.setTitle("Ouvrir");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getActivity());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
deleteItem.setWidth(dp2px(90));
// set a icon
deleteItem.setIcon(R.drawable.ic_delete);
// add to menu
menu.addMenuItem(deleteItem);
}
};
lv.setMenuCreator(creator);
lv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
//Ouvrir item
break;
case 1:
deleteItemDialog(position);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
}
public int dp2px(int dp) {
DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
//Dialog delete item:
public void deleteItemDialog(final int position){
Toast toast = Toast.makeText(getActivity(), "size:"+position, Toast.LENGTH_LONG);
toast.show();
Toast toat = Toast.makeText(getActivity(), "sizeTotal:"+symbolMonList.size(), Toast.LENGTH_LONG);
toat.show();
Toast oast = Toast.makeText(getActivity(), "code:"+symbolMonList.get(position).getCode(), Toast.LENGTH_LONG);
oast.show();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity() );
alertDialogBuilder.setTitle("Supprimer");
alertDialogBuilder.setMessage("Voulez vous supprimer ce symbole monétaire?");
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Code = symbolMonList.get(position).getCode();
Call<Void> api =API.deleteSymboleMon("delete", Code);
api.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
if(response.isSuccessful()){
Toast toast = Toast.makeText(getActivity(), "Symbole Monétaire supprimé", Toast.LENGTH_LONG);
toast.show();
symbolMonList.remove(position);
adapter.notifyDataSetChanged();
}else {
}
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
}
}
)
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
//Get liste des SM
private void getListSymbolMon(){
final ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage("Chargement en cours...");
Call<List<SymbMoneItems>> api =API.getListSymbolMon();
api.enqueue(new Callback<List<SymbMoneItems>>() {
#Override
public void onResponse(Call<List<SymbMoneItems>> call, Response<List<SymbMoneItems>> response) {
if (response.isSuccessful()){
List<SymbMoneItems> List = response.body();
addListSymbolMon(List);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}else{
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
Toast toast = Toast.makeText(getActivity(), "Erreur", Toast.LENGTH_LONG);
toast.show();
}
}
#Override
public void onFailure(Call<List<SymbMoneItems>> call, Throwable t) {
Toast toast = Toast.makeText(getActivity(), "Erreur "+t, Toast.LENGTH_LONG);
toast.show();
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
});
}
public void addListSymbolMon(List<SymbMoneItems> lem){
for (int i=0;i< lem.size();i ++){
SymbMoneItems fac = lem.get(i);
symbolMonList.add(fac);
}
adapter.addAll(symbolMonList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
in my Adapter
public void addAll(ArrayList<SymbMoneItems> result) {
this.listSymb = result;
this.notifyDataSetChanged();
}
Thanks for any help.
Setting data using "=" doesn't actually have any change on dataset for adapter.
Change your addAll() method like below:
public void addAll(ArrayList<SymbMoneItems> result) {
this.listSymb.clear();
this.listSymb.addAll(result);
this.notifyDataSetChanged();
}

Update current activity if my Sqlite DataBase get updated

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

Onitemclicklistener not working as same in search activity as it works in main activity

I have a main activity that displays a list retrived from parse.com( i know that parse.comis being closed and i am in the progress on migrating to my own server)
Now I have everything working in this activity like onitemclick etc,.
But I have another activity i.e. search activity that searches whether a list item searched by user is present in main activity's list
This too works fine but when the search results are shown the user should be able to click on desired results and be directed to singleitem class as they would be if they were in main activity
I am not able to implement this since when i click on search results nothing happens
I tried implemmenting onitemclicklistener for search activity as i did in main activity but no change
My code
aynctask of mainactivity of rhe list inimage and its onitem clicklistener
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new SpotsDialog(InterActivity.this, R.style.Custom);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
codelist = new ArrayList<CodeList>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("_created_at");
query.setLimit(limit);
ob = query.find();
for (ParseObject inter : ob) {
map.setDescription((String) inter.get("subheading"));
map.setIntroduction((String) inter.get("intro"));
codelist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (SwipeMenuListView) findViewById(R.id.inter_layoutListView);
// Pass the results into ListViewAdapter.java
adapter = new FinalAdapter(InterActivity.this,
codelist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemClickListener(InterActivity.this);
dialog.dismiss();
}
#Override
public void onItemClick(AdapterView<?> p1, View view, int position, long p4)
{
ObjectMapper mapper = new ObjectMapper();
CodeList codes = (CodeList) adapter.getItem(position);
try{
Intent intent = new Intent(InterActivity.this, SingleItemView.class);
String jsonString = mapper.writeValueAsString(codes);
intent.putExtra("selected item", jsonString);
intent.putExtra("subheading",
(codelist.get(position).getDescription()));
intent.putExtra("intro",
(codelist.get(position).getIntroduction()));
// Start SingleItemView Class
// startActivity(intent);
startActivityForResult(intent, 1);
}catch(JsonProcessingException e){
//something went w3ong
}
}
search activity
public class SearchActivity extends Activity
implements OnItemClickListener
{
protected EditText searchedittext;
Button searchButton;
List<ParseObject> ob;
#Override
public void onCreate(Bundle savedInstanceState )
{
// TODO: Implement this method
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
searchedittext = (EditText) findViewById(R.id.search_layoutEditText);
final ListView searchedlist = (ListView) findViewById(R.id.searchlist);
searchButton = (Button) findViewById(R.id.searchlayoutbtn);
searchButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String seaechedit = searchedittext.getText().toString();
if(seaechedit.isEmpty()){
AlertDialog.Builder builder = new AlertDialog.Builder(SearchActivity.this);
builder.setMessage("PLEASE ENTER SOME SEARCH QUERY")
.setTitle("EMPTY SEARCH")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else{
setProgressBarIndeterminateVisibility(true);
// InterActivity is the class name in parse database where listview retrives it data from
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
query.whereContains("listheading", seaechedit);
query.orderByAscending("_created_at");
query.setLimit(200);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> p1, ParseException e)
{
setProgressBarIndeterminateVisibility(false);
if(e == null){
ob = p1;
String [] searchHeadings = new String[ob.size()];
int i = 0;
// listheading is the coloumn name in parse database
for(ParseObject heading : ob){ searchHeadings[i] = (String) heading.get("listheading");
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>( SearchActivity.this, android.R.layout.simple_list_item_1, searchHeadings );
searchedlist.setAdapter(adapter);
searchedlist.setOnItemClickListener(this);
}else{
Log.e("searchactivity", e.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(SearchActivity.this);
builder.setMessage(e.getMessage())
.setTitle("Nothing found")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
#Override
public void onItemClick(AdapterView<?> p1, View view, int position, long p4)
{
ObjectMapper mapper = new ObjectMapper();
CodeList codes = (CodeList) adapter.getItem(position);
try{
Intent intent = new Intent(InterActivity.this, SingleItemView.class);
String jsonString = mapper.writeValueAsString(codes);
intent.putExtra("selected item", jsonString);
intent.putExtra("subheading",
(codelist.get(position).getDescription()));
intent.putExtra("intro",
(codelist.get(position).getIntroduction()));
// Start SingleItemView Class
// startActivity(intent);
startActivityForResult(intent, 1);
}catch(JsonProcessingException e){
//something went w3ong
}
}
Found the mistake
Forgot to execute RemoteDataTask in search activity as done in main activit

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
}
});

Categories

Resources