ListView with customView and onClickItemListener - java

i have problem with listview... i'm trying to add OnClickListener but in still doesn't work. I want to display another activity after click. Can somebody help me? I know that there are many of example, but it's doesn't work for my appl or i don't know how to use it in my example...
This is my LocationAdapter class:
public class LocationAdapter extends ArrayAdapter<LocationModel> {
int resource;
String response;
Context context;
private LayoutInflater mInflater;
public LocationAdapter(Context context, int resource, List<LocationModel> objects) {
super(context, resource, objects);
this.resource = resource;
mInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView titleGameName;
TextView distanceGame;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
LocationModel lm = (LocationModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.titleGameName = (TextView) convertView
.findViewById(R.id.it_location_title);
holder.distanceGame = (TextView) convertView
.findViewById(R.id.it_location_distance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleGameName.setText(lm.getGameName());
holder.distanceGame.setText(lm.getGameDistance()+" km");
return convertView;
}
}
This is my mainListView class:
public class SelectGameActivity extends Activity {
LocationManager lm;
GeoPoint userLocation;
ArrayList<LocationModel> locationArray = null;
LocationAdapter locationAdapter;
LocationList list;
ListView lv;
TextView loadingText;
TextView sprawdz;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectgame);
lv = (ListView) findViewById(R.id.list_nearme);
locationArray = new ArrayList<LocationModel>();
locationAdapter = new LocationAdapter(SelectGameActivity.this, R.layout.item, locationArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(locationAdapter);
lv.setItemsCanFocus(true);
String serverName = getResources().getString(R.string.serverAdress);
ApplicationController AC = (ApplicationController)getApplicationContext();
String idPlayer = AC.getIdPlayer();
int latitude = AC.getCurrentPositionLat();
int longitude = AC.getCurrentPositionLon();
int maxDistance = 99999999;
try {
new LocationSync().execute("myserverName");
} catch(Exception e) {}
}
//this is connection with json
private class LocationSync extends AsyncTask<String, Integer, LocationList> {
protected LocationList doInBackground(String... urls) {
LocationList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, LocationList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(LocationList loclist) {
for(LocationModel lm : loclist.getLocations())
{
locationArray.add(lm);
}
locationAdapter.notifyDataSetChanged();
}
}
EDIT:: I have second problem... i want to get id from item (items are downloading from json url) This is my list:
I want to get for example: ID:159 for first item and send it to nextActivity.
I have also the controllerClass.java where i'm setting and getting selectedIdGame:
public String getIdGameSelected() {
return idGame;
}
public void setIdGameSelected(String idGame) {
this.idGame = idGame;
}
Is it good idea? Thanks for help.
Ok, it's done. i used:
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
String idGame = (String) ((TextView) v.findViewById(R.id.idGameSelected)).getText();
Thanks, Michal.

You could define an onItemClick on your adapter instance (i.e. in mainListView.java, just after lv.setAdapter):
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
Intent i = new Intent(v.getContext(), NextActivity.class);
startActivity(i);
}
});

lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Intent i = new Intent(view.getContext(), NextActivity.class);
startActivity(i);
}
});
I don't know why this wouldn't work, put it after the try{}catch{} block.

Related

How do I send the text of the ListView item that was clicked to my new activity?

I would like someone to click on an item in my ListView and then my new activity would start and the text of the item they clicked on should be set as the text of the TextView in my new activity. Currently with the following code, my TextView result is:
'com.example.draft.AnimalNames#31571cf'
Here is what I have in MainActivity.java:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedName = (list.getItemAtPosition(position).toString());
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("clickedName", clickedName);
startActivity(intent);
System.out.println(clickedName);
}
});
And in my new activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
Intent intent = getIntent();
String clickedName = intent.getStringExtra("clickedName");
animalName = findViewById(R.id.textView);
animalName.setText(clickedName);
}
And in my AnimalNames.java file:
public class AnimalNames {
private String animalName;
public AnimalNames(String animalName) {
this.animalName = animalName;
}
public String getanimalName() {
return this.animalName;
}
}
I don't think it's relevant to my question but here is my ListViewAdapter.java file:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList; // Declare a null variable
private ArrayList<AnimalNames> arraylist; // Declare a null array
public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
mContext = context;
this.animalNamesList = animalNamesList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AnimalNames>();
this.arraylist.addAll(animalNamesList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public AnimalNames getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_view_items, null); // Locate the TextViews in list_view_items.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(animalNamesList.get(position).getanimalName());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (AnimalNames wp : arraylist) {
if (wp.getanimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
String clickedName = (list.getItemAtPosition(position).toString());
By calling toString() method, it will give you the object reference, which is what you get in the TextView.
According to your code, if you wish to see the Animal name, you should do (and fix the method name to getAnimalName):
String clickedName = ((AnimalNames)list.getItemAtPosition(position)).getanimalName();
getItemAtPosition() returns an Object, so you need to cast it to the correct class.

fail to retrieve data to listview - android

[EDIT] I'm new to android development, so please bear with me. I have two java classes named Join Game, extends to AppCompatActivity and HintList,extends to ArrayAdapter<>. This is connected to a database. So maybe its one of the factors?
For the layout of join game, I have a listview
and for the layout of hintlist I have three textview.
The code goes this way
JoinGame
public class JoinGame extends AppCompatActivity {
ListView list;
String[] itemdescription = {};
String[] itemhints = {};
String[] itemlocasyon = {};
ProgressDialog progress;
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joingame);
Button schan = (Button)findViewById(R.id.tarascan);
schan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(JoinGame.this,ScanActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
progress = new ProgressDialog(this);
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
RequestFactory.joingameitems(JoinGame.this, RequestFactory.user_id, new RequestCallback<JSONArray>() {
#Override
public void onSuccess(final JSONArray response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
} catch (JSONException e) {
e.printStackTrace();
}
} ////////// below this is the adapter
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
}
});
}
#Override
public void onFailed(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(JoinGame.this, message, Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
HintList
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, null, true);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
}
I actually retrieved the data (here)
E/DB: [{"description":"chinese garter","location":"near Tricycle station","hint":"garter plus chinese"},{"description":"isang pinoy game","location":"near ....","hint":"may salitang baka"},{"description":"\"tinik\"","location":"below...","hint":"may salitang tinik"},{"description":"aka Tinubigan","location":"at the back...","hint":"katunog ng pintero"},{"description":"\"knock down the can\"","location":"near...","hint":"gumagamit ng lata"}]
but it doesnt display on my listview
I dont know anymore what I should do.
I actually tried making this (I added view)
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)view.findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
but it will only returns an error of java.lang.NullPointerException: Attempt to invoke virtual method
Change this:
View rowView = inflater.inflate(R.layout.hints_list, null, true);
to:
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
Modify your getView() method to:
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
try adding getCount
#Override
public int getCount() {
return itemHints.length;
}
Try to change your code to this
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
private LayoutInflater inflater=null;
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return itemHints.length;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
view=inflater.inflate(R.layout.hints_list, null, true);
holder = new ViewHolder(view);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
holder.itemDesc2.setText(itemDesc[position]);
holder.itemHint.setText(itemHints[position]);
holder.itemLocation2.setText(itemLocation[position]);
return view;
}
static class ViewHolder{
TextView itemDesc2,itemHint,itemLocation2;
ViewHolder(View view) {
itemDesc2 = (TextView)view.findViewById(R.id.itemdescription);
itemHint = (TextView)view.findViewById(R.id.itemhint);
itemLocation2 = (TextView)view.findViewById(R.id.itemlocation);
}
}
}
My suggestions is create a bean class (DetailsBean), used for setter and getter method, and also the ArrayList (details1).
List<DetailsBean> details1 = new ArrayList<>(); // declare this as global
Then add the bean to below code
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
// here the bean
DetailsBean dbean = new DetailsBean(itemDescription, itemhints, itemlocasyon);
details1.add(dbean); // add all the data to details1 ArrayList
HintList hladapt = new HintList(getActivity(), details1);
(ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
} catch (JSONException e) {
e.printStackTrace();
}
}
Your DetailsBean should looked like this
public class DetailsBean {
private String itemDescription="";
private String itemhints="";
private String itemlocasyon ="";
public DetailsBean(String description, String hints, String itemlocasyon) {
this.itemDescription=description;
.....
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDesription;
}
public String getItemDescription() {
return itemDescription;
}
....
}
Then your HintList
public class HintList extends BaseAdapter{
Activity context;
List<DetailsBean> details;
private LayoutInflater mInflater;
public CustomBaseAdapter(Activity context,List<DetailsBean> details) {
this.context = context;
this.details = details;
}
........
}
Add these Override methods in your adapter
#Override
public int getCount() {
return itemHints.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}

How to add OnItemClickListener on my CustomAdapter

I'm in a bind here, I wanted to integrate OnItemClickListener in my CustomAdapter, so when an item is click, it'll show some message or something. But I am not sure where to set it. I've look at bunch of tutorials and some post here but it only make me more confuse. So I need guidance on how and where would I need to set it to make it work. Here is my code:
MainActivity.java
ListView listView;
listView = (ListView) findViewById(R.id.list_item);
new ReadRSS(MainActivity.this, listView, "http://malaysiakini.com/en/news.rss").execute();
ReadRSS.java
#Override
protected void onPostExecute(Void aVoid) {
//Dismiss progress dialog
super.onPostExecute(aVoid);
progressDialog.dismiss();
if (feedItems != null) {
CustomAdapter customAdapter = new CustomAdapter(context,R.layout.activity_listview,feedItems);
listView.setAdapter(customAdapter);
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<FeedItem> {
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public CustomAdapter(Context context, int resource, List<FeedItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.activity_listview, null);
}
FeedItem p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.title_text);
TextView tt2 = (TextView) v.findViewById(R.id.date_text);
if (tt1 != null) {
tt1.setText(p.getTitle());
}
if (tt2 != null) {
tt2.setText(p.getPubDate());
}
}
return v;
}
}
Here is not the direct answer to your question, but my own code example so you can have a look at it and get the idea;
ListAdapter adapter = new ArrayAdapter<String>(this,R.layout.listword,R.id.wordView1, companies);
ListView listView = (ListView) findViewById(R.id.secondListView1);
listView.setAdapter(adapter);
// Item Click listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> ok, View v, int position, long id){
// Do your stuff here
}
});
You don't set it inside the adapter, but inside your activity where you define you ListView :
ListView listView = (ListView)findViewById(R.id.list_item);
new ReadRSS(MainActivity.this, listView, "http://malaysiakini.com/en/news.rss").execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// your code here
}
}
You can perform task on individual component of CustomAdapter class. Check below code.
public class CustomAdapter extends ArrayAdapter<FeedItem> {
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public CustomAdapter(Context context, int resource, List<FeedItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.activity_listview, null);
}
FeedItem p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.title_text);
TextView tt2 = (TextView) v.findViewById(R.id.date_text);
if (tt1 != null) {
tt1.setText(p.getTitle());
}
if (tt2 != null) {
tt2.setText(p.getPubDate());
}
tt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Perform your task
});
tt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Perform your task
});
}
return v;
}
}
Just like this,hope it helps:
public class CustomAdapter extends ArrayAdapter<FeedItem> implements OnClickListener{
private Context mContext;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mContext = context;
}
public CustomAdapter(Context context, int resource, List<FeedItem> items) {
super(context, resource, items);
mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.activity_listview, null);
}
FeedItem p = getItem(position);
v.setTag(p);
v.setOnClickListener(this);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.title_text);
TextView tt2 = (TextView) v.findViewById(R.id.date_text);
if (tt1 != null) {
tt1.setText(p.getTitle());
}
if (tt2 != null) {
tt2.setText(p.getPubDate());
}
}
return v;
}
#Override
public void onClick(View v){
FeedItem p = (FeedItem) v.getTag();
// TODO,do something with p and mContext
}
}
But I think you should use listview.setOnItemClickListener(listener) to do this work.
Write this code on your activity below of your set adapter method.
Set Adapter Method
private void setAdapter() {
try {
DoctorAppointmentListAdapter doctorAppointmentListAdapter = new DoctorAppointmentListAdapter(getContext(), doctorAppointmentObjectArrayList, selectedItemClickListener, screen);
appointmentListView.setAdapter(doctorAppointmentListAdapter);
}catch (Exception e){}
}
Costume Click Methods
//ListAdapter Click Listener
DoctorAppointmentListAdapter.SelectItemClickListener selectedItemClickListener = new DoctorAppointmentListAdapter.SelectItemClickListener() {
#Override
public void itemClickedAtIndex(int index, String operation) {
if (operation.equalsIgnoreCase("00")) {
m_handler.removeCallbacks(m_handlerTask);
viewDetailsScreen(index);
} else if (operation.equalsIgnoreCase("11")) {
m_handler.removeCallbacks(m_handlerTask);
//Video Call Operation
patirntId = doctorAppointmentObjectArrayList.get(index).getAppointment_patient_id();
videocallService(doctorAppointmentObjectArrayList.get(index).getAppointment_patient_id(), doctorAppointmentObjectArrayList.get(index).getAppointment_id());
} else if (operation.equalsIgnoreCase("33")) {
m_handler.removeCallbacks(m_handlerTask);
//Video Call Operation
patirntId = doctorAppointmentObjectArrayList.get(index).getAppointment_patient_id();
videocallCompletedService(doctorAppointmentObjectArrayList.get(index).getAppointment_patient_id(), doctorAppointmentObjectArrayList.get(index).getAppointment_id());
} else if (operation.equalsIgnoreCase("22")) {
m_handler.removeCallbacks(m_handlerTask);
//Phone Call Operation
if (doctorAppointmentObjectArrayList.get(index).getPatient_contact_no().length() > 0) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + doctorAppointmentObjectArrayList.get(index).getPatient_contact_no()));
startActivity(intent);
} else {
}
}
}
};
This is Adapter Class
public class DoctorAppointmentListAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
private Context context;
private int screen;
private ArrayList<DoctorAppointmentObject> doctorAppointmentObjectArrayList;
private SelectItemClickListener itemClickListener;
public DoctorAppointmentListAdapter(Context context, ArrayList<DoctorAppointmentObject> doctorAppointmentObjectArrayList, SelectItemClickListener listener, int screen) {
this.context = context;
this.screen = screen;
this.doctorAppointmentObjectArrayList = doctorAppointmentObjectArrayList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
if (itemClickListener != null) {
itemClickListener = null;
}
itemClickListener = listener;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return doctorAppointmentObjectArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
public interface SelectItemClickListener {
public void itemClickedAtIndex(int index, String operation);
}
private class ViewHolder {
private TextView doctorNameTextView, numberTextView, datetimeTextView, enteryTextView;
private TextView viewDetailTextView, videoCallTextView, phoneCallTextView;
private CircleImageView profile_image;
private ImageView onlineStatusImageView;
private CircularProgressView progress_view;
}
ViewHolder holder = null;
#Override
public View getView(final int i, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.adapter_doctor_appointment_list, parent, false);
holder = new ViewHolder();
holder.doctorNameTextView = (TextView) convertView
.findViewById(R.id.doctorNameTextView);
holder.numberTextView = (TextView) convertView
.findViewById(R.id.numberTextView);
holder.datetimeTextView = (TextView) convertView
.findViewById(R.id.datetimeTextView);
holder.enteryTextView = (TextView) convertView
.findViewById(R.id.enteryTextView);
holder.viewDetailTextView = (TextView) convertView
.findViewById(R.id.viewDetailTextView);
holder.videoCallTextView = (TextView) convertView
.findViewById(R.id.videoCallTextView);
holder.phoneCallTextView = (TextView) convertView
.findViewById(R.id.phoneCallTextView);
holder.profile_image = (CircleImageView) convertView
.findViewById(R.id.profile_image);
holder.progress_view = (CircularProgressView) convertView.findViewById(R.id.progress_view);
holder.onlineStatusImageView = (ImageView) convertView.findViewById(R.id.onlineStatusImageView);
holder.onlineStatusImageView.setVisibility(View.INVISIBLE);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (screen == 1) {
holder.videoCallTextView.setVisibility(View.GONE);
}
try {
Picasso.with(context).load(doctorAppointmentObjectArrayList.get(i).getPatient_profile_pic()).into(holder.profile_image, new Callback() {
#Override
public void onSuccess() {
holder.progress_view.setVisibility(View.GONE);
}
#Override
public void onError() {
holder.progress_view.setVisibility(View.GONE);
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
}
});
} catch (Exception e) {
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
holder.progress_view.setVisibility(View.GONE);
e.printStackTrace();
}
holder.doctorNameTextView.setText(doctorAppointmentObjectArrayList.get(i).getPatient_display_name());
holder.numberTextView.setText(doctorAppointmentObjectArrayList.get(i).getPatient_contact_no());
if (doctorAppointmentObjectArrayList.get(i).getAppointment_time().equalsIgnoreCase("")) {
holder.numberTextView.setText("");
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date testDate = null;
try {
testDate = sdf.parse(doctorAppointmentObjectArrayList.get(i).getAppointment_time());
} catch (Exception ex) {
ex.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
String newFormat = formatter.format(testDate);
holder.numberTextView.setText("" + newFormat);
}
holder.datetimeTextView.setText(doctorAppointmentObjectArrayList.get(i).getAppointment_reason());
if (screen==0){
holder.enteryTextView.setText("Entry Time :" + doctorAppointmentObjectArrayList.get(i).getAppointment_entry_time());
}else {
holder.enteryTextView.setText("");
}
holder.viewDetailTextView.setId(i);
holder.viewDetailTextView.setOnClickListener(viewDetailSelectedListener);
holder.videoCallTextView.setId(i);
holder.videoCallTextView.setOnClickListener(videoCallSelectedListener);
holder.phoneCallTextView.setId(i);
holder.phoneCallTextView.setOnClickListener(phoneCallSelectedListener);
return convertView;
}
View.OnClickListener viewDetailSelectedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int index = (Integer) v.getId();
itemClickListener.itemClickedAtIndex(index, "00");
} catch (Exception e) {
e.printStackTrace();
}
}
};
View.OnClickListener videoCallSelectedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int index = (Integer) v.getId();
if (screen == 2) {
itemClickListener.itemClickedAtIndex(index, "33");
} else {
itemClickListener.itemClickedAtIndex(index, "11");
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
View.OnClickListener phoneCallSelectedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int index = (Integer) v.getId();
itemClickListener.itemClickedAtIndex(index, "22");
} catch (Exception e) {
e.printStackTrace();
}
}
};
}

How to keep custom listview items when they are out of screen?

I am trying to design a menu like this:
It almost works, however there is a problem. The menu works fine at start, but after scrolling down and up again, the items are gone and downloaded again and it takes a little time. Is there a way to set a number of elements to create at start and keep them from disappearing?
Here is my code:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
String headers[];
String image_urls[];
List<MyMenuItem> menuItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
menuItems = new ArrayList<MyMenuItem>();
headers = getResources().getStringArray(R.array.header_names);
image_urls = getResources().getStringArray(R.array.image_urls);
for (int i = 0; i < headers.length; i++) {
MyMenuItem item = new MyMenuItem(headers[i], image_urls[i]);
menuItems.add(item);
}
mylistview = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
}
}
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
// .placeholder(R.drawable.empty)
// .error(R.drawable.error)
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
Possibly you can implement lazy loading with some sort of caching of images or whatever you are downloading...
You say the images are donwloaded, i assume that the images are coming from internet. Implement a custom cache for http download or download and store the images in one place before you use

setOnItemClickListener custom Listview

I'm learning to program in android and I've stuck with this ... Someone should know how to make the items on the list are clickable? I will make a new view by passing the id parameter ...
Thank you very much.
This is my actual code:
public class ListaLugares extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_lugares);
ArrayList<Lugar> Lugares = getItems();
setListAdapter(new LugarAdapter(this, R.layout.lista_item, Lugares));
}
public ArrayList<Lugar> getItems() {
DatabaseHandler db = new DatabaseHandler(this);
ArrayList<Lugar> listaLugares = db.getAllLugares2();
db.close();
return listaLugares;
}
private class LugarAdapter extends ArrayAdapter<Lugar> {
private ArrayList<Lugar> items;
public LugarAdapter(Context context, int textViewResourceId, ArrayList<Lugar> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.lista_item, null);
}
Lugar lugar = items.get(position);
if (lugar != null) {
TextView tnombre = (TextView) v.findViewById(R.id.nombre);
TextView tdescripcion = (TextView) v.findViewById(R.id.descripcion);
if (tnombre != null) {
tnombre.setText(lugar.getNombre());
}
if (tdescripcion != null) {
tdescripcion.setText(lugar.getDescripcion());
}
}
return v;
}
}
}
You can override onListItemClick within your class, for instance, like in example you can call some other Activity:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Bundle positionBundle = new Bundle();
positionBundle.putInt("position", position);
Intent i = new Intent(this, MyOtherActivity.class);
i.putExtras(positionBundle);
startActivity(i);
}

Categories