how to hide textview whose value is null in customadapter - android

Please tell me how to hide the textview when it sometimes return null value through custom adapter. Here below is my code.
Android code:
public void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
search = jsonObj.getJSONArray(TAG_RESULT);
for (int i = 0; i < search.length(); i++) {
JSONObject c = search.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String phone = c.getString(TAG_PHONE);
String email = c.getString(TAG_EMAIL);
String description = c.getString(TAG_DESCRIPTION);
String postDate = c.getString(TAG_DATE);
String username=c.getString(TAG_USERNAME);
String city=c.getString(TAG_CITY);
String locality= c.getString(TAG_LOCALITY);
HashMap<String, String> search = new HashMap<String, String>();
search.put(TAG_TITLE, title);
search.put(TAG_PHONE, phone);
search.put(TAG_EMAIL, email);
search.put(TAG_DESCRIPTION, description);
search.put(TAG_DATE, postDate);
search.put(TAG_USERNAME, username);
search.put(TAG_CITY, city);
search.put(TAG_LOCALITY, locality); /* in some case it is null...at that time i want to hide tvlocality textview.*/
searchList.add(search);
}
ListAdapter adapter = new SimpleAdapter(
ResultDetail.this, searchList, R.layout.activity_show__result,
new String[]{TAG_TITLE, TAG_PHONE, TAG_EMAIL, TAG_DESCRIPTION, TAG_DATE, TAG_USERNAME, TAG_CITY, TAG_LOCALITY},
new int[]{R.id.tvTitle, R.id.tvMobile, R.id.tvEmail, R.id.tvDesp, R.id.tvDate, R.id.tvUserName, R.id.tvCityName, R.id.tvLocality}
);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
i am showing this result in listview .

Or simply override the getView(....) method like below example
ListAdapter adapter = new SimpleAdapter(this, searchList, R.layout.your_adapter_view, new String[]{"city"
}, new int[]{R.id.city}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.your_adapter_view, null);
holder.textView = (TextView) v.findViewById(R.id.city);
//other stuff
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
Map<String, String> data = searchList.get(position);
if (!TextUtils.isEmpty(data.get("city"))) {
holder.textView.setText(data.get("city"));
holder.textView.setVisibility(View.VISIBLE);
} else {
holder.textView.setVisibility(View.GONE);
}
//do the same thing for other possible views.
return v;
}
class ViewHolder {
TextView textView;
//your other views
}
};
I prefer TextUtils.isEmpty(str) for null and empty check.
Returns true if the string is null or 0-length.

Use below code in Adapter
if(textView.getText().toString()==null || textView.getText().toString().isEmpty() ){
textView.setVisibility(View.GONE);
}
else
{
textView.setText(searchList.get(position).get(TAG_TITLE));
}

You need to create a custom adapter, then inside getView() method you can change the TextView visibility depending on your items value.
public View getView (int position, View convertView, ViewGroup parent){
//...
if( yourItem == null ){
textView.setVisibility(View.INVISIBLE); // or GONE if you want
} else {
textView.setVisibility(View.VISIBLE);
}
//....
}

Related

Listview is showing only one row when showing json data in android

I'm trying to show json data in listview in android. I'm getting json data perfectly but when i'm trying to show it in listview just getting only one row.
And i want to show data of each row in an activity as per item click. Here i'm not understanding how to pass the data from json depending on which item is clicked.
here is my code:
public class CustomAdapter extends ArrayAdapter {
List list = new ArrayList();
public CustomAdapter(Context context, int resource) {
super(context, resource);
}
public void add(DataProvider dataProvider) {
super.add(dataProvider);
list.add(dataProvider);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row = convertView;
dataProviderHolder holder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_list, parent, false);
holder = new dataProviderHolder();
holder.name = (TextView) row.findViewById(R.id.name);
holder.subject = (TextView) row.findViewById(R.id.subject);
holder.date = (TextView) row.findViewById(R.id.date);
holder.time = (TextView) row.findViewById(R.id.tim);
row.setTag(holder);
} else {
holder = (dataProviderHolder) row.getTag();
}
DataProvider provider = (DataProvider) this.getItem(position);
holder.name.setText(provider.getName());
holder.subject.setText(provider.getSubject());
holder.date.setText(provider.getDate());
holder.time.setText(provider.getTime());
return row;
}
static class dataProviderHolder {
TextView name, subject, date, time;
}
}
Json parsing :
listView = (ListView) findViewById(R.id.list);
sessionManager = new SessionManager(this);
listView.setAdapter(customAdapter);
HashMap<String, String> user = sessionManager.getUserDetails();
json_string = user.get(SessionManager.JSON_STRING);
try {
String name, subject, message, date, time;
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("message");
int count = 0;
while (count < jsonObject.length()) {
JSONObject object = jsonArray.getJSONObject(count);
name = object.getString("name");
subject = object.getString("subject");
message = object.getString("message");
date = object.getString("date");
time = object.getString("time");
sessionManager.getJsonMesssage(message);
DataProvider dataProvider = new DataProvider(name, subject, date, time);
customAdapter.add(dataProvider);
count++;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> user = sessionManager.getUserDetails();
String message = user.get(SessionManager.JSON_MESSAGE);
Intent i = new Intent(MessageList.this, MessageDetails.class);
i.putExtra("message", message);
startActivity(i);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all, do not put listview.setOnItemClickListener in a loop. That does nothing. Instead add it in your getView() method of adapter.`
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> user = sessionManager.getUserDetails();
String message = user.get(SessionManager.JSON_MESSAGE);
Intent i = new Intent(context, MessageDetails.class);
i.putExtra("message", message);
startActivity(i);
}
});
Then, set your adapter after adding all the list items in while loop.

Different text color each item of listview when populating using simple adapter

i'm trying to set different text color of each item inside the listview when populating the item like the pict below, but i can't make it work,
the idea is if the number of "Rata-Rata" exceed 75 then the text color will be set to black, but if below it will be set to red.
here's my code, i'm overriding the getview method :
calonSiswa.add(map);
list = (ListView) findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(SeleksiNilai.this,
calonSiswa,
R.layout.activity_seleksi_nilai_single_item_view,
new String[] {
TAG_NO_URUTAN, TAG_NO_PENDAFTARAN,
TAG_NAMA_LENGKAP, TAG_JURUSAN,
TAG_RATA_RATA_NILAI, TAG_CARA_SELEKSI
},
new int[] {
R.id.nomorUrutan, R.id.noPendaftar,
R.id.namaPendaftar, R.id.jurusanPendaftar,
R.id.rataRataNilai, R.id.caraSeleksi
}) {
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
View view = super.getView(position, convertView,
parent);
float ratarata = Float.parseFloat(rata_rata);
int posisi = position;
int textColorId = R.color.black;
TextView text;
text = (TextView) view
.findViewById(R.id.noPendaftar);
if (ratarata <= 75) {
textColorId = R.color.red;
} else if (ratarata >= 75) {
textColorId = R.color.black;
}
text.setTextColor(getResources().getColor(
textColorId));
return view;
}
};
here's another pict if i change the order from lowest to highest number, it seems the problem is whenever the last number exceed or below 75, it will change all item color inside listview, not the specific position
here's the complete code :
private class GetData extends AsyncTask < String, String, JSONObject > {
private ProgressDialog pDialog;
String nomor, no_pendaftaran, nama_lengkap, jurusan, rata_rata, cara_seleksi;
#
Override
protected void onPreExecute() {
super.onPreExecute();
noPendaftaran = (TextView) findViewById(R.id.noPendaftar);
namaPendaftar = (TextView) findViewById(R.id.namaPendaftar);
statusProses = (TextView) findViewById(R.id.rataRataNilai);
pDialog = new ProgressDialog(SeleksiNilai.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#
Override
protected JSONObject doInBackground(String...args) {
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#
Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
pendaftar = json.getJSONArray(TAG_OS);
for (int i = 0; i < pendaftar.length(); i++) {
JSONObject c = pendaftar.getJSONObject(i);
// Storing JSON item in a Variable
nomor = String.valueOf(i + 1);
no_pendaftaran = c.getString(TAG_NO_PENDAFTARAN);
nama_lengkap = c.getString(TAG_NAMA_LENGKAP);
jurusan = c.getString(TAG_JURUSAN);
rata_rata = c.getString(TAG_RATA_RATA_NILAI);
cara_seleksi = c.getString(TAG_CARA_SELEKSI);
// Adding value HashMap key => value
HashMap < String, String > map = new HashMap < String, String > ();
map.put(TAG_NO_URUTAN, nomor);
map.put(TAG_NO_PENDAFTARAN, no_pendaftaran);
map.put(TAG_NAMA_LENGKAP, nama_lengkap);
map.put(TAG_JURUSAN, jurusan);
map.put(TAG_RATA_RATA_NILAI, rata_rata);
map.put(TAG_CARA_SELEKSI, cara_seleksi);
/*map.put(TAG_STATUS_PROSES, status_proses);*/
calonSiswa.add(map);
list = (ListView) findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(
SeleksiNilai.this, calonSiswa,
R.layout.activity_seleksi_nilai_single_item_view,
new String[] {
TAG_NO_URUTAN, TAG_NO_PENDAFTARAN, TAG_NAMA_LENGKAP, TAG_JURUSAN, TAG_RATA_RATA_NILAI, TAG_CARA_SELEKSI
},
new int[] {
R.id.nomorUrutan, R.id.noPendaftar, R.id.namaPendaftar, R.id.jurusanPendaftar, R.id.rataRataNilai, R.id.caraSeleksi
}) {#
Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
float ratarata = Float.parseFloat(rata_rata);
int posisi = position;
int textColorId = R.color.black;
TextView text;
text = (TextView) view.findViewById(R.id.noPendaftar);
if (ratarata <= 75) {
textColorId = R.color.red;
} else if (ratarata >= 75) {
textColorId = R.color.black;
}
text.setTextColor(getResources().getColor(textColorId));
return view;
}
};
list.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Get "rata_rata" by position in getView().
rata_rata = calonSiswa.get(position).get(TAG_RATA_RATA_NILAI);
int textColorId;
TextView text; //add this lines in global
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
float ratarata = Float.parseFloat(rata_rata);
int posisi = position;
text = (TextView) view.findViewById(R.id.noPendaftar);
if (ratarata <= 75)
{
textColorId = R.color.red;
} else {
textColorId = R.color.black;
}
text.setTextColor(getResources().getColor(textColorId));
return view;
}
};
that's obvious, your call the setAdapter method in the loop, the value of ratarata is always the last one
try this way may help u
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
View view = super.getView(position, convertView,
parent);
text1 =(TextView)view.findViewById(R.id.noPendaftar);
if (ratarata <= 75) {
textColorId = R.color.red;
text1.setTextColor(textColorId);
} else if (ratarata >= 75) {
textColorId = R.color.black;
text1.setTextColor(textColorId);
}
//set the tag of position
view.setTag(position);
return view;
}
};
the problem solved, thanks to situee, get the rata_rata value using
rata_rata = calonSiswa.get(position).get(TAG_RATA_RATA_NILAI);
so here's the code :
#
Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
pendaftar = json.getJSONArray(TAG_OS);
for (int i = 0; i < pendaftar.length(); i++) {
JSONObject c = pendaftar.getJSONObject(i);
// Storing JSON item in a Variable
nomor = String.valueOf(i + 1);
no_pendaftaran = c.getString(TAG_NO_PENDAFTARAN);
nama_lengkap = c.getString(TAG_NAMA_LENGKAP);
jurusan = c.getString(TAG_JURUSAN);
rata_rata = c.getString(TAG_RATA_RATA_NILAI);
cara_seleksi = c.getString(TAG_CARA_SELEKSI);
// Adding value HashMap key => value
HashMap < String, String > map = new HashMap < String, String > ();
map.put(TAG_NO_URUTAN, nomor);
map.put(TAG_NO_PENDAFTARAN, no_pendaftaran);
map.put(TAG_NAMA_LENGKAP, nama_lengkap);
map.put(TAG_JURUSAN, jurusan);
map.put(TAG_RATA_RATA_NILAI, rata_rata);
map.put(TAG_CARA_SELEKSI, cara_seleksi);
calonSiswa.add(map);
ListView list = (ListView) findViewById(R.id.list);
adapter = new SimpleAdapter(
SeleksiNilai.this, calonSiswa,
R.layout.activity_seleksi_nilai_single_item_view,
new String[] {
TAG_NO_URUTAN, TAG_NO_PENDAFTARAN, TAG_NAMA_LENGKAP, TAG_JURUSAN, TAG_RATA_RATA_NILAI, TAG_CARA_SELEKSI
},
new int[] {
R.id.nomorUrutan, R.id.noPendaftar, R.id.namaPendaftar, R.id.jurusanPendaftar, R.id.rataRataNilai, R.id.caraSeleksi
}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
//HERE I ADD THE CODE FROM situee
String rata_rata1 = calonSiswa.get(position).get(TAG_RATA_RATA_NILAI);
float ratarata = Float.parseFloat(rata_rata1);
//////////////////////////
int textColorId;
TextView text;
text = (TextView) view.findViewById(R.id.noPendaftar);
if (ratarata <= 75) {
textColorId = R.color.red;
} else {
textColorId = R.color.black;
}
text.setTextColor(getResources().getColor(textColorId));
return view;
}
};
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#
Override
public void onItemClick(AdapterView <? > parent,
View view, int position, long id) {
// TODO Auto-generated method stub
noPendaftaranTerpilih = calonSiswa.get(position).get("no_pendaftaran");
Intent i = new Intent(SeleksiNilai.this, SeleksiNilaiLanjutan.class);
startActivity(i);
/*Toast.makeText(SeleksiNilai.this,"You Clicked at "+ calonSiswa.get(position).get("no_pendaftaran"),
Toast.LENGTH_SHORT).show();*/
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
it works like a charm, thanks everyone.

insert value to arraylist hashmap base on position

Continue from my post about how can I use HashMap for BaseAdapter, I have another problem here. How can I insert or replace the value on arraylist hashmap?
I tried using mylist.set(position, map); but it's not working
my full code:
This code is to get data from database and put it on mylist
class LoadFarmasi extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LihatFarmasiObat.this);
pDialog.setMessage(Html.fromHtml("Ambil Data Farmasi..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places XML
* */
protected String doInBackground(String... args) {
String xml;
try {
// ----------------------------Make data Parameter for query-----------------
List<BasicNameValuePair> postsku = new ArrayList<BasicNameValuePair>(0);
postsku.add(new BasicNameValuePair("noregis", noregis));
parser = new XMLParser();
xml = parser.getXmlFromUrlWithPost(URL_FARMASI,postsku); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
nodes = doc.getElementsByTagName("result");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all hospitals
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
int leng = nodes.getLength();
for (int i = 0; i < leng; i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
map.put("nama", parser.getValue(e, "nama"));
map.put("in", parser.getValue(e, "in"));
map.put("id", "");
mylist.add(map);
}
}
});
}
}
This is for insert value on edittext and put the value to mylist
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < 20; i++) {
new LoadFarmasi().execute();
}
notifyDataSetChanged();
}
public int getCount() {
return mylist.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
HashMap<String,String> map =mylist.get(position);
// position gives you the index
String value = map.get("nama");
String value2 = map.get("in");
String value3 = map.get("id");
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_farmasi_obat, null);
holder.caption = (EditText) convertView.findViewById(R.id.editText1);
holder.txtNama = (TextView) convertView.findViewById(R.id.txtListFarmasiNama);
holder.txtIn = (TextView) convertView.findViewById(R.id.txtListFarmasiIn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Fill EditText with the value you have in data source
holder.txtNama.setText(value);
holder.txtIn.setText(value2);
holder.caption.setText(value3);
holder.txtNama.setId(position);
holder.txtIn.setId(position);
holder.caption.setId(position);
//we need to update adapter once we finish with editing
holder.caption.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final EditText Caption = (EditText) v;
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", Caption.getText().toString());
mylist.set(position, map);
}
}
});
return convertView;
}
}
class ViewHolder {
EditText caption;
TextView txtNama;
TextView txtIn;
}
// try this way here i also know what are changes i have done in your code.
please replace your getView() and let me know still have any problem
First of all i have add final keyword to position and hash so it can be access in onFocusChange()
Second one is we direct access position rather getting from view getTag Id.
Third one is i have replace id value in hashmap and notify adapter so update data reflected in list.
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final HashMap<String,String> map =mylist.get(position);
// position gives you the index
String value = map.get("nama");
String value2 = map.get("in");
String value3 = map.get("id");
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_farmasi_obat, null);
holder.caption = (EditText) convertView.findViewById(R.id.editText1);
holder.txtNama = (TextView) convertView.findViewById(R.id.txtListFarmasiNama);
holder.txtIn = (TextView) convertView.findViewById(R.id.txtListFarmasiIn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Fill EditText with the value you have in data source
holder.txtNama.setText(value);
holder.txtIn.setText(value2);
holder.caption.setText(value3);
holder.txtNama.setId(position);
holder.txtIn.setId(position);
holder.caption.setId(position);
//we need to update adapter once we finish with editing
holder.caption.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
EditText Caption = (EditText) v;
map.put("id", Caption.getText().toString());
notifyDataSetChanged();
}
}
});
convertView.setTag(holder);
return convertView;
}

how can I use HashMap for BaseAdapter

Originally, I'm using hashmap using SimpleAdapter, like this:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
int leng = nodes.getLength();
for (int i = 0; i < leng; i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
map.put("nama", parser.getValue(e, "nama"));
map.put("in", parser.getValue(e, "in"));
mylist.add(map);
}
// Adding myList to ListView
ListAdapter adapter = new SimpleAdapter(LihatFarmasiObat.this, mylist,
R.layout.list_farmasi_obat, new String[] { "nama", "in" },
new int[] {R.id.txtListFarmasiNama, R.id.txtListFarmasiIn});
listFarmasiObat.setAdapter(adapter);
But now I'm trying to put a EditText inside ListView, and I got this code from here.
I tried that code and it works, (I need to change some but the code is working).
and but when I tried to combine it with my own code, I got an error Cannot cast from HashMap to LihatFarmasiObat.ListItem on these line:
holder.caption.setText(((ListItem)mylist.get(position)).caption);
//It got an error on mylist
holder.caption.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem)mylist.get(position)).caption = Caption.getText().toString();
// it also got same error on mylist.
}
}
});
return convertView;
class ListItem {
String caption;
//this is the problem (I think) I don't know how to make this hashmap
}
I already try to change it to any other way but it's not working.
and this is my full code:
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
new LoadFarmasi().execute(); // This is for filling mylist with hashmap
notifyDataSetChanged();
}
public int getCount() {
return mylist.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_farmasi_obat, null);
holder.caption = (EditText) convertView.findViewById(R.id.editText1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Fill EditText with the value you have in data source
holder.caption.setText(((ListItem)mylist.get(position)).caption);
holder.caption.setId(position);
//we need to update adapter once we finish with editing
holder.caption.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem)mylist.get(position)).caption = Caption.getText().toString();
}
}
});
return convertView;
}
}
class ViewHolder {
EditText caption;
}
class ListItem {
String caption;
}
Can someone help me? I'm struggle with this for a few days
In getView you need to use
HashMap<String,String> map =mylist.get(position);
// position gives you the index
String value = map.get("nama");
String value2 = map.get("in");
Now use the String's and set it to views accordingly
You have arraylist of hashmap.

Pass a variable value from Base Adapter to activity

I have a set a variable in my Base Adapter class, now I want to get(pass) this variable in my related Activity. I am not getting how to do this.
Here is my code.
public class TourDescAdapter extends BaseAdapter {
private List<Descriptions> descriptList;
private LayoutInflater mInflater;
ViewHolder holder;
#SuppressWarnings("unused")
private OnClickListener clickListener;
Activity context;
//TourDescription tourDesc;
ArrayList<HashMap<String, Object>> obj = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> discountedTourDetails = null;
String price = null, prodId = null;
String promoTourname, tourName;
public TourDescAdapter(List<Descriptions> descriptList,
TourDescription activity) {
this.context = activity;
this.descriptList = descriptList;
mInflater = LayoutInflater.from(activity);
clickListener = (OnClickListener) activity;
}
#Override
public int getCount() {
return this.descriptList.size();
}
#Override
public Object getItem(int position) {
return this.descriptList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.tourlist, null);
/****
* Creates a ViewHolder and store references to the two children
* views we want to bind data to
****/
holder = new ViewHolder();
holder.rlayout = (RelativeLayout) convertView
.findViewById(R.id.tourlayout);
holder.title = (TextView) convertView
.findViewById(R.id.tourtitletext);
holder.desc = (TextView) convertView.findViewById(R.id.tourdes);
holder.amountButton = (Button) convertView
.findViewById(R.id.amtBtn);
holder.pinButton = (Button) convertView.findViewById(R.id.pinBtn);
holder.arrowButton = (Button)convertView.findViewById(R.id.arrowBtn);
holder.serialText = (EditText)convertView.findViewById(R.id.pinText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText((String) descriptList.get(position)
.getImageTitle());
holder.desc.setText((String) descriptList.get(position)
.getImageDescription());
((ImageView) holder.rlayout.getChildAt(0)).setImageBitmap(BitmapFactory
.decodeFile((RaconTours.PATH + RaconTours.city + File.separator
+ TourDescription.currentTour.getObjtourName()
+ File.separator + descriptList.get(position)
.getImagePath().split("/")[2]).replace(" ", "_")));
if (position == 0) {
SharedPreferences settings = context.getSharedPreferences("downloadDetails", 0);
String isTourDownloaded = settings.getString(TourDescription.currentTour.getObjtourName(), "");
if (isTourDownloaded.equals("true")) {
//if (!(TourDescription.downloadFile.exists())||TourDescription.downloadFile.exists() == false ) {
//if (TourDescription.currentTour.getIsTourDownloaded() == true) {
//holder.pinButton.setVisibility(View.INVISIBLE);
//holder.arrowButton.setVisibility(View.INVISIBLE);
//holder.serialText.setVisibility(View.INVISIBLE);
}
holder.amountButton.setVisibility(View.VISIBLE);
holder.amountButton.setText("Start");
} else {
File promoPlistPath = new File(RaconTours.PATH + "promocode.txt");
checkPromoCode(promoPlistPath);
if (discountedTourDetails != null) {
tourName = (String) discountedTourDetails.get("promoTour");
price = (String) discountedTourDetails.get("discountPrice");
prodId = (String) discountedTourDetails.get("disProId");
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText("$" +price);
//promoPlistPath.delete();
} else {
// Enabling the two buttons
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText(TourDescription.currentTour
.getObjPrice());
}
}
} else {
holder.amountButton.setVisibility(View.INVISIBLE);
holder.pinButton.setVisibility(View.INVISIBLE);
holder.arrowButton.setVisibility(View.INVISIBLE);
holder.serialText.setVisibility(View.INVISIBLE);
holder.title.setBackgroundColor(Color.WHITE);
holder.title.setTextColor(Color.BLACK);
holder.title.setGravity(Gravity.CENTER_HORIZONTAL);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.INVISIBLE);
}
return convertView;
}
#SuppressWarnings("unchecked")
private void checkPromoCode(File promoPlistPath) {
if (promoPlistPath.exists()) {
try {
ObjectInputStream inStream = new ObjectInputStream(
new FileInputStream(promoPlistPath));
obj = (ArrayList<HashMap<String, Object>>) inStream
.readObject();
for (HashMap<String, Object> tmpObj : obj) {
promoTourname = (String) tmpObj.get("promoTour");
if (promoTourname.equals(TourDescription.currentTour.getObjtourName())) {
discountedTourDetails = tmpObj;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ViewHolder {
Button pinButton;
Button amountButton;
RelativeLayout rlayout;
TextView title;
TextView desc;
Button arrowButton;
EditText serialText;
}
}
Here
prodId = (String) discountedTourDetails.get("disProId");
I want to pass prodId to related activity.
Note: Base Adapter is called from the activity
adapter = new TourDescAdapter(currentTour.getListOfDescriptions(), this);
setListAdapter(adapter);
Any one can tell me how to do this?
Couldn't you just use String iGotTheString = adapter.prodId?

Categories

Resources