send email for single email ID without using Intent in android - 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");
...

Related

Test if a user has selected an item from AutoCompleteTextView

My problem is that my code does not react accordingly whenever an user selects an item from an AutoCompleteTextView.
flag is a variable which is set to a value whenever one item from each AutoCompleteTextView has been selected. If it's set to 1, then it means it's right and it should proceed to main activity. Otherwise, a toast is displayed on click of button whose onClick calls the method callMainActivity.
There are no errors. Gradle build is successful, but clicking on that button (mentioned above) does nothing at all.
Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class Location extends AppCompatActivity {
private static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
int city = android.R.layout.simple_dropdown_item_1line;
int area = android.R.layout.simple_dropdown_item_1line;
int store = android.R.layout.simple_dropdown_item_1line;
String []city_array = getResources().getStringArray(R.array.City);
String []area_array= getResources().getStringArray(R.array.Area);
String []store_array= getResources().getStringArray(R.array.Store);
List<String> city_list= Arrays.asList(city_array);
List<String> area_list= Arrays.asList(area_array);
List<String> store_list= Arrays.asList(store_array);
ArrayAdapter<String> adapter_city = new ArrayAdapter(this,city, city_list);
ArrayAdapter<String> adapter_area = new ArrayAdapter(this, area, area_list);
ArrayAdapter<String> adapter_store = new ArrayAdapter(this, store, store_list);
final AutoCompleteTextView autocompleteView_city =
(AutoCompleteTextView) findViewById(R.id.City);
final AutoCompleteTextView autocompleteView_area =
(AutoCompleteTextView) findViewById(R.id.Area);
final AutoCompleteTextView autocompleteView_store =
(AutoCompleteTextView) findViewById(R.id.Store);
autocompleteView_area.setAdapter(adapter_area);
autocompleteView_city.setAdapter(adapter_city);
autocompleteView_store.setAdapter(adapter_store);
autocompleteView_area.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_area.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_city.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_city.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_store.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
//This is the newly updated part
autocompleteView_area.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
//... your stuff
if(autocompleteView_area.getListSelection()>0) {
flag = 1;
System.out.println(flag + "flag at area");
}else
flag=0;
}
});
}
public void callMainActivity(View view){
if(flag==1) {
Intent in = new Intent(getBaseContext(), MainActivity.class);
startActivity(in);
}
else
Toast.makeText(getBaseContext(),"Please select all fields properly",Toast.LENGTH_LONG);
}
}
The reason you are not seeing the Toast or changing activities, is because you are never calling callMainActivity(View view) in your code. Add this line to the end of all your OnClickListeners: callMainActivity(arg0) -- if this does not work, put some log statements in your OnClickListeners to check if they are triggering or not.
Also, if you want to trigger the call when an item from your AutoCompleteTextView result list is selected, you should use an AdapterView.OnItemClickedListener instead. This will notify you when an item is selected from the AutoCompleteTextView list, or when nothing is selected and then you can react accordingly.

In android, How can i display selected data from databse in list view??? i am using sqlite database

I am developing one android application.i want to display a data which is selected from database and display it in listview.first of all i had used static data for display Trainee(user) data. which is static. then after For same functionality i have use sqlite Database and register the Trainee(user) and now i want to display registered trainne's name in listview. i have just done below code. can anyone help me how to display trainee names in listview.
AddTraineeActivity.java
This file works basic function of create trainee database and insert values of trainee:
package com.example.gymapp;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTraineeActivity extends Activity implements OnClickListener
{
EditText fn;
EditText ln;
EditText un;
EditText pwd;
EditText pno;
EditText age;
Button btnAdd;
SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managetrainee);
fn = (EditText) findViewById(R.id.etfirstname);
ln = (EditText) findViewById(R.id.etlastname);
age = (EditText) findViewById(R.id.edage);
pno = (EditText) findViewById(R.id.etphoneno);
un = (EditText) findViewById(R.id.ettraineeun);
pwd = (EditText) findViewById(R.id.etpwdtrainee);
btnAdd = (Button) findViewById(R.id.btnsavedata);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("create table if not exists trainee(firstname text, lastname text,age varchar,phoneNumber varchar,userTrainee varchar,passwordTrainee varchar)");
btnAdd.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v== btnAdd)
{
String firstname = fn.getText().toString();
String lastname = ln.getText().toString();
String Age = age.getText().toString();
String phoneNumber = pno.getText().toString();
String usernameTrainee = un.getText().toString();
String passwordTrainee = pwd.getText().toString();
if(firstname==null||firstname==""||firstname.length()<3)
{
show("Please Enter Correct Name.");
}
else if(lastname==null||lastname==""||lastname.length()<2)
{
show("Please Enter Correct Name.");
}
else if(Age==null||Age==""||Age.length()>3)
{
show("Please Enter Correct Age.");
}
else if(phoneNumber==null||phoneNumber==""||phoneNumber.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(usernameTrainee==null||usernameTrainee==""||usernameTrainee.length()<4)
{
show("Please Enter valid User name.");
}
else if(passwordTrainee==null||passwordTrainee==""||passwordTrainee.length()<6)
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into trainee values('"+firstname+"','"+lastname+"','"+Age+"','"+phoneNumber+"','"+usernameTrainee+"','"+passwordTrainee+"')");
//i=new Intent(this,Welcome.class);
//startActivityForResult(i, 500);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
}
}
}`
UserListActivity.java
This file contain the code which display the trainee names in listview. but this file display static users for example,trainee1,trainee2,trainee3....trainee13.
package com.example.gymapp;
import com.tss.constant.Constant;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import com.example.gymapp.AddTraineeActivity;
import com.example.gymapp.dao.DBfitguidehelper;
public class UserListActivity extends Activity {
private ListView listViewUser;
private String loggedInType ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(DBfitguidehelper.)
listViewUser = (ListView)findViewById(R.id.listViewUser);
String[] values = new String[]{"trainee", "trainee1", "trainee2", "trainee3", "trainee4", "trainee5", "trainee6", "trainee7", "trainee8", "trainee9", "trainee10", "trainee11", "trainee12", "trainee13"};
ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listViewUser.setAdapter(userAdapter);
listViewUser.setOnItemClickListener(new ListViewListner());
if(savedInstanceState!=null){
Bundle extras = getIntent().getExtras();
loggedInType = extras.getString("loggedInType");
System.out.println("loggedInType - " + loggedInType);
}
}
private class ListViewListner implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected user is " + listViewUser.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
Constant.Selected_Trainee = ""+listViewUser.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(),TrainerActivity.class);
intent.putExtra("loggedInType", loggedInType);
Toast.makeText(getApplicationContext(), "loggedInType"+loggedInType, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
now i want to display name of trainees which is stored in database. can anyone help me??
If you want to see how a Cursor loader can work for you, you can review the following project that I have uploaded to github: GPS Distance Tracking

Can't refresh ListView after AlertDialog has been closed

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.

Cannot be resolved to type...Adding search feature to widget

In my widget, I have a listview that collects all of the user's installed applications in a sliding drawer. I want to add a search feature to make it easier for the user to just search for an installed application in the list so I am following the tutorial here. I have already created my listview as defined here:
package com.example.awesomefilebuilderwidget;
import java.util.List;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.widget.Toast;
public class Utilities {
/*
* Get all installed application on mobile and return a list
* #param c Context of application
* #return list of installed applications
*/
public static List getInstalledApplication(Context c) {
return c.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
}
/*
* Launch an application
* #param c Context of application
* #param pm the related package manager of the context
* #param pkgName Name of the package to run
*/
public static boolean launchApp(Context c, PackageManager pm, String pkgName) {
// query the intent for lauching
Intent intent = pm.getLaunchIntentForPackage(pkgName);
// if intent is available
if(intent != null) {
try {
// launch application
c.startActivity(intent);
// if succeed
return true;
// if fail
} catch(ActivityNotFoundException ex) {
// quick message notification
Toast toast = Toast.makeText(c, "Application Not Found", Toast.LENGTH_LONG);
// display message
toast.show();
}
}
// by default, fail to launch
return false;
}
}
And my listview and search bar show up here:
package com.example.awesomefilebuilderwidget;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Drag_and_Drop_App extends Activity {
private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.drag_and_drop_app);
// import buttons
Button btnLinkToFeedback = (Button) findViewById(R.id.btnLinkToFeedback);
// Link to Feedback Screen
btnLinkToFeedback.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Feedback.class);
startActivity(i);
finish();
}
});
// create new adapter
AppInfoAdapter adapter = new AppInfoAdapter(this, Utilities.getInstalledApplication(this), getPackageManager());
// load list application
mListAppInfo = (ListView)findViewById(R.id.lvApps);
// set adapter to list view
mListAppInfo.setAdapter(adapter);
// search bar
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
// Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// implement event when an item on list view is selected
mListAppInfo.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int pos, long id) {
// get the list adapter
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
ApplicationInfo appInfo = (ApplicationInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
}
});
// implement event when an item on list view is selected via long-click for drag and drop
mListAppInfo.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
// get the list adapter
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
ApplicationInfo appInfo = (ApplicationInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
return true;
}
});
}
}
My app runs fine, just the search function isn't working. I get this error on line 58(
Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
)
adapter cannot be resolved or is not a field
No matter what I do, I can't figure out how to fix this error.
make it this way
AppInfoAdapter adapter ;
onCreate(){
---------------
---------------
adapter = new AppInfoAdapter(.................
}

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