I am performing delete and delete all operations in my app on button click. when I click on delete button item is deleted from list view as well deleted from the server.When I click on delete all list view is not refreshing or updating at the same time.In delete all case server is updated but listview is not updated. I am using notifyDataSetChanged() method.How I can resolve this problem?
public void alertMessage()
{
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
switch (which){
//for cancel button
case DialogInterface.BUTTON_POSITIVE:
Category_Dashboard_Page activity = (Category_Dashboard_Page) context;
activity.swipeCategorylistView.closeAnimate(position);
break;
//for delete
case DialogInterface.BUTTON_NEGATIVE:
Category_Dashboard_Page activity1 = (Category_Dashboard_Page) context;
activity1.swipeCategorylistView.closeAnimate(position);
activity1.categoryList_items_obj.remove(position);
activity1.categoryAdapter.notifyDataSetChanged();
new DeleteList().execute();
break;
//for delete all
case DialogInterface.BUTTON_NEUTRAL:
Category_Dashboard_Page activity2 = (Category_Dashboard_Page) context;
activity2.swipeCategorylistView.closeAnimate(position);
for(int i=0;i<categoryList_items_obj.size();i++)
{
Category_Dashboard_Page.CategoryList_Item category_list_item = categoryList_items_obj.get(i);
System.out.println(category_list_item.getCategory_id());
if(category_list_item.getCategory_id().equalsIgnoreCase("all"))
{
categoryList_items_obj.remove(i);
}
}
// notifyDataSetChanged();
System.out.println(String.valueOf(getCount()));
System.out.println(String.valueOf(categoryList_items_obj.size()));
activity2.categoryAdapter.notifyDataSetChanged();
new DeleteAllList().execute();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure?");
builder.setMessage("You want to delete this article from all categories.")
.setPositiveButton("Cancel ", dialogClickListener)
.setNegativeButton("Delete ", dialogClickListener)
.setNeutralButton("Delete all", dialogClickListener).show();
}
You may want to call notifyDataSetChanged() on the corresponding adapter in onPostExecute() of DeleteList, since you are deleting the elements from the list through Aysnc task. Let me know if this solved your problem. If not, please share some more code of your project.
You need to remove the objects from the adapter also. Try the following code -
public void alertMessage()
{
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
switch (which){
//for cancel button
case DialogInterface.BUTTON_POSITIVE:
Category_Dashboard_Page activity = (Category_Dashboard_Page) context;
activity.swipeCategorylistView.closeAnimate(position);
break;
//for delete
case DialogInterface.BUTTON_NEGATIVE:
Category_Dashboard_Page activity1 = (Category_Dashboard_Page) context;
activity1.swipeCategorylistView.closeAnimate(position);
activity1.categoryList_items_obj.remove(position);
activity1.categoryAdapter.remove(position);
activity1.categoryAdapter.notifyDataSetChanged();
new DeleteList().execute();
break;
//for delete all
case DialogInterface.BUTTON_NEUTRAL:
Category_Dashboard_Page activity2 = (Category_Dashboard_Page) context;
activity2.swipeCategorylistView.closeAnimate(position);
for(int i=0;i<categoryList_items_obj.size();i++)
{
Category_Dashboard_Page.CategoryList_Item category_list_item = categoryList_items_obj.get(i);
System.out.println(category_list_item.getCategory_id());
if(category_list_item.getCategory_id().equalsIgnoreCase("all"))
{
categoryList_items_obj.remove(i);
categoryAdapter.remove(i);
}
}
// notifyDataSetChanged();
System.out.println(String.valueOf(getCount()));
System.out.println(String.valueOf(categoryList_items_obj.size()));
activity2.categoryAdapter.notifyDataSetChanged();
new DeleteAllList().execute();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure?");
builder.setMessage("You want to delete this article from all categories.")
.setPositiveButton("Cancel ", dialogClickListener)
.setNegativeButton("Delete ", dialogClickListener)
.setNeutralButton("Delete all", dialogClickListener).show();
}
Related
For a bit of context, I'm doing a learning app, when the user reach the end of the lesson a dialog shows but when I click the "go back" option to return to the previous fragment (the app is designed with a Navigation object and different fragments) I get the error on the title.
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
switch (view.getId()) {
case R.id.btnL:
if (pagina == 1) {
Toast toast = Toast.makeText(getContext(), "Estás al principio", Toast.LENGTH_SHORT);
toast.show();
} else {
llenarDatos(--pagina, datos);
}
break;
case R.id.btnR:
if (pagina < limite)
llenarDatos(++pagina, datos);
else
showDialog(view);
break;
case R.id.btn_no:
bundle.putBoolean("modo", true);
Navigation.findNavController(view).navigate(R.id.fragment_menu, bundle);
break;
case R.id.btn_yes:
break;
}
}
The case R.id.btn_no is the option with the error.
Dialog code:
private void showDialog(View v) {
dialog = new Dialog(getContext());
dialog.setContentView(R.layout.custom_dialog);
Button btnVolver = dialog.findViewById(R.id.btn_no);
Button btnExamen = dialog.findViewById(R.id.btn_yes);
btnVolver.setOnClickListener(this);
dialog.show();
}
I've read in another post that this happens because the dialog dismiss when pressing the button, so it doesn't exist anymore. How can I solve it?
I am working on a note application whereby a list view displays notes after storing them in internal storage which is controlled from my Utilities class. I just implemented a delete option in a context menu. The delete option works fine to remove each selected list view item. However when i refresh the list activity or add a new note, the deleted notes keeps re-appearing. Am thinking the file needs to be deleted also from the internal storage but am facing problems doing that.
Main Activity
public boolean onContextItemSelected(final MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final Note mLoadedNote = (Note) mListNotes.getAdapter().getItem(info.position);
mLoadedNote.getTitle();
switch (item.getItemId()) {
case R.id.delete:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
.setTitle("Delete " + mLoadedNote.getTitle())
.setMessage("are you sure?")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String mfileName = getIntent().getStringExtra(Utilities.EXTRAS_NOTE_FILENAME);
//my question if(mLoadedNote != null && Utilities.deleteFile(mfileName)) {
ArrayAdapter<Note> arrayAdapter = (ArrayAdapter<Note>) mListNotes.getAdapter();
arrayAdapter.remove(arrayAdapter.getItem(info.position));
arrayAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, mLoadedNote.getTitle() + " is deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "can not delete the note '" + mLoadedNote.getTitle() + "'", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("NO", null); //do nothing on clicking NO button :P
alertDialog.show();
}
return super.onContextItemSelected(item);
}
I'm having problem in storing the intent.putExtra inside the android local database. I am creating a game like 4Pics1Word for my project. It has only 25 levels so I created 25 activities and I randomized it. After solving a particular activity, it will then be removed to the ArrayList of Classes, ArrayList<Class>. Now, I used intent.putExtra("ACTIVITY_LIST", activityList); to store the intent and to pass it to the next activity. My problem is I can't store it on local database. When I exit the game the progress is not saved, it starts again from the first level. Any suggestions? Thank you!
Here's my code in my Main Activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btnStart;
Context context;
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// We are creating a list, which will store the activities that haven't been opened yet
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(first.class);
activityList.add(second.class);
activityList.add(third.class);
activityList.add(fourth.class);
activityList.add(fifth.class);
Random generator = new Random();
int number = generator.nextInt(5) + 1;
Class activity = null;
switch(number) {
case 1:
activity = first.class;
activityList.remove(first.class);
break;
case 2:
activity = second.class;
activityList.remove(second.class);
break;
case 3:
activity = third.class;
activityList.remove(third.class);
break;
case 4:
activity = fourth.class;
activityList.remove(fourth.class);
break;
default:
activity = fifth.class;
activityList.remove(fifth.class);
break;
}
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(activityList); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
startActivity(intent);
}
}
Here's my code in my first activity:
public class first extends AppCompatActivity implements View.OnClickListener{
EditText etAnswer;
Button btnGo;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etAnswer = (EditText) findViewById(R.id.etAnswer);
btnGo = (Button) findViewById(R.id.btnGo);
btnGo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnGo:
String answer = etAnswer.getText().toString();
if(answer.equals("Jose Rizal") || answer.equals("jose rizal") || answer.equals("Rizal") || answer.equals("rizal") ){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("The famous Rizal monument in Luneta was not the work of a Filipino but a Swiss sculptor named Richard Kissling?" +
"\n" +
"\n" +
"Source: http://www.joserizal.ph/ta01.html");
dlgAlert.setTitle("Did you know that ...");
dlgAlert.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
if(activityList.size() == 0) {
Context context = getApplicationContext();
CharSequence last = "Congratulations! You just finished the game! Please wait for the next update!";
int durationFinal = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, last, durationFinal);
toast.show();
} else {
// Now, the random number is generated between 1 and however many
// activities we have remaining
Random generator = new Random();
int number = generator.nextInt(activityList.size()) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// We will open the first remaining activity of the list
activity = activityList.get(0);
// We will now remove that activity from the list
activityList.remove(0);
break;
case 2:
// We will open the second remaining activity of the list
activity = activityList.get(1);
activityList.remove(1);
break;
case 3:
// We will open the third remaining activity of the list
activity = activityList.get(2);
activityList.remove(2);
break;
case 4:
// We will open the fourth remaining activity of the list
activity = activityList.get(3);
activityList.remove(3);
break;
default:
// We will open the fifth remaining activity of the list
activity = activityList.get(4);
activityList.remove(4);
break;
}
// Note: in the above, we might not have 3 remaining activities, for example,
// but it doesn't matter because that case wouldn't be called anyway,
// as we have already decided that the number would be between 1 and the number of
// activities left.
// Starting the activity, and passing on the remaining number of activities
// to the next one that is opened
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}else{
Context context = getApplicationContext();
CharSequence text = "Wrong! Try Again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
}
}
}
Everytime you come to MainActivity , you new an ArrayList and add all the activities rather than get the cache from your local SharedPreferences .
When you finish one game in an Activity , you did not save your progress in cache.
After updating the arrayList,save your arrayList like this :
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(activityList); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
And when you want to read the arrayList saved ,do like this:
String arrayStr = mPrefs.getString("myObject","defValue");
Gson gson = new Gson();
List<Class> array = gson.fromGson(arrayStr,new TypeToken<List<Class>>(){}.getType());
if(array==null){
array = new ArrayList<>();
array.add(...);
}
I have 20 XML layouts. What I want to happen is to show random xml layouts when the button is clicked. I tried and read same problem as mine but i didnt worked.
For example in Level1 class when the user clicked the PositiveButton in the AlertDialog, random XML Layout will be opened (Level 20 or Level 15 not Level 2).
This is code in Level1 class(the same pattern applies for the rest of the classes)
public class Luzon1 extends Activity {
private String [] answers;
private Button answerButton;
private TextView scoreTxt, showClue;
private EditText answerText;
int scoreNew=0;
public Button yes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_luzon1);
}
public void init()
{
//correct answer
answers=new String[]{"Tarlac"};
(R.id.AnswerButton);
answerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkAnswer();
}
});
}
public boolean isCorrect(String answer)
{ return(answer.equalsIgnoreCase(answers[currentQuestion])); }
public void checkAnswer()
{ String answer=answerText.getText().toString();
if(isCorrect(answer))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Congratulations! You will receive P10!");
builder.setMessage("Did you know that Former bla bla bla Did you know that Former bla bla bla Did you know that Former bla bla bla");
builder.setIcon(android.R.drawable.btn_star_big_on);
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String userData=scoreTxt.getText().toString();
int userNumber=Integer.parseInt(userData);
Intent intent=new Intent(Luzon1.this, Luzon2.class);
intent.putExtra("parameter name", userNumber);
startActivity(intent);
Luzon1.this.finish(); System.exit(0);
} });
AlertDialog alert = builder.create();
alert.show(); // Show Alert Dialog
Thank you so much in advance. and any code snippet will be a great help.
Setting the layout from inside onClick()
If you want this code to be in the onClick() method in your previous activity (the one shown above), use the following code:
#Override
protected void onClick(DialogInterface dialog, int which) {
Random generator = new Random();
int number = generator.nextInt(NUMBER_OF_LEVELS) + 1;
Class activity;
switch(number) {
case 1:
activity = LevelOne.class;
break;
case 2:
activity = LevelTwo.class;
break;
case 3:
activity = LevelThree.class;
break;
case 4:
activity = LevelFour.class;
break;
case 5:
activity = LevelFive.class;
break;
...
case 20:
activity = LevelTwenty.class;
break;
}
Intent intent = (getBaseContext(), activity);
startActivity(intent);
}
Try this:
Declare a public static int count = 0 before onCreate..
then, In onClick increment the count by 1(count++)..
Use switch statement like,(Dont forget to reset counter to 0 when count becomes 20)
void onClick(){
count++;
switch(count) {
case 1:
setContentView(R.layout.yourLayout1);
break;
case 2:
setContentView(R.layout.yourLayout2);
break;
case 3:
setContentView(R.layout.yourLayout3);
break;
case 4:
setContentView(R.layout.yourLayout4);
................................
................................
case 20:
setContentView(R.layout.yourLayout20);
break;
}
if(count==20){
count = 0;
}
}
And also instead of incrementing count each time user clicks, you can use Math.random() and assign it to count (Remember to check(use if statement) Math.random() is returning a value which is below or equal to 20..)
Hope it will help you..
I have a method deleteDilaog (it displays dialog with yes and no option. when clicked yes it does something, when clicked no it cancel dialog) and it is called either buy taping a button or on selecting a item in a option menu. Problem is, result is not the same? It works fine when selected from menu but when clicking a button it just displays dialog and no matter what i click,nothing happens?
Button:
private void RemoveAll(){
Button button=(Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteDialog();
}
});
}
Menu Item:
#Override
public boolean onMenuItemSelected(int id, MenuItem item) {
mDeleteId=item.getItemId();
switch(item.getItemId()) {
case INSERT_ID:
addItem();
return true;
case DELETE_ALL_ID:
deleteDialog();
break;
}
return super.onMenuItemSelected(id, item);
}
deleteDialog method:
private void deleteDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage
(CONFIRM_DIALOG_STRING).setCancelable(false).setPositiveButton
(POSITIVE, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int
which) {
switch (mDeleteId) {
case DELETE_ALL_ID:
mDbHelper.removeAllLists();
fillData();
break;
case DELETE_ID:
Cursor c = (Cursor)
getListView().getAdapter().getItem(which);
mDbHelper.removeList
(mItemId);
c.requery();
break;
}
}
}).setNegativeButton(NEGATIVE, new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
A dialog firstly should never be called as you have coded.
Make us of Activity.onCreateDialog to initialise and maintain you dialog lifecycle
Activities provide a facility to manage the creation, saving and restoring of dialogs. Also See onCreateDialog(int), onPrepareDialog(int, Dialog), showDialog(int), and dismissDialog(int).
It looks like the problem is with mDeleteID. It is set in OnMenuItemSelected, but not in button2's onClick listener.
I'm guessing that the switch(mDeleteID) falls through when the button is clicked.
In case of button you're not setting a value to mDeleteId.