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.
Related
my code is working and I am getting the value on textview but its not changing on first click, suppose my spinner pops up and I select other value than at the same time my textview value doesn't changes it changes on the next click.
package com.vedicrishiastro.kundli.Screens.Extras;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.vedicrishiastro.kundli.R;
import com.vedicrishiastro.kundli.Screens.AbstractActivity;
public class Settings extends AbstractActivity implements View.OnClickListener {
private LinearLayout linearSelectLang,linearSetDefault,linearSelectPanch;
private TextView txtSelectLang,txtSetDefault,txtSelectPanch;
private Spinner spinner1,spinner2,spinner3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
linearSelectLang = (LinearLayout)findViewById(R.id.LinearSelectLang);
linearSetDefault = (LinearLayout)findViewById(R.id.LinearSetDefault);
linearSelectPanch = (LinearLayout)findViewById(R.id.LinearSelectPanch);
spinner1 = (Spinner)findViewById(R.id.settingSpinner1);
spinner2 = (Spinner)findViewById(R.id.settingSpinner2);
spinner3 = (Spinner)findViewById(R.id.settingSpinner3);
txtSelectLang = (TextView)findViewById(R.id.selectLangtext);
txtSetDefault = (TextView)findViewById(R.id.setdefaulttext);
txtSelectPanch = (TextView)findViewById(R.id.selectPanchtext);
linearSelectLang.setOnClickListener(this);
linearSetDefault.setOnClickListener(this);
linearSelectPanch.setOnClickListener(this);
spinner1.setVisibility(View.GONE);
spinner2.setVisibility(View.GONE);
spinner3.setVisibility(View.GONE);
}
public void onClick(View view){
int id = view.getId();
switch (id){
case R.id.LinearSelectLang:
{
spinner1.performClick();
String text = spinner1.getSelectedItem().toString();
txtSelectLang.setText(text);
spinner1.setVisibility(View.GONE);
}
break;
case R.id.LinearSetDefault:
{
spinner2.performClick();
String text = spinner2.getSelectedItem().toString();
txtSetDefault.setText(text);
spinner2.setVisibility(View.GONE);
}
break;
case R.id.LinearSelectPanch:
{
spinner3.performClick();
String text = spinner3.getSelectedItem().toString();
txtSelectPanch.setText(text);
spinner3.setVisibility(View.GONE);
}
break;
}
}
}
I tried this but it isn't working
case R.id.LinearSelectLang:
{
spinner1.performClick();
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0)
{
txtSelectLang.setText("English");
}
else
{
txtSelectLang.setText("हिंदी");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
break;
How about you use the spinner's OnItemSelected event?
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Thing is, if you call performClick, the spinner pops out, but this call is not blocking. So you need the OnItemSelectedListener to get an async response with the input made by the user.
Calling getSelectedItem right after performClick (which opens the spinner?) will return the previously set element - which is the error you are facing.
Create an onItemSelectListener for your Spinner and change the text every time an item is selected.
spinner.setOnItemSelectedListener(new OnItemSelectListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
// DO it here
}
});
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
I made an Activity for searching people that also shows history of recent research.
If I long click on an item of the history it asks me if I want to delete it. If I press "Yes" it deletes the list item.
So, I write something and click to "Search" button. This brings me in another Activity with results. Here I click on result so it stores the person info and brings me in the person page.
When I come back I don't see the new person in the history.
So I overwritten onResume() but it still not work and now I cannot delete items from the history list.
Here the code:
package com.lpsmt.proffinder;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.lpsmt.R;
public class HomeActivity extends Activity
{
protected Db db = null;
protected List<ProfBean> historyProfs = null;
protected ProfListItemAdapter listAdapter = null;
protected ListView listView = null;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.db = new Db(this);
this.setContentView(R.layout.prof_finder_home);
this.historyProfs = this.db.getHistory(-1); // -1 means with no limits
this.listAdapter = new ProfListItemAdapter(HomeActivity.this, R.id.prof_finder_history_list_view, this.historyProfs);
this.listView = (ListView) this.findViewById(R.id.prof_finder_history_list_view);
listView.setAdapter(this.listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(HomeActivity.this, ProfPageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("profId", HomeActivity.this.historyProfs.get(position).getProfId());
intent.putExtras(bundle);
HomeActivity.this.startActivity(intent);
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id)
{
Resources resources = HomeActivity.this.getResources();
String title = resources.getString(R.string.prof_finder_history_delete_title);
String message = resources.getString(R.string.prof_finder_history_delete_message);
AlertDialog.Builder adb=new AlertDialog.Builder(HomeActivity.this);
adb.setTitle(title);
adb.setMessage(message);
final int positionToRemove = position;
String positive = resources.getString(R.string.prof_finder_history_delete_positive);
String negative = resources.getString(R.string.prof_finder_history_delete_negative);
adb.setNegativeButton(negative, null);
adb.setPositiveButton(positive, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ProfBean prof = HomeActivity.this.historyProfs.get(positionToRemove);
HomeActivity.this.db.deleteProf(prof.getProfId());
HomeActivity.this.historyProfs.remove(positionToRemove);
HomeActivity.this.runOnUiThread(new Runnable() {
public void run() {
HomeActivity.this.listAdapter.notifyDataSetChanged();
}
});
}});
adb.show();
return true;
}
});
}
public void searchProf(View view) throws Exception
{
EditText queryEditText = (EditText) this.findViewById(R.id.prof_finder_search_query);
String query = queryEditText.getText().toString().trim();
queryEditText.setText(query);
if (query.length() < 3) {
String message = this.getResources().getString(R.string.prof_finder_query_too_short);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(HomeActivity.this, SearchResultActivity.class);
Bundle bundle = new Bundle();
bundle.putString("query", query);
intent.putExtras(bundle);
this.startActivity(intent);
}
public void onResume()
{
super.onResume();
this.historyProfs = this.db.getHistory(-1);
this.listAdapter.notifyDataSetChanged();
}
}
You haven't set any new data to list view. Thats why your new contact isn't added to the list after notifyDataSetChanged(). You need to add some method into adapter like
setData(List<ProfBean> data)
{
this.currentAdaptersList= data;
}
and then call notifyDataSetChanged(). So the final onResume will be :
public void onResume()
{
super.onResume();
this.historyProfs = this.db.getHistory(-1);
this.listAdapter.setData(this.historyProfs);
this.listAdapter.notifyDataSetChanged();
}
Enjoy.
And using onResume() for this task is bad idea. Is better to use onActivityResult.
notifyDataSetChanged() didn't work for me either. I was able to solve this a little bit differently:
I use OnStart() (in a derived class from Fragment)
I use setNotifyOnChange() of the ArrayAdapter:
ListView listView = (ListView) findViewById(R.id.logListView);
listView.setAdapter(logAdapter);
logAdapter.setNotifyOnChange(true);
I create the adapter once:
logAdapter = new ArrayAdapter(activity, android.R.layout.simple_list_item_1, activity.logMessages);
in onViewCreated().
I am googling for the last few hours, I've seen this question asked like 20 times but none of the solutions seem to work for me. I have a ListView and a CustomList class, that incorporates a list adapter and a simple dialog for editing/removing/renaming items. everything works as supposed until the first screen rotation. After that, the list stops being updated, although the adapter contains all the right data.
I will post both files without skipping a line. I don't need any data being saved at this time, I will handle that later. This is really weird because supposedly the application gets completely restarted after screen rotation. What makes it even stranger, the dummy items are added onCreate even after screen rotation, but after that there is no other response from the list.
Please excuse my english and my noobness and try to point me in the right direction.
package com.sl.mylandmarks;
import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; 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.OnItemLongClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView;
public class MainActivity extends Activity {
Button addButton; ListView landmarksList; EditText inputName, inputSearch; CustomList customList; Context globalContext; TextView gpsState; private LocationManager locationManager; private GPSTracker gpsTracker; private double longitude; private double latitude;
#Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
gpsTracker = new GPSTracker(MainActivity.this);
globalContext = this;
addButton = (Button) findViewById(R.id.addBtn);
customList = new CustomList(this);
landmarksList = (ListView) findViewById(R.id.listView1); landmarksList.setAdapter(customList.getAdapter()); landmarksList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); landmarksList.setTextFilterEnabled(true); landmarksList.setLongClickable(true); customList.theList = landmarksList;
inputName = (EditText) findViewById(R.id.EditItemName);
gpsState = (TextView) findViewById(R.id.gpsState);
ContentResolver contentResolver = getBaseContext().getContentResolver(); boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER); if (gpsStatus) { gpsState.setText("GPS Enabled"); } else { gpsState.setText("GPS Disabled"); }
// // SEARCH BOX
inputSearch = (EditText) findViewById(R.id.editText3); inputSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) { }
public void onTextChanged(CharSequence s, int start, int before,
int count) {
customList.getAdapter().getFilter().filter(s); } }); // // SEARCH BOX
// / DUMMY ITEMS customList.addItem("Home", "43.1565 / 15.8645"); customList.addItem("Work", "43.1565 / 15.8645"); customList.addItem("Denis` apartment", "43.1565 / 15.8645"); customList.addItem("Natasa", "43.1565 / 15.8645"); customList.addItem("Bruce Wayne", "43.1565 / 15.8645"); customList.addItem("Walker shop", "43.1565 / 15.8645"); customList.addItem("Chuck Norris Residence", "43.1565 / 15.8645"); customList.addItem("Some landmark", "43.1565 / 15.8645"); // customList.removeItem(3);
OnItemLongClickListener listLongClick = new OnItemLongClickListener() {
#Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
customList.showOptionsDialog(arg2);
return true;// event consumed, not dispatched forward } };
landmarksList.setOnItemLongClickListener(listLongClick);
OnClickListener ButtonClick = new View.OnClickListener() {
#Override public void onClick(View v) {
switch (v.getId()) {
case R.id.addBtn:
customList.addItem(inputName.getText().toString(),
"45.5644 / 23.6541");
inputName.setText("");
break;
}
}
};
addButton.setOnClickListener(ButtonClick);
}
#Override public void onPause() { super.onPause();
}
#Override public void onResume() { super.onResume();
}
#Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true;
}
}
and CustomList.java
package com.sl.mylandmarks;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class CustomList {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(
2);
HashMap<String, String> maplist;
SimpleAdapter listAdapter;
public Context context;
public ListView theList;
public CustomList(Context con) {
context = con;
String[] from = { "line1", "line2" };
int[] to = { android.R.id.text1, android.R.id.text2 };
listAdapter = new SimpleAdapter(context, list,
android.R.layout.simple_list_item_2, from, to);
}
public void addItem(String name, String coords) {
if ((name != null) && (name.length() != 0)) {
maplist = new HashMap<String, String>();
maplist.put("line1", name);
maplist.put("line2", coords);
list.add(maplist);
listAdapter.notifyDataSetChanged();
}
}
public void removeItem(int id) {
Log.d("removing",list.remove(id).toString());
listAdapter.notifyDataSetChanged();
}
public void renameItem(int id, String newName) {
Log.d("SL","Rename Selected");
maplist = new HashMap<String, String>();
maplist.put("line1", newName);
maplist.put("line2", list.get(id).get("line2"));
list.set(id, maplist);
listAdapter.notifyDataSetChanged();
}
public SimpleAdapter getAdapter() {
return listAdapter;
}
public void showOptionsDialog(final int position) {
//Log.d("SL", String.valueOf(position));
final Dialog optionsDialog = new Dialog(context);
optionsDialog.setContentView(R.layout.list_dialog);
optionsDialog.setTitle("Options");
optionsDialog.show();
final EditText itemNameEdit = (EditText) optionsDialog
.findViewById(R.id.EditItemName);
final Button removeBtn = (Button) optionsDialog
.findViewById(R.id.removeBtn);
final Button renameBtn = (Button) optionsDialog
.findViewById(R.id.renameBtn);
final Button cancelBtn = (Button) optionsDialog
.findViewById(R.id.cancelBtn);
itemNameEdit.setText(list.get(position).get("line1"));
itemNameEdit.setSelection(itemNameEdit.length());
OnClickListener ButtonClick = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.removeBtn:
removeItem(position);
optionsDialog.dismiss();
break;
case R.id.renameBtn:
renameItem(position, itemNameEdit.getText().toString());
optionsDialog.dismiss();
break;
case R.id.cancelBtn:
optionsDialog.dismiss();
break;
}
}
};
removeBtn.setOnClickListener(ButtonClick);
renameBtn.setOnClickListener(ButtonClick);
cancelBtn.setOnClickListener(ButtonClick);
}
}
I not sure what exactly is your question. And I didn't look at your code, because I don't think that SO is a good place to just dump classes and say "fix this". But I might have an answer for you.
It is true that Android is recreating the activity when you rotate (like roky says). If you come from an iPhone development background (which is my case), it look like kind of weird.
But if your activity is not too complex, you can say to Android to handle it. Do to this, add this to your tag of your AndroidManifest.xml
<activity android:configChanges="orientation|screenSize" ... >
</activity>
Here is a better explanation than mine : android:configChanges="orientation" does not work with fragments
If my answer was the good one, it would be nice to accept it!
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);