Can't refresh ListView after AlertDialog has been closed - android

I have a ListView with a button on it. When I click the Button I have a AlertDialog with a EditText on it that pops up. When the users enters data into the EditText on the AlertDialog it goes out and updates a SQLite Database. When the original ListView shows back up it is blank. When I exit the app and return the app the data entered in the AlertDialog shows up. I need the new data to show up after the AlertDialog closes.
package com.wmason.testcreator;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.os.Bundle;
//import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.app.ListActivity;
import android.widget.Button;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
public class MainActivity extends ListActivity {
private DbManagement mdbManager;
private TestProcessor tp;
SimpleCursorAdapter notes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lookup);
mdbManager = new DbManagement(this);
tp = new TestProcessor(this);
mdbManager.open();
fillData();
Button testingCsv =(Button)findViewById(R.id.btnTestCsv);
testingCsv.setOnClickListener(ChokeSlam);
fillData();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
fillData();
}
private OnClickListener ChokeSlam = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AssetManager aM = getAssets();
try{
//This line of code opens the AlertDialog
tp.ProcessInboundStream(aM,"Book1.csv",mdbManager);
fillData();
}
catch(Exception ex){
System.out.println(ex.toString());
}
}
};
protected void onListItemClick(ListView l, View v, int position, long id) {
/*
boolean b;
b=mdbManager.deleteTests(id);
*/
//fillData();
Intent i = new Intent(this,DisplayTests.class);
i.putExtra("ID",Long.toString(id));
startActivity(i);
}
private void fillData(){
Cursor testCursor = mdbManager.fetchAllTests();
startManagingCursor(testCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{DbManagement.Gen_Test_Name};
// 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};
//R.layout.
// Now create a simple cursor adapter and set it to display
notes =
new SimpleCursorAdapter(this, R.layout.testrows, testCursor, from, to);
setListAdapter(notes);
notes.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

They way I figured this out was to use the following method
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
fillData();
}
Basically as soon the AlertDialog closes it fires off this method and it goes out and re-populates the ListView

Try this....
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();

I do something like this in the Activity file where the dialog is required.
AlertDialog dialog = dialogViewer.returnEditDialog();
dialog.show();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
refreshView();
}
});
The OnDismissListener is called every time an ALertDialog fragment is closed.

Related

How to fix setOnItemClickListener inside ListView

I have a ListView which has more rows in it. Inside of rows I have two LinearLayouts (deleteItem and editItem) which has setOnClickListener on them. When I'm trying to click on deleteItem or editItem it works only at the second touch, i don't know why.. I've read some answers on stackoverflow but I couldn't find one answer to fix my problem..
This is the code:
import org.json.JSONArray;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.currencymeeting.adapters.GetAllMyCurrencyListViewAdapter;
import com.currencymeeting.beans.User;
import com.currencymeeting.connectors.DeleteCurrencyConnector;
import com.currencymeeting.connectors.MyCurrencyConnector;
import com.currencymeeting.controllers.MessageDialogController;
import com.currencymeeting.controllers.VariableController;
public class MyCurrencyActivity extends FragmentActivity {
private ListView getAllMyCurrencyListView;
private ProgressDialog dialog;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_currency);
this.dialog = ProgressDialog.show(MyCurrencyActivity.this, MessageDialogController.PROGRESS_DIALOG_TITLE, MessageDialogController.PROGRESS_DIALOG_MESSAGE);
this.getAllMyCurrencyListView = (ListView) findViewById(R.id.getAllMyCurrencyListView);
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
getAllMyCurrencyListView.setOnItemClickListener(
new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
MyCurrencyActivity.this.view = view;
final TextView itemID = (TextView) view.findViewById(R.id.itemID);
final LinearLayout deleteItem = (LinearLayout) view.findViewById(R.id.deleteItem);
final LinearLayout editItem = (LinearLayout) view.findViewById(R.id.editItem);
deleteItem.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(MyCurrencyActivity.this)
.setMessage("Are you sure do you want to delete it?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String vid = itemID.getText().toString();
String userId = ""+VariableController.getInstance().getUser().getId();
new DeleteCurrencyTask().execute(userId, vid);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
);
editItem.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),EditCurrencyActivity.class);
startActivity(intent);
}
}
);
}
}
);
final LinearLayout menu = (LinearLayout) findViewById(R.id.menu);
menu.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuLoggedActivity.class);
startActivity(intent);
}
}
);
}
public void setListAdapter(JSONArray jsonArray){
this.getAllMyCurrencyListView.setAdapter(new GetAllMyCurrencyListViewAdapter(jsonArray,this));
this.dialog.dismiss();
};
private class GetMyCurrencyResults extends AsyncTask<MyCurrencyConnector,Void,JSONArray>{
#Override
protected JSONArray doInBackground(MyCurrencyConnector... params) {
User user = VariableController.getInstance().getUser();
return params[0].getAllResults(user);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
private class DeleteCurrencyTask extends AsyncTask<String,Void,String[]>{
#Override
protected String[] doInBackground(String... params) {
return params;
}
#Override
protected void onPostExecute(String[] result) {
boolean status = new DeleteCurrencyConnector().deleteTransaction(result[0],result[1]);
LinearLayout itemViewId = (LinearLayout) MyCurrencyActivity.this.view.findViewById(R.id.itemViewID);
if(status){
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
} else {
Toast.makeText(MyCurrencyActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
}
Your problem might be caused by the way your program executes. You first thread your adapter initialization, and then your main thread starts attaching onclick listeners before your adapter initialization finishes. This means your listview will have a click listener but not the items in the adapter, and when you click the listview once
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
this fires off in your DeleteCurrencyTask and sets the adapter again. To fix this try putting setOnClick initializaion in the post execute of your
private class GetMyCurrencyResults extends AsyncTask<MyCurrencyConnector,Void,JSONArray>{
I believe I realized why the event of deleteItem and editItem is called only on second click, because deleteItem and editItem clickListeners are atached only when getAllMyCurrencyListView.setOnItemClickListener (when I click on row) is called not when the code is loaded. So I guess I have to find another way to make these events

send email for single email ID without using Intent in android

I am developing an application that has a form to send email without in-built application. I have seen so many examples for email sending. In all the examples, it is for so many email ID. That means we can send email to multiple persons at a time. But I want to send email to one person only. I am following this tutorial. Please let me know where and what should I have to change the code.
http://javapapers.com/android/android-email-app-with-gmail-smtp-using-javamail/
From this tutorial in the ToEmail box, we can add multiple email ID. But I want to add a single email ID only.Please help me where should I change this.This is the code I have edited from this tutorial..plzzz help.
import java.util.Arrays;
import java.util.List;
import javax.security.auth.Subject;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Contact extends Activity implements OnClickListener, OnItemSelectedListener
{
Button submit1,clear;
EditText et1,et2,et3;
Spinner spin;
String[] selction = { "I want to request a mobile feature",
"I want to tell about something that I like",
"I want to tell you about something that I do not like",
"I have general comments",
"I want to contact the office",
"I want to suggest an improvement in the church premise"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
Spinner spin=(Spinner)findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);
#SuppressWarnings({ "unchecked", "rawtypes" })
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,selction);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
//--------------------Submit_Button_Start-----------------------------------------------------------
final Button submit1=(Button)findViewById(R.id.button1);
submit1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.i("SendMailActivity", "Send Button Clicked.");
String fromEmail ="user#gmail.com";
String fromPassword="password";
String toEmails="anything#gmail.com";
//List<String> toEmailList = Arrays.asList(toEmails.split("\\s*,\\s*"));
//Log.i("SendMailActivity", "To List: " + toEmailList);
String emailBody = ((TextView) findViewById(R.id.editText1)).getText().toString();
new SendMailTask(Contact.this).execute(fromEmail,fromPassword, toEmails, emailBody);
}
});
//--------------------Submit_Button_End-----------------------------------------------------------
clear=(Button)findViewById(R.id.button2);
clear.setOnClickListener(this);
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
/*ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.question,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);*/
}
public boolean onCactivity_list_itemreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact, menu);
return true;
}
/*
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
*/
#Override
public void onClick(View v1)
{
if(v1==clear)
{
et1.setText("");
et2.setText("");
et3.setText("");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
/*
new AlertDialog.Builder(Contact1.this)
.setMessage("Your requested has been Accepted\nThank You")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
})
.show();*/
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
It looks like you should just build a list with only one item. Something like:
...
List<String> toEmailList = new ArrayList<String>();
toEmailList.add("anything#gmail.com");
...

How to implement the prev and next button

I want to implement 2 activities , one is a listview with image and text which works well now. The other one is a onClicklistener when I click any ListItem it will start another activity to show more information, with 1 previous button and next button to see the Prev information or next. However there is something wrong with the button. It can only see the previous one and next one once. Which means you can't click the next button twice. Any suggestions will be appreciated .
Here is my main activity code
package com.example.manchesterunited;
import com.example.manchesterunited.R;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
static PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter adapter = new CustomAdapter(this);
setListAdapter(adapter);
}
public void onListItemClick(ListView l,View v, int pos, long id){
int playerId = (int)id;
Toast.makeText(getApplicationContext(),"Selected "+data.getName(pos),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, InfoActivity.class);
intent.putExtra("playerId", playerId);
startActivity(intent);
}
}
And here is the second activity
package com.example.manchesterunited;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class InfoActivity extends Activity {
TextView dobText;
TextView pobText;
TextView internationalText;
Button prevButton;
Button nextButton;
PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
dobText = (TextView)findViewById(R.id.textView1);
pobText = (TextView)findViewById(R.id.textView2);
internationalText = (TextView)findViewById(R.id.textView3);
prevButton = (Button)findViewById(R.id.prev);
nextButton = (Button)findViewById(R.id.next);
Intent intent = getIntent();
final int playerId = intent.getExtras().getInt("playerId");
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId-1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
#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_info, menu);
return true;
}
}
You're not updating the playerID.
You're just getting a new ID.
you should put
int newId = playerId+1;
playerID = newId; //insert this line
so that when you click again,
playerID gets updated.
You are always adding just 1 to player ID which will now point to next item. But as soon as you re-click the button it will have the same player ID that was passed through intent. So again it will add in the same value. Make a new variable which will store the current player ID that is visible and keep on incrementing it then you will be able to browse next and vice versa in the previous case.
You can't increment player ID as it has been declared as final, so you can either make a global variable or put a variable in intent and increment it on button clicks.
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//make newId global then it will work. And keep on updating it when the button is clicked accordingly.
newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
Try this on InfoActivity,
private int playerId;
...
...onCreate(...){
...
playerId = intent.getExtras().getInt("playerId");
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId--;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId++;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
}

OnListItemClick in an activity

In my Android app I have a list of countries that I can add new entries to at any time when the app is running. This list is held in a database. I have tried several different ways of trying to implement an OnListItemClick but I cannot get it to work. Here is my class containing my list:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity
{
private DBManager db;
Cursor cursor;
Button goEdit;
ListView listContent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.initial_activity);
listContent = (ListView)findViewById(R.id.list);
goEdit = (Button)findViewById(R.id.goedit);
//Open database
db = new DBManager(this);
db.openToRead();
cursor = db.queueAll();
String[] from = new String[]{DBManager.KEY_ID, DBManager.KEY_YEAR, DBManager.KEY_CONTENT, DBManager.KEY_DESC};
int[] to = new int[]{R.id.editcountry, R.id.yeartext, R.id.countrytext};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
//go to add/delete screen
goEdit = (Button)findViewById(R.id.goedit);
goEdit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Log.i("Test", "Now moving to the edit activity");
Intent intent = new Intent(MainActivity.this, EditList.class);
startActivity(intent);
}
});
}
//life cycles
protected void onPause()
{
super.onPause();
db.close();
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
finish();
}
}
Here is my class where I can choose to enter new countries into the list:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class EditList extends Activity
{
private DBManager db;
Cursor cursor;
EditText editCountry, editYear, editDesc;
Button add, delete, back;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editCountry = (EditText)findViewById(R.id.editcountry);
editYear = (EditText)findViewById(R.id.edityear);
editDesc = (EditText)findViewById(R.id.editdesc);
add = (Button)findViewById(R.id.add);
delete = (Button)findViewById(R.id.delete);
back = (Button)findViewById(R.id.backmain);
//Open database and fill it with content, then close it
db = new DBManager(this);
db.openToWrite();
cursor = db.queueAll();
add.setOnClickListener(buttonAddOnClickListener);
delete.setOnClickListener(buttonDeleteAllOnClickListener);
//handle switching back to main screen
Log.i("Test", "back to main");
back = (Button)findViewById(R.id.backmain);
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
db.close();
//can't use "finish()" because then the list won't refresh with the new data
Log.i("Test", "Going back to the main screen");
Intent intent = new Intent(EditList.this, MainActivity.class);
startActivity(intent);
}
});
}
//insert new country button
Button.OnClickListener buttonAddOnClickListener = new Button.OnClickListener()
{
#Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(), "Added!", Toast.LENGTH_LONG).show();
int year = Integer.parseInt(editYear.getText().toString());
String country = editCountry.getText().toString();
String desc = editDesc.getText().toString();
db.insert(year, country, desc);
updateList();
//clear text fields after use
editYear.setText(null);
editCountry.setText(null);
editDesc.setText(null);
}
};
//delete all button
Button.OnClickListener buttonDeleteAllOnClickListener = new Button.OnClickListener()
{
#Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(), "Your list has been deleted!", Toast.LENGTH_LONG).show();
db.deleteAll();
updateList();
}
};
private void updateList()
{
cursor.requery();
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
finish();
}
}
I have previously implemented an OnListItemClick in a class where the data was statically held in an array. That class also extended ListActivity, which this one doesn't.
The difference between ListActivity and a standard Activity is that the ListActivity handled the OnItemClickListener interface mapping for you, and just provided an extra callback method. Without ListActivity, you'll need to add that plumbing yourself; i.e.
public class MainActivity extends Activity implements AdapterView.OnItemClickListener
{
...
ListView listContent;
#Override
public void onCreate(Bundle savedInstanceState)
{
...
listContent.setOnItemClickListener(this);
...
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Callback logic here for clicked items
}
...
}
In your MainActivity add
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// a list item is click do whatever you want
}

clicking item on listview android

on my application i want to click the list item and make some changes like deleting or updating the item.but i could not implemented the other codes to my code.so little help will be useful. here is my code
package com.example.todolist;
import java.util.ArrayList;
import java.util.Collection;
import android.os.Bundle;
import android.provider.Contacts;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener,OnKeyListener,OnInitListener {
EditText txtitem;
ListView listitem;
TextToSpeech talker;
ArrayList<String> todolist;
ArrayAdapter<String> arrayadapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtitem = (EditText) findViewById(R.id.txtitem);
listitem = (ListView) findViewById(R.id.listitem);
talker = new TextToSpeech(this, this);
txtitem.setOnKeyListener(this);
todolist = new ArrayList<String>();
arrayadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,todolist);
listitem.setAdapter(arrayadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
MenuItem toAdd = menu.add("AddItem");
MenuItem toDelete = menu.add("DeleteItem");
MenuItem toSave = menu.add("SaveItem");
MenuItem toExit = menu.add("ExitItem");
MenuItem toUpdate = menu.add("UpdateItem");
return true;
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
if(item.getTitle().equals("AddItem")){
todolist.add(txtitem.getText().toString());
arrayadapter.notifyDataSetChanged();
txtitem.setText("");
}
if(item.getTitle().equals("DeleteItem")){
String x = txtitem.getText().toString();
int y = Integer.parseInt(x);
todolist.remove(y-1);
arrayadapter.notifyDataSetChanged();
txtitem.setText("");
}
if(item.getTitle().equals("SaveItem")){
say("Save Complete");
arrayadapter.notifyDataSetChanged();
}
if (item.getTitle().equals("ExitItem")){
talker.speak("Are you sure you want to close this activity?",TextToSpeech.QUEUE_FLUSH,null);
onBackPressed();
}
if(item.getTitle().equals("UpdateItem")){
String x = txtitem.getText().toString();
int y = Integer.parseInt(x);
arrayadapter.notifyDataSetChanged();
txtitem.setText(todolist.get(y-1));
todolist.remove(y-1);
}
return true;
}
public void say(String text2say){
talker.speak(text2say, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onInit(int status) {
}
#Override
public void onDestroy() {
if (talker != null) {
talker.stop();
talker.shutdown();
}
super.onDestroy();
}
}
#Override
public void onBackPressed()
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
runOnUiThread(new Runnable() {
#Override
public void run() {
say("Bye");
}
});
}
})
.setNegativeButton("No", null)
.show();
}
this code takes the list's elemnt number and delete's it.but i want to click and delete or update.son little help will be useful.thank you already
To remove the desired item from the list using the remove() method of your ArrayAdapter.
A possible way to do that would be:
Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);
Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.
arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();
To Add items you can do something like this :
on a click of button take text from edittext and add it as an item on list
/** Reference to the button of the layout main.xml */
Button btn = (Button) findViewById(R.id.btnAdd);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
/** Defining a click event listener for the button "Add" */
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
Read official android docs here 1 and 2 for handling click of menu items ...
What you want to do is set the itemClickListener(). This is done by something like this:
list.setOnItemClickListner(new OnItemClickListener(){
onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Do stuff here.
}
});
From that block, you just need to call your delete statement. Alternatively, you could have your class use the AdapterView.OnItemClickListener interface, and put the routine there, then changing the command to list.setOnItemClickListner(this);

Categories

Resources