OnListItemClick in an activity - android

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
}

Related

Handling clicks inside listview

I'm new in Android and need help with my ListView, which contains text view and image in every list item. I need handle clicks on list item and on icon (R.id.list_star) in list item separately. I tried several ways but it seems I can't do it by myself. I tried to put star.setOnItemClickListener in the beginning, near lvData.setOnItemClickListener - but in this case view isn't found, and add swith inside AdapterView.OnItemClickListener - doesn't work. My code handles only list item click but no icon clicks
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class ListViewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
ListView lvData;
DB db;
SimpleCursorAdapter scAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
db = new DB(this);
db.open();
String[] from = new String[]{DB.COLUMN_IMG, DB.COLUMN_TXT, DB.COLUMN_IMG2};
int[] to = new int[]{R.id.list_label, R.id.list_text, R.id.list_star};
scAdapter = new SimpleCursorAdapter(this, R.layout.list_item, null, from, to, 0);
lvData = (ListView) findViewById(R.id.list);
lvData.setAdapter(scAdapter);
getSupportLoaderManager().initLoader(0, null, this);
lvData.setOnItemClickListener(mOnListItemClickListener);
}
final Context context = this;
protected void onDestroy() {
super.onDestroy();
db.close();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle bndl) {
return new MyCursorLoader(this, db);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
scAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
static class MyCursorLoader extends CursorLoader {
DB db;
public MyCursorLoader(Context context, DB db) {
super(context);
this.db = db;
}
#Override
public Cursor loadInBackground() {
Cursor cursor = db.getAllData();
return cursor;
}
}
private AdapterView.OnItemClickListener mOnListItemClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Cursor cursor = (Cursor) scAdapter.getItem(position);
switch (v.getId()) {
case R.id.list_star:
Toast.makeText(getApplicationContext(), "star", Toast.LENGTH_SHORT).show();
case R.id.list_label:
Toast.makeText(getApplicationContext(), "label", Toast.LENGTH_SHORT).show();
}
ImageView star = (ImageView) findViewById(R.id.list_star);
star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Вы выбрали стихи Агнии Барто", Toast.LENGTH_SHORT).show();
}
});
Intent intent = new Intent(context, ViewPagerActivity.class);
String pos = Long.toString(position);
intent.putExtra("pos", pos);
startActivity(intent);
}
};
}

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.

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

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.

Android ListView does not update onResume

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().

Categories

Resources