why is getView in ArrayAdapter class executing twice? - android

I have an app that is used by carers to get their rota for a particular day. The user sets a date in a datepicker. This date is passed to an activity called NfcScannerActivity. This activity calls a webservice using that date to get the rota. The rota data is an array. NfcScannerActivity passes this array to GetRota, which is an activity that has an array adapter with which shows the rota data.
All this works fine until in the getView method of GetRota i check if there is no data for a particular day. At this point I toast the user stating this fact and then re-call NfcScannerActivity with another date(hopefully a valid one). If there is no data the getView method seems to execute twice as the user is toasted twice. Why is this?
Snippets from NfcScannerActivity:
if(intent.getAction().equalsIgnoreCase("NEXT_ROTA")){
Log.e(TAG, "next rota action");
String date = intent.getStringExtra("nextRota");
getNextRota(date);
}
private void getNextRota(String stringExtra) {
String[] params = new String[]{nfcscannerapplication.getCarerID(), stringExtra};
AsyncGetRota agr = new AsyncGetRota();
agr.execute(params);
}
//////////snippet of async result of webservice call
...........
..........
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
if(isRotaArrayNull == false){
Intent intent = new Intent(NfcscannerActivity.this,
GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", rotaArray);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}else{...........
...........
.
snippet from GetRota, the activity that shows the rota
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
super.onNewIntent(intent);
}
#Override
protected void onResume(){
super.onResume();
Log.e(TAG, "global date in onresume getrota = " + nfcscannerapplication.getglobalDateTime());
array = (ArrayList<String[]>)getIntent().getBundleExtra("rotaArrayBundle").get("rotaArray");
Log.e(TAG, "array size in onresume = " + array.size());
..............
...............
/////////adapter class in getrota
private class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<?> list;
public MySimpleArrayAdapter(Context context, ArrayList<?> list) {
super(context, R.layout.rotarowlayout);
Log.e(TAG, "inside adapter constructor");
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rotarowlayout, parent,
false);
TextView startTime = (TextView) rowView
.findViewById(R.id.rowstarttime);
TextView duration = (TextView) rowView
.findViewById(R.id.rowduration);
TextView status = (TextView) rowView.findViewById(R.id.rowstatus);
TextView name = (TextView) rowView.findViewById(R.id.rowclientname);
//ImageView imageView = (ImageView)rowView.findViewById(R.id.rowimagestatus);
String record = list.get(position).toString();
rowView.setTag(record);
String[] itemsInRecord = record.split(",");
Log.e(TAG, "itemin record = " + itemsInRecord.length);
String[] recordItem = new String[itemsInRecord.length];
for (int x = 0; x < itemsInRecord.length; x++) {
recordItem[x] = itemsInRecord[x];
}
if(recordItem[9].toString().trim().equalsIgnoreCase("Out of range]")){
Toast.makeText(GetRota.this, "No rota available", Toast.LENGTH_LONG).show();
nfcscannerapplication.setGobalDateTime(new DateTime());
//onBackPressed();
DateTime globalDateTime = nfcscannerapplication.getglobalDateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
String formattedglobalDateTime = fmt.print(globalDateTime);
Intent i = new Intent(GetRota.this, NfcscannerActivity.class);
i.putExtra("nextRota", formattedglobalDateTime);
i.setAction("NEXT_ROTA");
startActivity(i);
}else if(recordItem[0].toString().trim().equalsIgnoreCase("[nodata")){
Toast.makeText(GetRota.this, "You have no calls", Toast.LENGTH_LONG).show();
Log.e(TAG, "you have no calls");
nfcscannerapplication.setGobalDateTime(new DateTime());
//onBackPressed();
DateTime globalDateTime = nfcscannerapplication.getglobalDateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
String formattedglobalDateTime = fmt.print(globalDateTime);
Intent i = new Intent(GetRota.this, NfcscannerActivity.class);
i.putExtra("nextRota", formattedglobalDateTime);
i.setAction("NEXT_ROTA");
startActivity(i);

You do not have control over the call of getView(). An arrayadapter acts as the bridge between the data and list view. When ever a list view loads, refreshes or there is some scrolling etc, the list view calls the get view method of the array adapter. So you have no control over when the getView() is called.
Moreover the getView() is called for each item of the list. So if there are two items who have recordItem[0] as no data, the toast will appear two times.
recorditem is an array that is created from a particular position of the ArrayList: list.
recorditem=list.get(position).split();
So row1 of the listview will hold a recorditem array, row2 will hold another recorditem array. Hence if recorditem[0] for both the rows have no data, then Toast will be shown multiple times.

This is because getView is something we cannot control. It is designed this way to consistently refresh views, as decided by the Android system.
Perhaps you can move the toast somewhere else in your code. You can check if there is no rota in onResume or onActivityResult. Generally, you should only be concerned with a specific item in your ArrayList in the getView method.

Related

ListView Generated from SQLite onClickListener() to take me to another activity based on where i clicked

I'm creating an android app. In this app, I have a ListView populated with data from SQLite. I am trying to add an onClickEventListener to each row of the ListView so that when a menu item is clicked it opens up another Activity with more information from the Database about the item clicked. I have succeeded in adding an event listener to the ListView, but I am not sure how to pass on database information depending on the list item clicked.
Here is my code:
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbh;
private ArrayList listItems = new ArrayList();
ArrayList<String[]> noteList;
private ArrayAdapter adapter;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbh = new DatabaseHelper(this);
dbh.open();
lv = (ListView) findViewById(R.id.noteListView);
noteList = dbh.selectAll();
String id = "";
String content = "";
for(int i = 0; i < noteList.size(); i++){
content = noteList.get(i)[1];
id = noteList.get(i)[0];
listItems.add(id + ", " + content);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(MainActivity.this, EditNote.class);
//i.putExtra();
startActivity(i);
}
});
}
}
In your case list has strings, so here is what you need to do:
String yourString = listItem.get(position);
i.putExtra("KEY", yourString);
startActivity(i);
And at the receiving activity you can retrieve as
intent intent = getIntent();
String yourString = intent.getExtras().getString("KEY");
EDIT: If your list is having some POJO class or simple class objects
You can pass to second activity like this
intent.putExtra("Your class", obj);
To retrieve object in second Activity
getIntent().getSerializableExtra("Your class");
EDIT: One important thing to remember.
If you passing a class object it must implement Serializable or Parcelable interface.
For eg
class Student implements Serializable{
}
You should make a custom adapter that extends the arrayadapter. Load everything from your database into an arraylist and use something like this:
// CODE DOES NOT WORK WITH YOUR CODE, IT'S JUST AN EXAMPLE
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}
...
lv.setAdapter(new MyClassAdapter(....));
In your OnItemClickListener you have the position of the clicked item so to get the object use MyClass object = lv.getItemAtPosition(position); and use that object to pass data to the new activity.
Intent intent = new Intent(getBaseContext(), my.class);
intent.putExtra("key", "value");
startActivity(intent);
To access
String s = getIntent().getStringExtra("key");
More: https://stackoverflow.com/a/2265712/2890156

Retrieving Parse ObjectID in OnTimeClickListener method

I want to retrieve an objectID of an item (to be specific, it's a class called "Room" in our Parse Model) clicked within a ListView.
And after that, I want to pass the retrieved ObjectID to another class using Intent.
I tried parse docs' getObjectId(); method but seems like it won't work.
How should I retrieve it?
Here's my code.
Button createBtn;
Button searchBtn;
Button myGroupBtn;
Button settingBtn;
String[] courses;
List<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
TextView textView;
// when CREAT button is tapped
public void createBtn(View view){
Intent i = new Intent(getApplicationContext(), Create.class);
// Removes animation
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
// when Setting button is tapped
public void settingBtn(View view) {
Intent i = new Intent(getApplicationContext(), Setting.class);
// Removes animation
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String courseName = intent.getStringExtra("courseName");
String courseNumber = intent.getStringExtra("courseNumber");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
// Making Links to Buttons on Create
createBtn = (Button) findViewById(R.id.createBtn);
searchBtn = (Button) findViewById(R.id.searchBtn);
myGroupBtn = (Button) findViewById(R.id.myGroupBtn);
settingBtn = (Button) findViewById(R.id.settingBtn);
//Chaning the button colors
searchBtn.setTextColor(0xFFFFFFFF);
createBtn.setTextColor(0xFFBFBFBF);
myGroupBtn.setTextColor(0xFFBFBFBF);
settingBtn.setTextColor(0xFFBFBFBF);
listView= (ListView)findViewById(R.id.listView);
textView= (TextView)findViewById(R.id.textView2);
textView.setText(courseName + " " + courseNumber);
listItems = new ArrayList<>();
ParseQuery<ParseObject> roomQuery = ParseQuery.getQuery("Room");
roomQuery.whereEqualTo("course" , courseName);
roomQuery.whereEqualTo("number" , courseNumber);
roomQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject room : objects) {
Log.i("Appinfo", String.valueOf(room.get("title")));
String stringToAdd = "";
String opened = String.valueOf(room.get("opened"));
String x;
if(opened.equals(true)){
x = "Open";
}else{
x = "Closed";
}
stringToAdd = stringToAdd + String.valueOf(room.get("studyDate")) + " " +
String.valueOf(room.get("category")) + " " + x + "\n"
+ String.valueOf(room.get("title")) +
" "
;
listItems.add(stringToAdd);
Log.i("Appinfo", "A");
}
} else {
Log.i("Appinfo", "B");
e.printStackTrace();
}
}
});
initList();
}
public void initList() {
Log.i("Appinfo", "C");
adapter = new ArrayAdapter<String>(this, R.layout.list_two, R.id.txtvw, listItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), Room.class);
String category = listItems.get(position);
}
}
Your problem is that you loose the objectId of Parse in your "Adapter": you use Strings and the basic android Adapter (there: new ArrayAdapter<String>(this, R.layout.list_two, R.id.txtvw, listItems);) to display your elements; the problem is that converting your complicated Room object into String which does not contain a lot of informations makes you loose the objectId you want to keep.
The solution to your problem is a very Android-ish pattern called Adapter or more specifically for this case a Custom Adapter which will explain to the device how to render your Room elements into every cell of your app's ListView.
It is extremely well documented (much better that everything I could possibility write in this post) so here is the generic official doc and here is, to me, the best tutorial to get the concept.
PS: for a beginner, I recommend the Base Adapter, it is, to me, the simplest :)

ArrayList not populated correctly from AsyncTask

I've an app that populates an ArrayList from a webservice. The webservice is called from an AsyncTask. The ArrayList is populated when i test it in the onPostExecute. The ArrayList is defined as an instance variable. Why when AsyncTask finishes is the arrayList populated but when i test the instance variable itself after, it's null. It seems like Async is not setting the values properly.
Once Async has finished i am passing the ArrayList to an arrayAdapter, but my listView is empty.
Tests: in onPostExecute
Log.e(TAG, "array from WS = " + array.size()); // returns 4
tests: in onCreate
Log.e(TAG, "checking to see if array is null " + array.size()); // returns 0
package com.carefreegroup;
public class GetRotaDetails extends NfcBaseActivity implements OnItemClickListener
{
ArrayList<ArrayList<String>> array;
MySimpleArrayAdapter arrayAdapter;
Intent intent;
private static final String TAG = GetRotaDetails.class.getSimpleName();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
array = new ArrayList<ArrayList<String>>();
nfcscannerapplication = (NfcScannerApplication) getApplication();
intent = this.getIntent();
setContentView(R.layout.getrotadetailslayout);
listView = (ListView) findViewById(R.id.getrotadetailslistview);
//set titlebar to carer's name
Cursor cursorCarerName = nfcscannerapplication.loginValidate.queryAllFromCarer();
cursorCarerName.moveToLast();
String carerTitleName = cursorCarerName.getString(cursorCarerName
.getColumnIndex(LoginValidate.C_CARER_NAME));
setTitle(carerTitleName + " is currently logged in");
callID = intent.getStringExtra("callIDExtra");
Log.e(TAG, "callID = " + callID);
String[] params = { callID };
AsyncGetRotaDetails agrd = new AsyncGetRotaDetails();
agrd.execute(params);
Log.e(TAG, "checking to see if array is null " + array.size());
if (arrayAdapter == null){
MySimpleArrayAdapter arrayAdapter = new MySimpleArrayAdapter(this, array);
listView.setAdapter(arrayAdapter);
}
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(this);
}// end of onCreate
#Override
protected void onResume() {
super.onResume();
}
private class AsyncGetRotaDetails extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String rotaDetails = null;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog
.show(GetRotaDetails.this, "Connecting to Server",
" retrieving rota details...", true);
};
#Override
protected String doInBackground(String... params) {
try {
Log.e(TAG, "inside doInBackground");
rotaDetails = nfcscannerapplication.loginWebservice.getRotaDetail(params[0]);
} catch (Exception e) {
e.printStackTrace();
}
return rotaDetails;
}
#Override
protected void onPostExecute(String xmlResult) {
super.onPostExecute(xmlResult);
if (progressDialog != null)
progressDialog.dismiss();
if (rotaDetails != null) {
RetrieveExtraDetails red = new RetrieveExtraDetails();
array = red.getExtraDetails(xmlResult);
Log.e(TAG, "array from WS = " + array.size());
} else {
AlertDialog alertDialog = new AlertDialog.Builder(
GetRotaDetails.this).create();
alertDialog.setTitle("Signal/Server Test");
alertDialog.setMessage("No Phone Signal or Server Problem");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
onStart();
}
});
alertDialog.show();
}
}// end of postExecute
}//end of Async
private class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<?> list;
public MySimpleArrayAdapter(Context context, ArrayList<?> list) {
super(context, R.layout.getrotadetailsrow);
Log.e(TAG, "inside adapter constructor");
this.context = context;
this.list = list;
}// end of constructor
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.getrotadetailsrow, parent,
false);
TextView recTypeID = (TextView) rowView
.findViewById(R.id.rectypeid);
TextView recType = (TextView) rowView
.findViewById(R.id.rectype);
TextView name = (TextView) rowView
.findViewById(R.id.name);
TextView relationship = (TextView) rowView
.findViewById(R.id.relationship);
TextView address = (TextView) rowView
.findViewById(R.id.address);
TextView postCode = (TextView) rowView
.findViewById(R.id.postcode);
TextView telNo = (TextView) rowView
.findViewById(R.id.telno);
TextView keySafe = (TextView) rowView
.findViewById(R.id.keysafe);
TextView notes = (TextView) rowView
.findViewById(R.id.notes);
TextView meds = (TextView) rowView
.findViewById(R.id.meds);
String record = list.get(position).toString();
Log.e(TAG, "record = " + record);
recTypeID.setText(record);
return super.getView(position, convertView, parent);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
}
}
Actually, AsyncTask runs asynchronously it is not a blocking call (like execute() method returns, after the execution of onPostExecute() ). So you need to notify adapter in onPostExecute() when your data is downloaded. Its a multi-thread related problem,when execute() line executed a thread is created for AsyncTask and onCreate()'s execution move to next line, so simultaneously, doInBackground() and onCreate() will be executing in AsyncTask thread and UI thread respectively.
Make your ListView a field in the class and
Use
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(this);
in onPostExecute(String result) method
but what i recommend is:
Use a loading spinner until the data is fetched and adapter is set, otherwise the behavior is the Activity shows up as empty and after 3-5 secs suddenly the whole list appears, which is a bad UX.
Usually we use Async Tasks without any loading spinner when the data being fetched is a small part of the UI, not a ListView which is a major component of the UI.
and don't check the length of the Array in onCreate(). It will always be 0. Because the code flow will be :
1. Create Array
2. Check its length in onCreate //0 as nothing is added yet
3. Add data to the Array in background
4. Check its length in onPostExecute(String result) //actual length

Can I have two different sources pass data to an array adapter?

I am trying to add data from two different sources to an array adapter. One source is from a spinner containing hard coded strings, the other is to allow the user to create their own string to pass to the array (via the adapter). Here is my code below. It appears to me that the array adapter can only except one data source according to the arguments that can be passed to it.......ie
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.alarmList, android.R.layout.simple_spinner_item );
Here I can only guess that the actual string input is gathered from......... android.R.layout.simple_spinner_item
Do I need to use another array adapter or is there a way to add my string variable to the adaoter as well as the item the user has chosen from the spinner? I've done some research here but drawing a blank!!Many thanks. Here's my code which tries to enter strings to adapter..........
public class NewAlarm extends Activity {
Spinner alarms;
//private Button b = (Button) findViewById(R.id.btnAddCustom);
final EditText et = (EditText) findViewById(R.id.edittext);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newalarm);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.alarmList, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//et.setText("name");
alarms = (Spinner) findViewById(R.id.cmbAlarms);
alarms.setAdapter(adapter);
}
public void addAlarm(View view) {
MainMenu.alarmList.add(new Alarm(alarms.getSelectedItem().toString()));
Toast.makeText(getApplicationContext(), "Added " + alarms.getSelectedItem().toString() + " alarm.", Toast.LENGTH_SHORT).show();
NewAlarm.this.finish();
}
public void addCustomAlarm (View view){
MainMenu.alarmList.add(new Alarm(et.getText().toString()));
}
}
And here's my array adapter code............
public View getView(final int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.alarm_item, null);
}
Thanks guys!!
// Get a handle on the UI controls
TextView name = (TextView) convertView.findViewById(R.id.txtAlarmName);
final TextView timeStamp = (TextView) convertView.findViewById(R.id.txtTimeStamp);
// if the value of the timestamp from the alarm at the position selected is not a null value then set the text label to the alarm timestamp value
if (MainMenu.alarmList.get(position).getTimeStamp() != null)
{
timeStamp.setText(MainMenu.alarmList.get(position).getTimeStamp().toString());
}
// Set the alarm name
name.setText(listItems.get(position).getName());
// Get a handle on the button
Button btnCheckNow = (Button) convertView.findViewById(R.id.btnCheckNow);
btnCheckNow.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Set the timestamp of the alarm object at the selected position
MainMenu.alarmList.get(position).setTimeStamp();
// Set the timestamp label
timeStamp.setText(MainMenu.alarmList.get(position).getTimeStamp().toString());
}
});
return convertView;
}
Instead of calling ArrayAdapter.createFromResource(), import the array and add the string before creating the adapter :
CharSequence[] array = Arrays.asList(
getResources().getTextArray(R.array.alarmList));
List<CharSequence> list = new ArrayList<CharSequence>(array);
list.add("custom string");
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, list);

how to pull strings from an array adapted listview for a clicked list item

ok so i have an array adapted listview (the array adapting is done in another class).. i just got the click listener working for the list but now i want set it up so that when i click an item it pulls the strings from the clicked item and piggybacks them on the intent to a new activity.. i figure im supposed to use intent.putextra however im not sure how to pull the correct strings corresponding to the item that i click on.. my code is below.. im simply lost to be honest
//Initialize the ListView
lstTest = (ListView)findViewById(R.id.lstText);
//Initialize the ArrayList
alrts = new ArrayList<Alerts>();
//Initialize the array adapter notice with the listitems.xml layout
arrayAdapter = new AlertsAdapter(this, R.layout.listitems,alrts);
//Set the above adapter as the adapter for the list
lstTest.setAdapter(arrayAdapter);
//Set the click listener for the list
lstTest.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int item, long arg3) {
Intent intent = new Intent(
HomePageActivity.this,
PromotionActivity.class
);
finish();
startActivity(intent);
}
});
my alerts class..
public class Alerts {
public String cityid;
public String promoterid;
public String promoshortcontent;
public String promocontent;
public String promotitle;
public String locationid;
public String cover;
#Override
public String toString() {
return "City: " +cityid+ " Promoter: " +promoterid+ "Short Promotion: " +promoshortcontent+ "Promotion: " +promocontent+ "Title: " +promotitle+ "Location: " +locationid+ "Cover: " +cover+ "$";
}
}
anddddd my alertsadapter class..
public class AlertsAdapter extends ArrayAdapter<Alerts> {
int resource;
String response;
Context context;
//Initialize adapter
public AlertsAdapter(Context context, int resource, List<Alerts> items) {
super(context, resource, items);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout alertView;
//Get the current alert object
Alerts al = getItem(position);
//Inflate the view
if(convertView==null)
{
alertView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, alertView, true);
}
else
{
alertView = (LinearLayout) convertView;
}
//Get the text boxes from the listitem.xml file
TextView textPromo =(TextView)alertView.findViewById(R.id.txtPromo);
TextView textPromoter =(TextView)alertView.findViewById(R.id.txtPromoter);
TextView textLocation =(TextView)alertView.findViewById(R.id.txtLocation);
//Assign the appropriate data from our alert object above
textPromo.setText(al.promocontent);
textPromoter.setText(al.promoterid);
textLocation.setText(al.locationid);
return alertView;
}
}
You need to use the onItemClick event's parameters
a full more readable param enum with param name is
(AdapterView<?> parent, View view, int pos, long id)
that means you have the pos param that indicated the position in the adapter.
What you have to do is:
jump to pos in the adapter
read out the values from the adapter
use putExtra to signup for the intent
had an epiphany over the weekend about how to fix this problem and i finally found a good work around for my app.. i know it isnt optimal because i hard coded the number 100 into it but for my uses as of now i know i wont ever have that many list items..
i added these 2 bits of code to my alertsadapter class
int startzero = 0;
public static String[][] promomatrix = new String[6][100];
and
promomatrix[0][startzero] = al.cityid;
promomatrix[1][startzero] = al.promoterid;
promomatrix[2][startzero] = al.promocontent;
promomatrix[3][startzero] = al.promotitle;
promomatrix[4][startzero] = al.locationid;
promomatrix[5][startzero] = al.cover;
startzero++;
then went to my homepageactivity class and added this to the click listener
Intent intent = new Intent(
HomePageActivity.this,PromotionActivity.class);
intent.putExtra("listitemcity", AlertsAdapter.promomatrix[0][pos]);
intent.putExtra("listitempromoter", AlertsAdapter.promomatrix[1][pos]);
intent.putExtra("listitemcontent", AlertsAdapter.promomatrix[2][pos]);
intent.putExtra("listitemtitle", AlertsAdapter.promomatrix[3][pos]);
intent.putExtra("listitemlocation", AlertsAdapter.promomatrix[4][pos]);
intent.putExtra("listitemcover", AlertsAdapter.promomatrix[5][pos]);
finish();
startActivity(intent);
and finally went to my promotionactivity (where i was trying to send the strings) and added this
Bundle extras = getIntent().getExtras();
if (extras == null){
return;
}
String listitemcity = extras.getString("listitemcity");
String listitempromoter = extras.getString("listitempromoter");
String listitemcontent = extras.getString("listitemcontent");
String listitemtitle = extras.getString("listitemtitle");
String listitemlocation = extras.getString("listitemlocation");
String listitemcover = extras.getString("listitemcover");
worked like a charm.. i hope this helps someone :)

Categories

Resources