Android notifyDatasetChange with SQLite cursor how to? - android

So I have 2 activities.
The first (ActivityOne) displays a listview with data from SQLite cursor, and a button.
On click of that button, I want to add an item to the listview, so I display the second activity (ActivityTwo), that contains a number of editTexts and a save Button, that does the saving in the Database.
But what I want is:
after saving the new item to the DB, the ActivityTwo should close and the ActivityOne should be displayed with the refreshed content from the DB
.
This seems a reasonable workflow. How do I achieve it?
Code for ActivityOne:
public class ActivityOne extends Activity {
private ArrayList<String> idclient = new ArrayList<String>();
private ArrayList<String> numeclient = new ArrayList<String>();
private ArrayList<String> tipclient = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView mylist = (ListView) findViewById(R.id.lv_clienti);
LoadList();
Button btnex = (Button) findViewById(R.id.btnNewCli);
btnex.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View aView)
{
Toast.makeText(getApplicationContext(), "Add new client... " , Toast.LENGTH_SHORT).show();
Intent toAnotherActivity = new Intent(aView.getContext(), NewClientActivity.class);
startActivity(toAnotherActivity);
}
}
);
}
public void LoadList(){
SQLiteDatabase db = new myDbHelper(getApplicationContext()).getWritableDatabase();
Cursor mCursor = db.rawQuery("select idclient,nameclient,typeclient from clienti order by numeclient" , null);
idclient.clear();
numeclient.clear();
tipclient.clear();
if (mCursor.moveToFirst()) {
do {
idclient.add(Integer.toString(mCursor.getInt(0)));
nameclient.add(mCursor.getString(1));
typeclient.add(mCursor.getString(2));
} while (mCursor.moveToNext());
}
DisplayClientiAdapter disadpt = new DisplayClientiAdapter(ClientiActivity.this,idclient,nameclient, typeclient);
ListView lv = (ListView) findViewById(R.id.lv_clienti);
lv.setAdapter(disadpt);
mCursor.close();
db.close();
}
}
And in the ActivityTwo, I have in a button click:
db.execSQL("insert into clients (idclient, nameclient,typeclient,...");
DisplayClientiAdapter da = new DisplayClientiAdapter(getApplicationContext());
da.notifyDataSetChanged();
finish();
Also the displayAdapter is something like:
public class DisplayClientiAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> idclient;
private ArrayList<String> numeclient;
private ArrayList<String> tipclient;
public DisplayClientiAdapter(Context c){
this.mContext = c;
}
public DisplayClientiAdapter(Context c, ArrayList<String> idclient, ArrayList<String> numeclient, ArrayList<String> tipclient) {
this.mContext = c;
this.idclient = idclient;
this.numeclient = numeclient;
this.tipclient = tipclient;
}
public int getCount() {
return idclient.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.clienti_item, null);
mHolder = new Holder();
mHolder.txt_idclient = (TextView) child.findViewById(R.id.tv_cl_id);
mHolder.txt_numeclient = (TextView) child.findViewById(R.id.tv_cl_nume);
mHolder.txt_tipclient = (TextView) child.findViewById(R.id.tv_cl_tip);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_idclient.setText(idclient.get(pos));
mHolder.txt_numeclient.setText(numeclient.get(pos));
mHolder.txt_tipclient.setText(tipclient.get(pos));
return child;
}
public class Holder {
TextView txt_idclient;
TextView txt_numeclient;
TextView txt_tipclient;
}
Of course it does not work like this. The list is not refreshed... I assume it has to do with the displayAdapter !?!?!
I cannot call the LoadList method since it is static or something like that...
Please help.
Thank you

Its not a problem with your adapter. You have to call Loadlist() in onresume method instead of oncreate method in ActivityOne. It will work then.

First of all, have a look at this two articles:
http://www.doubleencore.com/2013/05/layout-inflation-as-intended/
http://www.doubleencore.com/2013/06/context/
You shouldn't inflate your views with null in your inflate method if you have parent view available.
Also, using application context for inflating may cause strange behaviour, as it may not use correct theme you may've set in app manifest for your Activity.
On the other hand - why don't you use CursorAdapter instead of BaseAdapter?
The problem with your adapter is, that you don't set the data in it! :)
///EDIT:
I checked the wrong activity - why do you create second adapter in there?
The easiest solution would be to move the LoadList() to onStart.
If you want to do it right, you should use ContentObserver and (probably) CursorAdapter.

Related

Listview not updating after arraylist is updated?

I've seen many other posts in this context, but none helped. Problem is when i click on the addField button, the listview inside dialog adds new view just once. But at other clicks it doesn't get updated though The adapter works correctly (I mean the getView is called and also the arrayList in the adapter is changed in size).
I've used notifyDataSetChanged() in the adapter class. No result! I used an instance of adpater class in activity and called myAdapter.notifyDataSetChanged(). No result!
here is my code:
public class MainActivity extends Activity {
ListView lvfid;
FieldAdapter fAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
showFid();
}
private void showFiD(){
final ArrayList <HashMap<String,String>> al = new ArrayList<HashMap<String,String>>();
final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
dialog.setContentView(R.layout.field_dialog);
dialog.setCancelable(true);
dialog.show();
Button addField = (Button) dialog.findViewById(R.id.btnfidField);
lvfid = (ListView) dialog.findViewById(R.id.lvfid);
//Another plan i have tested, but no result:
//fAdapter = new FieldAdapter(dialog.getContext(),al);
//lvfid.setAdapter(fAdapter);
addField.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
HashMap<String,String> h = new HashMap<String,String>();
h.put("name", "");
h.put("value", "");
al.add(h);
lvfid.setAdapter(new FieldAdapter(dialog.getContext(), al));
//fAdapter.notifyDataSetChanged();
}
});
}
public class FieldAdapter extends BaseAdapter{
private ArrayList <HashMap <String,String>> arrayList;
private LayoutInflater inflater;
public FieldAdapter(Context context, ArrayList<HashMap <String,String>> arrayList) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
View view = null;
if (convertView == null)
view = inflater.inflate(R.layout.field_inflater, null);
else
view = convertView;
Holder holder = new Holder();
holder.edName = (EditText) view.findViewById(R.id.edfidName);
holder.edValue = (EditText) view.findViewById(R.id.edfidValue);
//holder.edName.setText(arrayList.get(position).get("name"));
//holder.edValue.setText(arrayList.get(position).get("value"));
return view;
}
private class Holder {
private EditText edName;
private EditText edValue;
}
}
}
UPDATE:
I'm sorry i took everybody's time. The stupid problem was that my listview was inside a scrollview where it must not be! I hope this helps others who have the same issue!
Use the notifyDataSetChanged() every time the list is updated.
I had the same problem. I was facing with this problem when I wanted to update the listView after onDateChanged(). I resolved it with an extra ArrayList variable and an extra custom adapter in your case FieldAdapter variable.
Update your listView with a refresh adapter and array list variables after any operations. For example after button clicks.
1. Define a counter.
2. Check when the button is clicked, increase counter by one
3. Every time check the counter, if counter is greater than 1 it means the button is clicked more than once so update the list view with new variables (arrayList, FeildAdapter)
I recommend you to define the variables as a private class fields and name them such as refreshedArrayList and refreshedAdapter
Option
Try to use the ArrayAdapter. And don't create a new adapter every
time you click on the button.
only call the add(T o) function from the ArrayAdapter.
Other Option:
add a add function to your FieldAdapter in the add field adapter add the object to your arraylist and call notifiyDataSetChanged(the adapter has aslo one and the adapter notifies all his observers)
also don't create a new adapter every time you click the button.
public class MainActivity extends Activity {
ListView lvfid;
FieldAdapter fAdapter;
ArrayList <HashMap<String,String>> al ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
al = new ArrayList<HashMap<String,String>>();
lvfid.setAdapter(new FieldAdapter(MainActivity.this , al));
showFid();
}
private void showFiD(){
final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
dialog.setContentView(R.layout.field_dialog);
dialog.setCancelable(true);
dialog.show();
Button addField = (Button) dialog.findViewById(R.id.btnfidField);
lvfid = (ListView) dialog.findViewById(R.id.lvfid);
//Another plan i have tested, but no result:
//fAdapter = new FieldAdapter(dialog.getContext(),al);
//lvfid.setAdapter(fAdapter);
addField.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
HashMap<String,String> h = new HashMap<String,String>();
h.put("name", "");
h.put("value", "");
al.add(h);
fAdapter.notifyDataSetChanged();
}
});
}
I'm sorry i took everybody's time! The stupid problem was just my listview was inside a scrollview where it must not be! after getting the listview out of scrollview the problem got solved.

custom adapter isn't showing any items

This is a follow on from an earlier question: ImageButton within row of ListView android not working
But after suggestions from SO gurus it has been suggested I post a new question.
The issue is that I have a custom adapter that is not showing any data. I have looked into other questions, but it didn't provide a solution.
In my Main Activity I have a couple of buttons, one of them: ToDo, should create a row that displays data from a SQLite database, and depending on some factors (dates mainly), it shows a type of traffic light that is stored as a drawable.
Part of the Items in this Row is an Image Button that I want the user to be able to click and the image should change. The user should be able also to click on the actual row and a new activity starts.
The issue I have is that NO DATA is being displayed.
So, here is my code:
public class MainActivity extends Activity {
// definitions etc ...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// definitions etc ...
}
public void ToDo(View v){ // the user has clicked in the ToDo button
IgroDatabaseHelper helper = new IgroDatabaseHelper(getBaseContext()); // create instance of SQLIte database
numRows = helper.NumEntries("ToDo"); // Get the number of rows in table
int i = 1;
ArrayList<RowItem> rowItems = new ArrayList<>();
RowItem myItem1;
while (i <= numRows){
// get items from database
// depending on value select different drawable
// put data into List Array of RowItem
myItem1 = new RowItem(TheWhat, R.drawable.teamworka, R.drawable.redtrafficlight, R.drawable.checkbox, TheWhenBy);
rowItems.add(myItem1);
//
i = i+ 1;
}
ListView yourListView = (ListView) findViewById(R.id.list);
CustomListViewAdapter customAdapter = new CustomListViewAdapter(this, R.layout.todo_row, rowItems);
yourListView.setAdapter(customAdapter);
}
The CustomListViewAdapter looks like this:
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
ArrayList<RowItem> _rowItems;
public CustomListViewAdapter(Context context, int resourceId,
ArrayList<RowItem> rowItems) {
super(context, resourceId);
this.context = context;
_rowItems = rowItems;
System.out.println("I am in the custom Adapter class "+ _rowItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
System.out.println("This is the get view");
View row = convertView;
RowItem item = _rowItems.get(position);
// you can now get your string and drawable from the item
// which you can use however you want in your list
String columnName = item.getColumnName();
int drawable = item.getDrawable();
if (row == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.todo_row, parent, false);
}
ImageButton chkDone = (ImageButton) row.findViewById(R.id.chkDone);
chkDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
System.out.println("I am in position "+ position);
}
});
return row;
}
}
The RowItem Class looks like:
public class RowItem {
private String _heading;
private int _icon;
private int _lights;
private int _chkdone;
private String _date;
public RowItem(String heading, int icon, int lights, int chkDone, String date) {
_heading = heading;
_icon = icon;
_lights = lights;
_chkdone = chkDone;
_date = date;
System.out.println("adding stuff to my rows");
System.out.println("my column Name is " + heading);
System.out.println("My drawable int is "+ icon);
}
public String getColumnName() {
System.out.println("column Names is "+ _heading);
return _heading;
}
public int getDrawable() {
return _icon;
}
public int getLights(){
return _lights;
}
public int getchkDone(){
return _chkdone;
}
public String getDate(){
return _date;
}
}
I am obviously missing something, as I mentioned earlier, no data gets shown. I know that there are 2 row items that get passed to the CustomListViewAdapter. But I also know that the View getView inside the CustomListViewAdapter does not actually get called.
I hope I have put enough information/code, but if you feel I need to explain something further, please say.
Thanking all very much in advance!
I don't see a getCount() method. You should be overriding it like this:
#Override
public int getCount() {
return _rowItems.getCount();
}
Alternatively, calling super(context, resourceId, rowItems); should also fix it.
Your ListView thinks there are no items to display. If you are using your own array, you must override the getCount() method to indicate the number of items you want to display.

refresh listview after data has changed from custom adapter

I have seen several posts on this but I cannot seem to follow one well enough to fix my problem.
I am trying to refresh my ListView after I update or delete a record. I am currently using notifyDataSetChanged() however it does not refresh upon deletion. I can delete, and then if i back our and reload my history.java it will show the updates because I am reloading all of the data.
here is my HistoryAdapter.java
public class HistoryAdapter extends BaseAdapter {
private Context mContext;
Cursor cursor;
history historyClass = new history();
MySQLiteHelper db;
public HistoryAdapter(Context context, Cursor cur){
super();
mContext = context;
cursor = cur;
db = new MySQLiteHelper(context);
}
public int getCount(){
// return the number of records in cursor
return cursor.getCount();
}
// getView method is called for each item of ListView
public View getView(final int position, View view, ViewGroup parent){
// inflate the layout for each item of listView
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.history_list_item, null);
// move the cursor to required position
cursor.moveToPosition(position);
final String id = cursor.getString(cursor.getColumnIndex("_id"));
final long deleteId = Long.parseLong(id);
// fetch the information for each card
String pricePerGallon = cursor.getString(cursor.getColumnIndex("pricePerGallon"));
String gallons = cursor.getString(cursor.getColumnIndex("gallons"));
String odometer = cursor.getString(cursor.getColumnIndex("odometer"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String filledOrNot = cursor.getString(cursor.getColumnIndex("filledOrNot"));
String comments = cursor.getString(cursor.getColumnIndex("comments"));
//String milesPerGallon = cursor.getString(cursor.getColumnIndex("miledPerGallon"));
String totalSpent = cursor.getString(cursor.getColumnIndex("totalSpent"));
// get the reference of TextViews
TextView textViewPricePerGallon = (TextView) view.findViewById(R.id.cardPrice);
TextView textViewGallons = (TextView) view.findViewById(R.id.cardGallons);
TextView textViewOdometer = (TextView) view.findViewById(R.id.cardOdometer);
TextView textViewDate = (TextView) view.findViewById(R.id.cardDate);
TextView textViewFilledOrNot = (TextView) view.findViewById(R.id.cardFilledOrNot);
TextView textViewComments = (TextView) view.findViewById(R.id.cardComments);
//TextView textViewMilesPerGallon = (TextView) view.findViewById(R.id.mpg);
TextView textViewTotalSpent = (TextView) view.findViewById(R.id.usd);
TextView textViewDeleteButton = (TextView) view.findViewById(R.id.deleteButton);
// Set the data to each TextView
textViewPricePerGallon.setText(pricePerGallon);
textViewGallons.setText(gallons);
textViewOdometer.setText(odometer);
textViewDate.setText(date);
textViewFilledOrNot.setText(filledOrNot);
textViewComments.setText(comments);
//textViewMilesPerGallon.setText(milesPerGallon);
textViewTotalSpent.setText(totalSpent);
final HistoryAdapter historyAdapter = this;
textViewDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("History Adapter", "" + deleteId);
//need to delete here
deleteRecord(deleteId);
historyAdapter.notifyDataSetChanged();
}
});
return view;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position){
return position;
}
private void deleteRecord(long id){
db.deleteGasLog(id);
}
}
here is my history.java which sets the adapter and creates the listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
context = this;
initViews();
cursor = db.getAllLogs();
// Create the Adapter
historyAdapter = new HistoryAdapter(this, cursor);
// Set the adapter to ListView
listContent.setAdapter(historyAdapter);
}
I guess you will need to get a new cursor.
Try moving this
cursor = db.getAllLogs();
into the adapter and call it again before the notifyDataSetChanged() call.
You are deleting the row but you are never updating or getting a new cursor, which has the result set the adapter uses to layout the list. You need to give the adapter a new cursor after you delete a row, then call notifyDatasetChanged(). If you use SimpleCursorAdapter
instead of BaseAdapter, you can use its swapCursor() method to set the new cursor.
Make sure to call:
registerDataSetObserver(...)
from your BaseAdapter subclass.
Pass it the reference to your DataSetObserver implementation. Possibly through an inner class of HistoryAdapter:
public class HistoryAdapter extends BaseAdapter {
. . .
public class MyDataSetObserver extends DataSetObserver {
public void onChanged() {
// Data Set changed.... do something...
}
public void onValidated() {
// Your implementation here
}
}
. . .
public HistoryAdapter(Context context, Cursor cur) {
. . .
registerDataSetObserver(new MyDataSetObserver());
. . .
}
}
HTH

custom adapter do not refresh the listview for onclicklistener in android

I delete database entry using onclicklistener but it is not refreshing the listview. how can i refresh this listview?
This is main class for listview:
public class AFragment extends Fragment implements OnItemClickListener {
protected static final String file_name ="user";
ListView list;
Database entry;
View v;
String values[];
MySimpleArrayAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
SharedPreferences settings = getActivity().getSharedPreferences(file_name, 0);
String name = settings.getString("name", null);
entry = new Database(getActivity());
entry.open();
values=entry.planlist(name);
entry.close();
if(values.length>0){
v = inflater.inflate(R.layout.activity_afragment, container,false);
adapter = new MySimpleArrayAdapter(getActivity(), values);
list=(ListView)v.findViewById(R.id.list);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
list.setOnItemClickListener(this);
}else{
v = inflater.inflate(R.layout.activity_my_tabs_listener, container,false);
}
// Toast.makeText(getActivity(),String.valueOf(values.length), Toast.LENGTH_LONG).show();
return v;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(),Details.class);
i.putExtra("sub", values[arg2]);
startActivity(i);
Toast.makeText(getActivity(), "clicked", Toast.LENGTH_SHORT).show();
}
}
Here i use onclicklistener to delete data from database but it is not refreshing:
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public Business aFragment = new Business();
int mypos =0;
ViewHolder holder;
View row;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context,R.layout.activity_my_simple_array_adapter, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
mypos = position;
row = convertView;
holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(R.layout.activity_my_simple_array_adapter, parent, false);
TextView textView = (TextView) row.findViewById(R.id.text);
Button btn = (Button) row.findViewById(R.id.button1);
holder.tv = textView;
holder.btn = btn;
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
holder.tv.setText(values[position]);
final int id = position;
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Database entry = new Database(context);
entry.open();
entry.delete(values[id]);
entry.close();
// Toast.makeText(getContext(), String.valueOf(id), Toast.LENGTH_LONG).show();
}
});
return row;
}
static class ViewHolder{
TextView tv;
Button btn;
}
}
as anil said, you should put notifyDataSetChanged(); inside the onClickListener
this basically tells the adapter to render the list again and will call getView() again for every visible item in the list, if your code crashes, you should check two things:
first - debug the program and check that the new data fits what you want, in your case, check that the entry was deleted properly.
second - debug the getView method, step through each call and see what gives you the crash.
in your case the problem is that you are only updating the database, but in fact your listview data is taken from the values[] array which is not updated after you delete the database entry, you should create a function for updating it.
Put adapter.notifyDataSetChanged(); on click of ListView
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Database entry = new Database(context);
entry.open();
entry.delete(values[id]);
entry.close();
adapter.notifyDataSetChanged();
// Toast.makeText(getContext(), String.valueOf(id), Toast.LENGTH_LONG).show();
}
If you do lots of adding and deleting to the list I think you should do the things below.
You should use ArrayList<String> instead of simple String[] so that you can easily delete. Database deletion do not effect the list directly unless you use Loaders
After you delete and item from the list, you should call notifyDataSetChanged() to the adapter. If you do not call this method, the list wont be updated.
adapter.notifyDataSetChanged();
you are removing it from the database but you are not removing it from the dataset that fills up your ListView. The simplest thing you can do is to change values from array to ArrayList, and since you are using an ArrayAdapter, you can call remove(int position). You need a List<T> of objects otherwise remove will throws an exception.
You can do one thing.
Firstly create a method called myAdapter().
In this put your creation of adapter code,so you can create new adapter for loading new data by simply calling myAdapter() method.
Whenever there should be modification in your ListView just called the following code,
listview.invalidate();
Then simply call the myAdapter().
That's it.Hope this is useful to you..:)

Android: How to pass an object from one activity to another in an onClick method and use it for an AsyncTask class

I have a problem that is a little hard to explain. I am building an android application for trip planning. I have a main activity that contains the map item and some other buttons and an AsyncTask class where the communication with the server is done and the path is displayed on the map. I am trying to make it work offline by saving the response from the server in sqllite database.
I have an Activity called MainActivity. There, I have a method for menu items
public boolean onOptionsItemSelected(final MenuItem pItem) {
switch (pItem.getItemId()) {
case R.id.recent_trips:
startActivity(new Intent(this, recentTripsActivity.class));
break;
default:
break;
}
return false;
}
}
Here is the current method for calling the AsyncTask class
btnPlanTrip.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tripReq = new TripRequest(MainActivity.this,activityHandler,db);
tripReq.execute(request);
}
});
}
When I click on the recent_trips from the menu button, recentTripsActivity opens. Basically, in this class I retrieve some data from mysqllite database and present it on a listView through an adapter. There, I have a method view.setOnClickListener in which when a list item is clicked I take a certain value (res=listItem.getofflineResult();). I would like to use that value on Main Activity (see below for more details).
Here is the code.
public class recentTripsActivity extends Activity implements Serializable {
private ImageButton stopSearch;
private AutoCompleteTextView searchField;
SQLiteDatabase db;
OfflineTripRequest tripReq;
String res;
//db = openOrCreateDatabase("AndroidDatabase.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
private ListView listview;
private ArrayList mListItem;
ItemBO listItem;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_trips);
//open database connection
db = openOrCreateDatabase("AndroidDatabase.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
int i=0;
String [] str={"id","description","offlineResult"};
listview = (ListView) findViewById(R.id.lview_trips);
mListItem = new ArrayList<ItemBO>();
Cursor cursor = db.query("tbl_offlinePathResult",str, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
i++;
ItemBO listItem = new ItemBO(i,cursor.getString(1),cursor.getString(2));
mListItem.add(listItem);
cursor.moveToNext();
if(i==10){
break;
}
}
// Make sure to close the cursor
cursor.close();
i++;
listview.setAdapter(new ListAdapter(recentTripsActivity.this, R.id.lview_trips,mListItem));
db.close();
}
//***ListAdapter***
class ListAdapter extends ArrayAdapter { //--CloneChangeRequired
private ArrayList mList; //--CloneChangeRequired
private Context mContext;
#SuppressWarnings("unchecked")
public ListAdapter(Context context, int textViewResourceId,
ArrayList list) { //--CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
try {
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item_saved_paths, null); //--CloneChangeRequired(list_item)
}
final ItemBO listItem = (ItemBO) mList.get(position); //--CloneChangeRequired
if (listItem != null) {
// setting list_item views
((TextView) view.findViewById(R.id.tv_name))
.setText(listItem.getDescription());
view.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) { //--clickOnListItem
res=listItem.getofflineResult();
}
});
}
} catch (Exception e) {
Log.i(recentTripsActivity.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
}
I would like to pass the data mentioned above(res=listItem.getofflineResult() to MainActivity. After doing that I would like to call an AsyncTask class and pass that data to that class. How can I do all this by clicking on the listItem? As I said before the map is on MainActivity but the click will happen from a different Activity.
I hope I made my self clear enough, If you have any questions please ask me
First, you need to override onListItemClick in your list. You will then need to put the needed information into a bundle and end the activity. This bundle gets "returned" to the calling activity in that activity's onActivityReuslt method (which you will need to override). See:
Passing Data Between Activities
I generally use a singleton method when passing data in an android app. If you are unfamiliar, it is basically a static class that always returns the same instance. This allows you to create multiple 'instances' of the class that all share the same data.
Singleton Design Pattern
Well you can pass the res (String?) in many ways, the simple is throw preferences:
SharedPreferences settings = context.getSharedPreferences(APPNAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("res", res);
editor.commit();
and then in MainActiviy get:
SharedPreferences settings = context.getSharedPreferences(APPNAME, 0);
res = settings.getString("res","");
You can also save in the local database, or like "tkcsam" says using a static and abstract variable.
public abstract Global{
public static String res;
}
and you can acess in any Activity like :
Global.res = "A"

Categories

Resources