In my app, information like file names are stored in the externally storage. They are then implemented into the app with the help of ListView. I can delete files individually with OnItemLongClickListener() but I want to select multiple files in ListView and then click a Delete button. How can I do this? My MainActivity file is below:
public class MainActivity extends AppCompatActivity {
ArrayList<FileName> filenames;
ListViewAdapter adapter;
ListView lv_filenames;
public Handler handler;
private String _path = Environment.getExternalStorageDirectory() + "/sample_directory/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditorManager manager = new EditorManager(getApplicationContext());
manager.CreateNewDirectory();
lv_filenames = (ListView) findViewById(R.id.list);
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
filenames = manager.GetList();
adapter = new ListViewAdapter(getApplicationContext(), R.layout.listView, filenames);
lv_filenames.setAdapter(adapter);
lv_filenames.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int file_name, long l) {
final File deleteFile = new File(_path + filenames.get(file_name).getName());
final String tempFileName = filenames.get(file_name).getName() + " is deleted";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete File");
builder.setMessage("Do you really want to delete this file?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
boolean deleted = deleteFile.delete();
if (deleted) {
Toast.makeText(getApplicationContext(), tempFileName, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do nothing.
}
});
builder.create();
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
}
}
I deleted the extra code. Thanx for helping!
PS -
I heard that in Android 4.4 + files can't be deleted like this. What should I do?
EDIT -
I have seen those answers. But I want to create a button on whose click the check/uncheck buttons would be available. How can I do that? I want the Check/Uncheck buttons to be visible only when I click delete button. Also the other answers are a bit confusing.
I would have a button with a edit or delete icon and have it change the ListView to one with checkboxes in each view. Either make a new ListView with a new Adapter or just tell adapter and set a boolean in it, and then dataSetChange the Adapter.
I fixed my problem. I use a SparseBooleanAdapter to register the delete options.Then I press delete button to delete them.
Related
In this application, I have a listview and a sqlitedatabase. There is a floating action button which on clicking displays a dialog box containing two edittext one for name and another for number. The problem is that the after clicking on the add option of the dialog box the entry is not shown on the listview. But when the activity is destroyed and onCreate is called again on the activity , the entry is shown.
I tried using adapter.notifyDataSetChanged() but it doesn't work. The code is shown below :
Code
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
Cursor cursor=manager.fetch();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),
R.layout.row_item, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
/*adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();*/
insertData(name.getText().toString(),phone.getText().toString());
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
Some of the statements are commented because I tried to get the desired result but couldn't get it.
There's a couple things here you have to change. Taking a look at this code:
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) && !TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(), "Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
When you click the "Add" button, right away you call adapter.notifyDataSetChanged();. In your case, you are only supposed to call that after you have added items to listView, but you haven't added anything yet.
You insert into your database using manager.insert(name.getText().toString(), phone.getText().toString());, but you don't update listView with your newly added data. You need to insert that data to the database, and then also add that data to listView.
Now you can call adapter.notifyDataSetChanged();.
I would recommend that when you want to insert into your database, create a method which will insert the data, add the new data to the listView, and then tell the adapter to refresh.
Edit
Regarding your recent edit, there's still a few things that need to be taken care of.
You should not have listView.setAdapter(adapter) in the method. You had it right the first time (in onCreate() but before the dialog builder).
You call manager.insert(fname,phnumber);, but still do not add the newly inserted data to listView.
Here's pseudocode for what you should have in your method:
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
// Code to add the data you just inserted into the manager above to `listView`.
adapter.notifyDataSetChanged();
}
Remember, adapter.notifyDataSetChanged(); only updates listView if there's changes to listView, and as of right now you haven't added/deleted/modified listView.
After you insert the entries in your database, you should fetch the data again so that your list has the newest entry. So you can either modify your code to be able to add a data point to the list you are passing to the adapter or refetch the data from the database after insertions and before notifyDatasetChanged().
i have did some changes into the code please try it and let me know if it is helpful or not
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),R.layout.row_item, cursor, from, to, 0);
//adapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
Cursor cursor = manager.fetch();
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}}
Try to use notifyDataSetChanged after insert operation. In all place where you call(try to call) notify manager data isn't change yet.
I am trying to send one item of a list on being long clicked to another activity's list.But the second activity i.e MySchedule doesnt update beyond one item.
Here's My code
Activity from where i am sending the string
(didnt added the code of string)
public class CloudEvents extends AppCompatActivity {
static int scheduleId = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(CloudEvents.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Save Event")
.setMessage("Do you want to save this event into your schedule?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scheduleId++;
Toast.makeText(CloudEvents.this,"Saved",Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CloudEvent",listView.getItemAtPosition(position).toString()).apply();
Intent i = new Intent(CloudEvents.this,MySchedule.class);
startActivity(i);
//myArrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No",null)
.show();
return true;
}
});
Activity Receiving the string and making a list
public class MySchedule extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_schedule);
final ArrayList<String> schedule = new ArrayList<>();
final ListView scheduleListView = (ListView)findViewById(R.id.scheduleListView);
String key = "CloudEvent";
String myEvent ="";
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
if(sharedPreferences.contains(key))
{
myEvent = sharedPreferences.getString(key,"");
schedule.add(CloudEvents.scheduleId,myEvent);
}
final ArrayAdapter myArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,schedule);
scheduleListView.setAdapter(myArrayAdapter);
scheduleListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MySchedule.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure ?")
.setMessage("Do you want to delete this note")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
schedule.remove(position);
myArrayAdapter.notifyDataSetChanged();
CloudEvents.scheduleId--;
}
})
.setNegativeButton("No",null)
.show();
return true;
}
});
}
}
(after adding one item)
Error:Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.add(ArrayList.java:457)
at com.yatin.whatshappeningdtu.MySchedule.onCreate(MySchedule.java:35)
Being racking my brain for hours now.Please Help Thanks !
When you add item first time, your CloudEvents.scheduleId is set to 0 from -1. Suppose your string is "FirstEvent" that you save in CloudEvent key of sharedpreference, and then In MySchedule activity it is added in 0 position of schedule arraylist, and it works fine.
Now when you come back to CloudEvents activity, your CloudEvents.scheduleId is 0 because it's statica variable, and you add another item let's say "SecondEvent", so CloudEvents.scheduleId will change from 0 to 1, and you are saving "SecondEvent" string in CloudEvent key again in sharedpreference, so that previous value "FirstEvent" will override with "SecondEvent" that means in MySchedule activity you will only get "SecondEvent" from sharedpreference, but you are adding this in 1st position of schedule arraylist and 0th position of schedule arraylist will be left null.
Now you are passing this arraylist, with null value in 0th position, in Listview adapter, that's way it is throwing IndexOutOfBoundsException exception.
To solve this issue, you can maintain one ArrayList<String>.In CloudEvents activity make following changes.
private ArrayList<String> eventList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState){
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
Collections.addAll(eventList, prefManager.getString("CloudEvent", "").split(","));
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(CloudEvents.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Save Event")
.setMessage("Do you want to save this event into your schedule?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scheduleId++;
eventList.add(listView.getItemAtPosition(position).toString());
Toast.makeText(CloudEvents.this, "Saved", Toast.LENGTH_LONG).show();
Intent i = new Intent(CloudEvents.this, MySchedule.class);
i.putStringArrayListExtra("EventList", eventList);
startActivity(i);
//myArrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
Now in MySchedule activity make following changes.
public class MySchedule extends AppCompatActivity {
ArrayList<String> schedule = new ArrayList<>();
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_schedule);
sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
schedule = getIntent().getStringArrayListExtra("EventList");
ListView scheduleListView = (ListView)findViewById(R.id.scheduleListView);
final ArrayAdapter myArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,schedule);
scheduleListView.setAdapter(myArrayAdapter);
scheduleListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MySchedule.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure ?")
.setMessage("Do you want to delete this note")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
schedule.remove(position);
myArrayAdapter.notifyDataSetChanged();
String events = "";
for(int i=0; i<schedule.size(); i++){
events = events + schedule.get(i);
if(i != (schedule.size() - 1)){
events = events + ",";
}
}
sharedPreferences.edit().putString("CloudEvent", events).apply();
}
})
.setNegativeButton("No",null)
.show();
return true;
}
});
}
}
Just try commit() instead of apply()
apply() was added in 2.3, it commits without returning a boolean indicating success or failure.
commit() returns true if the save works, false otherwise.
And also please confirm that the instance of shared preference which is used to read the data is same as the instance to which the data is written.
The way my dialog is set up currently, it is supposed to take the values from the EditTexts and save in into a database (a process simplified through Sugar ORM), then place the newly created SubjectInfo object into the RecyclerView. The way the notifyDataSetChanged(); is included gives me errors concerning the Thread (basically no thread is waiting upon the change in the data set). SO, I have two paths as I see it, but I'm still confused as to how each approach would work.
Option 1: Somehow revoke the onCreate() method in the SubjectManagerActivity so that the adapter responds to the new database. (How to revoke an onCreate method?)
Option 2: Create a custom Dialog Fragment Activity. Does this navigate back up to recreate the parent activity?
Please help explain how to make the notifyDataSetChanged(); respond, because once that line is removed, there are no errors, but I can't see the new Subject card until I restart the app.
Here is my code:
public class SubjectManagerActivity extends ActionBarActivity {
public static ArrayList<SubjectInfo> subjectList = new ArrayList<SubjectInfo>();
public static FloatingActionButton fabCreateSubject;
private AlertDialog.Builder build;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject_manager);
RecyclerView recList = (RecyclerView) findViewById(R.id.subject_card_list);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
subjectList = getSubjectInfoArrayList();
SubjectAdapter sa = new SubjectAdapter(subjectList);
recList.setAdapter(sa);
fabCreateSubject = (FloatingActionButton) findViewById(R.id.fab_create_subject);
fabCreateSubject.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
build = new AlertDialog.Builder(SubjectManagerActivity.this);
LayoutInflater inflater = getLayoutInflater();
View alertview = inflater.inflate(R.layout.create_subject_dialog, null);
// Pass null as the parent view because its going in the dialog layout
build.setView(alertview);
final EditText inputSubjectName = (EditText) alertview.findViewById(R.id.dialog_edit_subject_card_name);
final EditText inputSubjectGrade = (EditText) alertview.findViewById(R.id.dialog_edit_subject_card_grade);
build.setTitle("Add Subject")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String enteredSubjectName = inputSubjectName.getText().toString();
boolean enteredSubjectIsArchived = false;
if((!(inputSubjectName.getText().toString().equals("")))) {
SubjectInfo si = new SubjectInfo(enteredSubjectName, enteredSubjectIsArchived);
si.save();
}
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
}
});
}
public ArrayList<SubjectInfo> getSubjectInfoArrayList(){
ArrayList<SubjectInfo> sial= new ArrayList<SubjectInfo>();
List<SubjectInfo> sil = SubjectInfo.listAll(SubjectInfo.class);
sial.addAll(sil);
notifyDataSetChanged;
return sial;
}
It turns out often the most effective way to deal with an issue is to trust in your code and research to make it work! For anyone else with a similar issue, I included this code:
si.save();
subjectList.add(si);
sa.notifyDataSetChanged();
The method notifyDataSetChanged(); had to be directed to an adapter, which is the container of the Thread. Though the adapter isn't being populated from the getSubjectInfoArrayList() method in real-time (when the dialog is prompted), the ArrayList is still acquiring the same value and when the app is reopened, it can populate the adapter from the database (and in turn, the same get( ) method).
I am trying to create a pop-up dialog to allow the user of my android app to add a new field to a list on their main page.
I've done a bit of research and found the Dialog/alertDialog option, but i haven't been able to get it working correctly.
Here is my MainActivity class:
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
//final Dialog dialog = new Dialog(this); //!!! ERROR HERE !!! //
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
Button AddNewStudent = (Button) findViewById(R.id.AddNew);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
//db.addStudentProfile(new StudentProfile("Shannon", "White"));
//db.addStudentProfile(new StudentProfile(1,"Shannon", "White", "WhitehousePS", "30", "21" ));
/*AddNewStudent.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Using an alertDialog to get the user to enter in a new Student
dialog.setContentView(R.layout.add_new_student);
dialog.setTitle("Add a new student");
final EditText firstName=(EditText)dialog.findViewById(R.id.firstName);
final EditText surname=(EditText)dialog.findViewById(R.id.surname);
final EditText school=(EditText)dialog.findViewById(R.id.school);
final EditText age=(EditText)dialog.findViewById(R.id.age);
Button save=(Button)dialog.findViewById(R.id.save);
Button btnCancel=(Button)dialog.findViewById(R.id.cancel);
dialog.show();
}
});*/
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<StudentProfile> contacts = db.getAllStudents();
for (StudentProfile studProf : contacts) {
String log = "Id: "+studProf.getID()+" , First name: " + studProf.getFirstName() + ", Surname: " + studProf.getSurname() + ", School: " + studProf.getSchool() +
", Reading Level: "+ studProf.getReadingLevel() + ", Age: " + studProf.getAge();
// Writing Contacts to log
Log.d("Name: ", log);
}
db.getAllStudents();
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
It's linked to a very simple xml page that just has editible text fields.
My application won't even open with this code - i have tracked the issue down to this line:
final Dialog dialog = new Dialog(this);
at the top of my program.
IS this the best way to go about making a pop up dialog?
Also, what is the easiest way to pass the information back to the class to be stored in a database?
Any help would be much appreciated, thanks! :)
You can create some private variables at the top of your class, and get the text from the editText and put it into those variables in the dialog's button click handler method (where you have the 'sign in the user' comment.)
Sometimes it's also easyer to crate a dialog themed activity.
this question is is similar to this
* Android - Listview delete item and Refresh
and this (the same , but I added the full code here to check if I have any problems in my code):
please give me code example. . .
can i call an intent to refresh my list ?
I cant refresh my adapter with :
adapter.notifyDataSetChanged();
I tried:
adapter.remove(adapter.getItem(pos));
but without success, just one time (weird...).
there is another answer there:
Call that Activity once again Using Intent
sombody can give me the exact code for this (or for the adapter/cursor) ?
I am trying this for a couple of hours without success.
my full code:
protected void onCreate (Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.personalmessageview);
headtitle= getIntent().getExtras().getString("head");
setTitle(headtitle);
personalresults = getIntent().getExtras().getStringArrayList("personalres");
personalresultswithtime = getIntent().getExtras().getStringArrayList("personalrestime");
// setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,personalresults));
ListView list = (ListView)findViewById(R.id.listview_personal);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, personalresults);
list.setAdapter(adapter);
registerForContextMenu(list);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
String time = personalresultswithtime.get(pos).toString();
Show_Alert_box(v.getContext(),"Please select action.",time,pos);
return true;
}
});
public void Show_Alert_box(Context context, String message,String time,int position)
final String timestamp = time;
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(getString(R.string.app_name));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try
{
db = databaseHelper.getWritableDatabase();
db.delete("messages","timestamp" + "=?", new String[] { timestamp });
Log.d("DB"," delete! ");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PersonalMessageView.this, android.R.layout.simple_list_item_1, personalresults);
adapter.remove(adapter.getItem(pos)); //not working t all! why ?
list.notify();
list.invalidate();
personalresults.remove(pos);
personalresultswithtime.remove(pos);
adapter.notifyDataSetChanged();
db.close();
}
catch(Exception e)
{
}
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
} });
alertDialog.setMessage(message);
alertDialog.show();
}
Inside your onClick of Dialog, you are dealing with an entirely new Adapter.There is no accociation of adapter(inside onClick()) to the listView Either you should say list.setAdapter(adapter); inside the onClick() method or make the adapter global.
instead of using
adapter.remove(adapter.getItem(pos));
use
string str=list.getItemAtPosition(index).toString();
personalresults.remove(str);
adapter.notifyDataSetChanged();