android sqlite onresume() oncreate() - android

I have several activities that write and read to database. As client has to switch between them. If i leave code just in onCreate, different views will not be updated when activity is broght back to screen. What is the best way to ensure that all data is apdated when activity gets focus?
Is it wise to move evrything from onCreate() to onResume() ?
is there wat to make it better?
public class InboxActivity extends ListActivity {
List<Candidate> candidates;
private DatabaseHandler db;
private CandidateAdapter adapter;
private ListView lvMain;
public void onDestroy(){
if (db != null)
db.close();
super.onDestroy();
//db.close();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox_list);
db = new DatabaseHandler(this);
candidates = db.getAllCandidates(1);
db.close();
adapter = new CandidateAdapter(this,(ArrayList) candidates);
lvMain = getListView();
lvMain.setAdapter(adapter);
lvMain.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.from)).getText().toString();
Log.d("Name ", name);
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra("name", name);
Log.d("Starting activity ", "Yeah ");
startActivity(in);
}
});
}
public void onResume(){
super.onResume();
db = new DatabaseHandler(this);
candidates = db.getAllCandidates(1);
db.close();
adapter = new CandidateAdapter(this,(ArrayList) candidates);
lvMain = getListView();
lvMain.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
adapter
public class CandidateAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
ArrayList<Candidate> objects;
CandidateAdapter(Context context, ArrayList<Candidate> candidates) {
ctx = context;
objects = candidates;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return objects.size();
}
public Object getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
Candidate getCandidate(int position) {
return ((Candidate) getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
// используем созданные, но не используемые view
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.inbox_list_item, parent, false);
}
Candidate p = getCandidate(position);
((TextView) view.findViewById(R.id.from)).setText(p.get_name());
((TextView) view.findViewById(R.id.subject)).setText(p.get_office());
((RatingBar) view.findViewById(R.id.rateindicator)).setRating(p.get_ranking());
int loader = R.drawable.loader;
ImageView image = (ImageView) view.findViewById(R.id.photo);
String image_url = p.get_photograph();
ImageLoader imgLoader = new ImageLoader(ctx);
imgLoader.DisplayImage(image_url, loader, image);
return view;
}
}

If you are not finishing your activity, than you no need to write all thing in onResume()
you should write just this in onResume().
public void onResume(){
adapter = new CandidateAdapter(this,(ArrayList) candidates);
lvMain.setAdapter(adapter);
adapter.notifyDataSetChanged()
}
define your CandidateAdapter as a class variable.

Related

Passing data in from list to detail view in Android

I have a list view populated threw an SQlitedatabase but I need to pass to a detail activity from the list view. The problem is in passing the details from the listview activity to the detail activity because when I click the detail activity it gives me blank edit texts
Here is my listview activity:
public class consulter_note extends Activity implements AdapterView.OnItemClickListener{
ListView list;
SQLiteDatabase sqLiteDatabase;
DataBaseOperationstwo dataBaseOperationstwo;
Cursor cursor;
ListDataAdapter listDataAdapter;
String titre,objet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consulter_note);
list = (ListView) findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.notelist_row);
list.setAdapter(listDataAdapter);
list.setOnItemClickListener(this);
dataBaseOperationstwo = new DataBaseOperationstwo(getApplicationContext());
sqLiteDatabase = dataBaseOperationstwo.getReadableDatabase();
cursor = dataBaseOperationstwo.getInformations(sqLiteDatabase);
if (cursor.moveToFirst())
{
do
{
titre = cursor.getString(0);
objet = cursor.getString(1);
DataProvider dataProvider = new DataProvider(titre,objet);
listDataAdapter.add(dataProvider);
}while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, note_details.class);
startActivity(intent);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
}
}
And here is my array adapter:
public class ListDataAdapter extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView TITRE,OBJET;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.notelist_row,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.TITRE = (TextView) row.findViewById(R.id.titredemo);
layoutHandler.OBJET = (TextView) row.findViewById(R.id.objetdemo);
row.setTag(layoutHandler);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.TITRE.setText(dataProvider.getTitre());
layoutHandler.OBJET.setText(dataProvider.getObjet());
return row;
}
}
The data provider class used in the array adapter:
public class DataProvider {
private String titre,objet;
public DataProvider(String titre,String objet)
{
this.titre = titre;
this.objet = objet;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getObjet() {
return objet;
}
public void setObjet(String objet) {
this.objet = objet;
}
}
And finally my details activity. I'm only interested in the intent part; the rest has nothing to do with my problem:
public class note_details extends Activity {
ImageButton Del;
EditText PASSTITRE,USEROBJET;
String Passtitre,Userobjet;
DataBaseOperationstwo DOP;
Context CTX = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =getIntent();
if(intent != null)
{
String objet = intent.getStringExtra("objet");
String titre= intent.getStringExtra("titre");
PASSTITRE.setText(objet);
USEROBJET.setText(objet);
}
setContentView(R.layout.activity_note_details);
Del = (ImageButton) findViewById(R.id.suppnote);
PASSTITRE = (EditText) findViewById(R.id.titree);
USEROBJET = (EditText) findViewById(R.id.objett);
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passtitre = PASSTITRE.getText().toString();
Userobjet = USEROBJET.getText().toString();
DOP = new DataBaseOperationstwo(CTX);
DOP.deleteNote(DOP,Passtitre,Userobjet);
Toast.makeText(getBaseContext(),"note supprimé",Toast.LENGTH_LONG).show();
finish();
}
});
}
public void liste(View v)
{
Intent i = new Intent(this, consulter_note.class);
startActivity(i);
}
public void supprimer(View v)
{
}
}
My logcat doesn’t show any errors but the details activity shows with empty edittexts.
You should first add extras to the Intent and then fire it:
Intent intent = new Intent(this, note_details.class);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
startActivity(intent);
Another thing worth mentioning is that you should avoid doing DB queries on the main thread, as it will slow down your app. Use Loaders, or just run queries on worker threads.

Start activity, stop timer, change values from another class

I don't know neither how to write my question so I hope you will understand from my code:
So i have this EXAMPLE code:
MAIN:
public class ListImageButton extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView lv = (ListView) findViewById( R.id.list );
lv.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
//HERE THIS IS WORKING
boolean_toast = false;
timer.cancel();
zanimivosti.cancel();
Intent intent = new Intent(ListImageButton.this,
ANOTHER_ACTIVITY.class);
startActivity(intent);
}
});
ArrayList<String> items = new ArrayList<String>();
items.add( "item1");
items.add( "item2");
ListAdapter adapter = new ListAdapter( this, items);
lv.setAdapter( adapter );
}
}
And the ADAPTER:
public class ListAdapter extends BaseAdapter {
public ListAdapter(Context context,
List<String> items ) {
inflater = LayoutInflater.from( context );
this.context = context;
this.items = items;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
String item = items.get(position);
View v = null;
if( convertView != null )
v = convertView;
else
v = inflater.inflate( R.layout.item, parent, false);
TextView itemTV = (TextView)v.findViewById( R.id.item);
itemTV.setText( item );
ImageButton button =
(ImageButton)v.findViewById( R.id.button);
button.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
//HERE THIS IS NOT WORKING
boolean_toast = false;
timer.cancel();
zanimivosti.cancel();
Intent intent = new Intent(ListImageButton.this,
ANOTHER_ACTIVITY.class);
startActivity(intent);
}
});
return v;
}
private Context context;
private List<String> items;
private LayoutInflater inflater;
}
So I would like to stop some timers and cancel some toast that I have in the main activity/class, and also I would like to start a new activity.
Ok I thought about it and the answer was very simple..looks like I was to tired to think about it..
I made this function in the main activity:
public static void preklopi() {
boolean_toast = false;
cas = 0;
perioda = 0;
timer.cancel();
zanimivosti.cancel();
Intent intent = new Intent(Context, kasper.api.Najdi_osebo.class);
Context.startActivity(intent);
}
And then I called the function from main activity in the other class..

How to refresh view after updating sql row while using OnItemLongClick?

The problem is as follows: When I click on the row, dialog opens where I enter new row value and click ok to save changes. The row is updated, but I need to exit view and go back again to see changes. How can I refresh view automatically when the sava button is clicked?
Here is my code for Dialog:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
And here is the code where I want to refresh view instead of doing it manually:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
I hope it's clear enough what I am looking for. Where my list is, I want the list to be refreshed automatically after updating row so the new content of the row shows up immediately instead of navigating to other view and going back. I will be appreciated for your help.
At some point, after you call EditListItemDialog and it finishes, you need to run NotifyDataSetChanged() on your listview adapter. onResume() is a good place to do it,

Why do I have to scroll to refresh my list view?

I'm new to android. I'm trying to get my list view to update, I've tried everything...from calling notifydatasetchanged on the ui thread to just simply recreating my list adapter but for whatever reason when I update, no matter which method I use I have to scroll to see the changes. By this I mean that the data updates (say 13:01 changes to 13:02 in the list), it will update, but to see the change I have to scroll so that 13:01 goes off screen and then move back and it will have updated visually.
Why is this? (I can't post code right now as I'm on my phone but if required I will post later.)
EDIT: Here's the relevant code...sorry it took so long I haven't been at my computer for a couple of days.
Relevant parts of ListFragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.match_fragment, container, false);
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MatchAdapter adapter = (MatchAdapter) this.getListAdapter();
if(futureMatches)
adapter = new MatchAdapter (this.getActivity(), ((MainActivity)this.getActivity()).getMatches(), futureMatches);
else
adapter = new MatchAdapter (this.getActivity(), ((MainActivity)this.getActivity()).getPastMatches(), futureMatches);
setListAdapter(adapter);
}
public void refresh()
{
MatchAdapter adapter;
//Update array in mainactivity
if(futureMatches)
MainActivity.refreshMatches((MainActivity) getActivity());
else
MainActivity.refreshPastMatches((MainActivity) getActivity());
//put updated entries in the adapter
if(futureMatches)
adapter = new MatchAdapter (getActivity(), ((MainActivity)getActivity()).getMatches(), futureMatches);
else
adapter = new MatchAdapter (getActivity(), ((MainActivity)getActivity()).getPastMatches(), futureMatches);
setListAdapter(adapter);
updateList();
}
public void updateList(){
this.getActivity().runOnUiThread(new Runnable() {
public void run() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
getListView().refreshDrawableState();
getListView().invalidate();
}
});
}
public void onViewStateRestored(Bundle savedInstanceState)
{
super.onViewStateRestored(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
refresh();
}
My adapter class:
public class MatchAdapter extends BaseAdapter
{
private final Activity context;
private LayoutInflater inflater;
private boolean time = false;
private boolean futureMatchAdapter = true;
private ArrayList<String> matchList;
public MatchAdapter(Context cont, ArrayList<String> matches, boolean isFutureMatchAdapter)
{
matchList = matches;
futureMatchAdapter = isFutureMatchAdapter;
context = (Activity) cont;
inflater = LayoutInflater.from(context);
}
public int getCount()
{
return MatchAdapter.size();
}
#Override
public Object getItem(int position)
{
return MatchAdapter.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
String curPos = "";
curPos = MatchAdapter.get(position);
//times, future matches and past matches are handled differently
if(curPos.contains("Last updated:"))
time = true;
else
time = false;
if (convertView == null)
{
holder = new ViewHolder();
if(time)
{
convertView = inflater.inflate(R.layout.time_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_time);
}
else
{
if(futureMatchAdapter)
{
convertView = inflater.inflate(R.layout.feed_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_title);
}
else
{
convertView = inflater.inflate(R.layout.past_feed_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_title_past);
}
}
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
if(futureMatchAdapter)
holder.title.setText(matchList.get(position));
else
{
String matchString = matchList.get(position);
String alwaysVisible = matchString.replace("<", "vs");
alwaysVisible = alwaysVisible.replace(">", "vs");
if(!time)
alwaysVisible = alwaysVisible.substring(0, alwaysVisible.length() - 1);
holder.title.setText(alwaysVisible);
if(matchString.contains(">"))
{
String winner = matchString.substring(0, matchString.indexOf(">")) + "won!";
alwaysVisible = alwaysVisible.concat(winner);
}
else if(matchString.contains("<"))
{
String winner = matchString.substring(matchString.indexOf("<") + 2, matchString.indexOf("\n")) + " won!";
alwaysVisible = alwaysVisible.concat(winner);
}
holder.title.setOnClickListener(new pastMatchesOnclickListener(alwaysVisible)
{
public void onClick(View v)
{
((TextView) v).setText(matchWinner);
}
});
}
return convertView;
}
static class ViewHolder
{
TextView title;
TextView time;
}
}
did you try to update your list using the adapter?
dataadapter.clear();
dataadapter.addAll(allDataResult);
To show and update content in a ListView you should:
Create or find your ListView
Create your ListAdapter
Add your ListAdapter to your ListView
Add data to your ListAdapter
Call notifyDataSetChanged() on your ListAdapter.
Example:
ListView listView = (ListView) findViewById(R.id.listview);
MyListAdapter myListAdapter = new MyListAdapter();
listView.setAdapter(myListAdapter);
myListAdapter.add("Hello");
myListAdapter.add("Hi");
myListAdapter.notifyDataSetChanged();
Note: if you're using a subclass of ArrayAdapter the notifyDataSetChanged() will be called for you when you use the methods add(), addAll(), etc.

My ListView consist an ImageView and a TextView i need to get the Text from the TextView

My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> 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.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..

Categories

Resources