I have a custom adapter for GridView Adapter
I want to get an specific value from the selected Item such as "stamp ID"
I was developing this to display only the stamps long time ago and now I want to be able to click on one stamp to send him to next page
I looked in the internet for a solution but most of the tutorials require me to modify a lot on the Adapter code (Witch means creating a new class)
I need to know if there a simple way to fix this using the adapter that I am using.
this is the part on StampActiviy class where connect
GridView gridView = (GridView) findViewById(R.id.gvStamps);
// Pass the results into ListViewAdapter.java adapterCollected,adapterunCollected
adapterListStamps = new ListViewListStampsAdapter(KioskStampsListActivity.this, arraylistStamps);
// Set the adapter to the ListView
gridView.setAdapter(adapterListStamps);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// I need to get StampId then send the user to next screen
Toast.makeText(KioskStampsListActivity.this, ""+arg2+" - "+stampsUtil.getStampId(), Toast.LENGTH_LONG).show();
}
});
this is the ListViewListStampsAdapter
public class ListViewListStampsAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewListStampsAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView tvStampName, tvStampId;
ImageView stampImage;
String STAMP_IMAGE_URL = SharedPrefUtils.getUrl(context, "images/stamp/");
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.single_stamp_layout, parent, false);
// Get the position
resultp = data.get(position);
tvStampName = (TextView) itemView.findViewById(R.id.tvStampName);
tvStampId = (TextView) itemView.findViewById(R.id.tvStampId);
stampImage = (ImageView) itemView.findViewById(R.id.stampImage);
tvStampName.setText(resultp.get(KioskStampsListActivity.TAG_STAMP_NAME));
tvStampId.setText(resultp.get(KioskStampsListActivity.TAG_STAMPS_ID));
// Passes stampImage images URL into ImageLoader.class
imageLoader.DisplayImage(STAMP_IMAGE_URL+resultp.get(StampsActivity.TAG_STAMP_IMAGE), stampImage);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fadein);
stampImage.startAnimation(myFadeInAnimation);
return itemView;
}
}
this is StampUtil class
public class StampsUtil {
private static String StampId, message, stampimage, stampname;
public String getStampId() {
return StampId;
}
public void setStampId(String stampId) {
StampId = stampId;
}
public static String getMessage() {
return message;
}
public static void setMessage(String message) {
StampsUtil.message = message;
}
public static String getStampimage() {
return stampimage;
}
public static void setStampimage(String stampimage) {
StampsUtil.stampimage = stampimage;
}
public static String getStampname() {
return stampname;
}
public static void setStampname(String stampname) {
StampsUtil.stampname = stampname;
}
}
Thanks
Try below code:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// I need to get StampId then send the user to next screen
Toast.makeText(KioskStampsListActivity.this, ""+arg2+" - "+stampsUtil.getStampId(), Toast.LENGTH_LONG).show();
System.out.println(arraylistStamps.get(i).getStampId());// you can get value
}
});
You can use
grid.getItemAtPosition(position).toString();
I have used like this:-
public static String getUrl(int position){
String itemName = grid.getItemAtPosition(position).toString();
return itemName;// Return your string value
}
OR
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String itemName = grid.getItemAtPosition(position).toString();
}});
and in Adapter :-
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return web[position]; //--> web is my array of string
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
Related
I'm creating an android app, in which I'm using recyclerView and the row of recyclerView is having editText.
This is my ReadingAdapter class
public class ReadingAdapter extends RecyclerView.Adapter<ReadingAdapter.ViewHolder> implements AdapterView.OnItemSelectedListener {
Context context;
String valOpenReading, valClosReading, valConsumption;
private List<ReadingData> readingList;
static String[] arrValOpenRead, arrValClosRead, arrValConsumption;
public ReadingAdapter(Context context, List<ReadingData> readingList) {
this.context = context;
this.readingList = readingList;
arrValOpenRead = new String[readingList.size()];
arrValClosRead = new String[readingList.size()];
arrValConsumption = new String[readingList.size()];
}
#Override
public ReadingAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reading_sheet_layout, parent, false);
return new ReadingAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final ReadingAdapter.ViewHolder holder, final int position) {
ReadingData tempData = readingList.get(position);
holder.pdtName.setText(tempData.pdtName);
holder.keyId.setText("Key "+tempData.keyId);
holder.etClosRead.addTextChangedListener(new TextWatcher() {
boolean ignore = false;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (ignore)
return;
ignore = true;
valOpenReading = holder.etOpenRead.getText().toString();
arrValOpenRead[position] = valOpenReading;
valClosReading = s.toString().equals("") ? "0": s.toString();
arrValClosRead[position] = valClosReading;
if (!valOpenReading.equals("")) {
if (Integer.parseInt(valClosReading) < Integer.parseInt(valOpenReading)) {
Toast.makeText(context, "Check once! closing reading should be more than opening reading!", Toast.LENGTH_LONG).show();
valConsumption = "0";
holder.consumption.setText("");
} else {
valConsumption = (Integer.parseInt(valClosReading) - Integer.parseInt(valOpenReading))+"";
arrValConsumption[position] = valConsumption;
holder.consumption.setText(valConsumption);
}
} else
Toast.makeText(context, "Please fill the opening reading!", Toast.LENGTH_SHORT).show();
ignore = false;
}
});
}
#Override
public int getItemCount() {
return readingList.size();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView pdtName, keyId, consumption;
EditText etOpenRead, etClosRead;
public ViewHolder(View view) {
super(view);
pdtName = (TextView)view.findViewById(R.id.txt_list_pdt_supp);
keyId = (TextView)view.findViewById(R.id.key_set);
etOpenRead = (EditText)view.findViewById(R.id.open_val_set);
etClosRead = (EditText)view.findViewById(R.id.clos_val_set);
consumption = (TextView)view.findViewById(R.id.consumption_val);
}
}
}
This is my ReadingData.java
public class ReadingData {
String pdtName, keyId, openReading, closReading, consumption;
public ReadingData(String pdtName, String keyId) {
this.pdtName = pdtName;
this.keyId = keyId;
}
}
Here, if I enter value in the starting items of the recyclerView then as I scroll up the items to the bottom of the list, the last item will have that value.
Please ignore the quality of image as we can't upload above of 2MiB of snap.
Here the views are recycled as the list is scrolled. How to prevent the copying values to the other item in the list.
And that Toast is also repeated several times. How to stop this.
update:
By the suggetion of LQ Gioan through the SO question How ListView's recycling mechanism works , I got the logic how ListView actually works with recycling of views.
But I'm not sure whether the recyclerView also works same.
But here in my case, how can I implement this process. pls someone help me here.
RecyclerView reuse views, in fact it only generate the as many as views that is visible on the screen. so it's expected if you can see a value you set for other rows
The solution would be set all attributes of the view that you are changing to default or whatever the row should present from your data set
So put addTextChangedListener insode ViewHolder constructor(you can get position by calling getAdapterPosition()) for better performance and set the editText value inside onBindViewHolder method from your data set
Your Activity Code:
ListView listview = (ListView) findViewById(R.id.list_view);
listview.setItemsCanFocus(true);
Adapter adapter = new Adapter (YourActivity.this, YourArrayList);
listview .setAdapter(adapter);
Adapter class
public class Adapter extends BaseAdapter {
// Declare Variables \\
Context mContext;
LayoutInflater inflater;
Activity act;
String[] temp;
public Adapter(Context context, ArrayList<String> list) {
mContext = context;
inflater = LayoutInflater.from(mContext);
act = (Activity) context;
//-------Temp String Array-------\\
temp = new String[this.count];
for (int i = 0; i < this.count; i++) {
temp[i] = list.get(i);
}
//---------------------------\\
}
public class ViewHolder {
TextView optionTitle;
EditText optionText;
int ref;
}
#Override
public int getCount() {
return list.size;
}
#Override
public Object getItem(int position) {
return temp[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.lv_items_add_ques_options_mcq, null);
holder.optionTitle = (TextView) view.findViewById(R.id.add_ques_opts_count_mcq_tv);
holder.optionText = (EditText) view.findViewById(R.id.add_ques_opts_title_mcq_et);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.ref = position;
holder.optionTitle.setText(getCharForNumber(position) + ":");
holder.optionText.setText(temp[position]);
holder.optionText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
temp[holder.ref] = arg0.toString().trim();
}
});
return view;
}
public void getList() {
StaticValues.arrayListOptions = new ArrayList<String>(Arrays.asList(temp));
StaticValues.arrayListOptionsCount = new ArrayList<String>();
for (int i = 0; i < count; i++) {
StaticValues.arrayListOptionsCount.add(String.valueOf(i+1));
Log.e("err_al", StaticValues.arrayListOptions.get(i));
Log.e("err_al", StaticValues.arrayListOptionsCount.get(i));
}
}
private String getCharForNumber(int i) {
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
if (i > 25) {
return null;
}
return Character.toString(alphabet[i]);
}}
I'am new to android and I've a project of making a grid view of images and onclick on image it shows it , thats the ImageAdapter class code
public class ImageAdapter extends BaseAdapter{
private static LayoutInflater inflater = null;
private Activity activity;
private String mode = "";
int[] images=null ;
public ImageAdapter(Activity act, String mode , int[] images){
inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = act;
this.mode = mode;
this.images= images ;
}
public ImageView getImage(int pos)
{
ImageView im = (ImageView) getItem(pos);
return im ;
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return new Integer(images[position]);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if(mode.equalsIgnoreCase("grid")){
if (view == null) {
view = inflater.inflate(R.layout.each_image1, null);
}
ImageView iv = (ImageView)view.findViewById(R.id.imageView);
iv.setImageResource(images[position]);
} else if(mode.equalsIgnoreCase("gallery")){
if (view == null) {
view = inflater.inflate(R.layout.each_image_gallery, null);
}
ImageView iv = (ImageView)view.findViewById(R.id.imageView);
iv.setImageResource(images[position]);
}
return view;
}
}
thats my grid activity
public class GridActivity extends Activity {
GridView grid = null;
public static ImageAdapter adapter1 ;
public static ImageAdapter adapter2 ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
adapter1= new ImageAdapter(GridActivity.this, "grid" , Images.images1);
adapter2 = new ImageAdapter(GridActivity.this, "grid" , Images.images2);
Intent i = this.getIntent();
if (i!=null)
{
String unique = i.getExtras().getString("Unique");
if (unique.equals("islam"))
{
Toast.makeText(GridActivity.this, "islam", Toast.LENGTH_LONG).show();
grid = (GridView)findViewById(R.id.gridView1);
grid.setAdapter(adapter1);
}
if (unique.equals("natural"))
{
Toast.makeText(GridActivity.this, "nat", Toast.LENGTH_LONG).show();
grid = (GridView)findViewById(R.id.gridView1);
grid.setAdapter(adapter2);
}
}
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long id) {
Intent i = new Intent(GridActivity.this, imgPrevActivity.class);
i.putExtra("selectedIntex", pos);
startActivity(i);
Toast.makeText(GridActivity.this,"ddd",Toast.LENGTH_LONG).show();
}
});
}
}
and this is the activity where it supposes to show any clicked on image
public class imgPrevActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.each_image1);
ImageView im = (ImageView)findViewById(R.id.imageView);
int pos = getIntent().getExtras().getInt("selectedIntex");
// ImageAdapter adapter = new ImageAdapter(imgPrevActivity.this, "image prev", null);
long Id= GridActivity.adapter1.getItemId(pos);
im.setImageResource((int) Id);
}
}
i've tried to get the position of image clicked on from the grid
then getting the Id from the position
and setting the image view to that ID
but it doesnt work !!
thats where the images are put in arrays
public class Images {
public static int[] images1 = {
R.drawable.buds, R.drawable.cherry_34,
R.drawable.clouds_2, R.drawable.coffee_beans_2,
R.drawable.death_valley_sand_dunes
};
public static int[] images2= {
R.drawable.morning_glory_pool,
R.drawable.pink_flowers, R.drawable.sun_flower,
R.drawable.sunrise_3, R.drawable.yellow_rose_3,
};
}
You have to pass your image resource id with intent. The list item id of adapter is useless because you have new Activity on the screen.
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long id) {
Intent i = new Intent(GridActivity.this, imgPrevActivity.class);
i.putExtra("selectedIntex", grid.getAdapter().getItem(pos);
startActivity(i);
Toast.makeText(GridActivity.this,"ddd",Toast.LENGTH_LONG).show();
}
});
and change your code in your ImgPreviewActivity:
public class imgPrevActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.each_image1);
ImageView im = (ImageView)findViewById(R.id.imageView);
int pos = getIntent().getIntExtra("selectedIntex", 0);
im.setImageResource(pos);
}
}
I think it should work
I have an arrayList of this class:
public class Lawyer extends DbHelper{
private int id;
private String fullName;
private String mobile;
private Context context;
public Lawyer(Context context,int id, String fullName, String mobile) {
super(context);
this.id = id;
this.fullName = fullName;
this.mobile = mobile;
this.context = context;
}
}
My arrayList is filled with information of a few people. Is it possible to have a spinner filled with "fullName" of all lawyers in the array list?
Currently I have this code to fill my spinner with static data from a simple array:
String [] items={"Lawyer1","Lawyer2","Lawyer3","Lawyer4","Lawyer5"};
final Spinner lstLawyers;
lstLawyers=(Spinner)findViewById(R.id.lstLawyers);
lstLawyers.setAdapter( new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,items));
lstLawyers.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(lstLawyers.getSelectedItem().toString());
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Look at SpinnerAdaper.
If you have an alTypes ArrayList with Lawyer classes (with fullName, mobile etc...)
you should extend SpinnerAdapter (see AdapterForSpinner1 below)
and then set it to your spinner like this:
AdapterForSpinner1 spinad1 = new AdapterForSpinner1(activity, alTypes);
lstLawyers.setAdapter(spinad1);
AdapterForSpinner1
class AdapterForSpinner1 extends BaseAdapter implements SpinnerAdapter {
/**
* The internal data (the ArrayList with the Objects).
*/
private final List<Lawyer> data;
Context mContext;
public AdapterForSpinner1(Context context, List<Lawyer> data){
this.data = data;
mContext=context;
}
/**
* Returns the Size of the ArrayList
*/
#Override
public int getCount() {
return data.size();
}
/**
* Returns one Element of the ArrayList
* at the specified position.
*/
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
/**
* Returns the View that is shown when a element was
* selected.
*/
#Override
public View getView(int position, View recycle, ViewGroup parent) {
TextView text;
if (recycle != null){
// Re-use the recycled view here!
text = (TextView) recycle;
} else {
// No recycled view, inflate the "original" from the platform:
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
text = (TextView) (li.inflate(android.R.layout.simple_dropdown_item_1line, parent, false) );
}
text.setTextColor(Color.BLACK);
text.setText(data.get(position).getFullname());
return text;
}
}
I'm trying to implement a simple android REST Client and i having some problems understanding how to pass data between my activities.
I have this ListActivity (I'm using the Spring REST Template) :
public class MainActivity extends ListActivity
{
protected static final String TAG = MainActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "You have selected" + position + id ,
Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart() {
super.onStart();
new DownloadClientesTask().execute();
}
private void refreshClientes(List<Cliente> clientes) {
if (clientes == null) {
return;
}
ClientesListAdapter adapter = new ClientesListAdapter(this, clientes);
setListAdapter(adapter);
}
private class DownloadClientesTask extends AsyncTask<Void, Void, List<Cliente>> {
#Override
protected List<Cliente> doInBackground(Void... params) {
final String url = "http://192.168.1.119/~henry/api_slim/index.php/customers";
try {
// Set the Accept header for "application/json"
HttpHeaders requestHeaders = new HttpHeaders();
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(acceptableMediaTypes);
// Populate the headers in an HttpEntity object to use for the request
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
// Perform the HTTP GET request
ResponseEntity<Cliente[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
Cliente[].class);
// convert the array to a list and return it
return Arrays.asList(responseEntity.getBody());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(List<Cliente> result) {
refreshClientes(result);
}
}
}
And this is My listAdapter :
public class ClientesListAdapter extends BaseAdapter{
private List<Cliente> clientes;
private final LayoutInflater layoutInflater;
public ClientesListAdapter(Context context, List<Cliente> clientes) {
this.clientes = clientes;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return this.clientes != null ? clientes.size() : 0;
}
#Override
public Cliente getItem(int position) {
return this.clientes.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.cliente_list_item, parent, false);
}
Cliente cliente = getItem(position);
if (cliente != null) {
TextView t = (TextView) convertView.findViewById(R.id.name);
t.setText(cliente.getFirstname());
}
return convertView;
}
}
This the POJO class of the data iḿ getting :
public class Cliente {
private Integer id_customer;
private String firstname;
public Integer getId_customer() {
return id_customer;
}
public void setId_customer(Integer id_customer) {
this.id_customer = id_customer;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
When i select an element from the listView i would like show details specific about this element on another activity or fragment, but i don't know how to obtain the customer_id of this element from the list, do i have to save it when i procesing the response? do I need to use content provider or database provide this behavior? i'm really confused, thanks in advance for any help!
There are good examples on how to pass data from one activity to another here, pass objects between activities. You may want to take a look first to the solutions on those links.
Please see below an example that can put you on the right track.
List adapter class:
public class ClientesListAdapter extends BaseAdapter{
//private members
private List<Cliente> clientes;
//adapter position - not used for this example
public int adapterPosition;
//context of app
private Context mContext;
//default constructor
public ClientesListAdapter(Context context, List<Cliente> clientes) {
//context pointer
this.mContext = context;
//alloc
this.clientes = new ArrayList<Cliente>(clientes.size());
this.clientes.addAll(clients);
}
//Holder for events and dates (memory management)
public static class ViewHolder{
TextView myTextView;//this is actually findViewById(R.id.name) #see getView() method
}
//generated method
#Override
public int getCount() {
// TODO Auto-generated method stub
return this.clientes != null ? clientes.size() : 0;
}
//generated method
#Override
public Cliente getItem(int position) {
return this.clientes.get(position);
}
//generated method
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
//get client's id
public int getClienteId(int position){
return this.clientes.get(position).getClienteId();
}
//get client's id without passing the position
public int getClienteId(){
return this.clientes.get(adapterPosition).getClienteId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//row is actually convertView (the current view)
View row = convertView;
//holds our view elements
ViewHolder holder;
//if row is null
if(row == null){
//inflate layout to get our view elements
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(com.yourapp.R.layout.my_layout, parent, false);//your layout here, modify code
//set up the holder
holder = new ViewHolder();
holder.myTextView = (TextView) row.findViewById(com.yourapp.R.id.name);
//give the row a tag (holder)
row.setTag(holder);
}else{
//row is not null we can see it (no need to allocate memory)
holder = (ViewHolder) row.getTag();
}
//get your cliente object
Cliente cliente = this.clientes.get(position);
if (cliente != null) {
holder.myTextView.setText(cliente.getFirstname());
}
//copy position
adapterPostion = position;
return convertView;
}
}
You see that we used a ViewHolder class for memory management. This is a good practice for holding view elements inside your list adapter. You can find more info about list views, explained by Romain Guy - The World of ListViews.
From your MainActivity allocate the adapter and get your item on click:
//---- code --- //
ListView myListView = (ListView)findViewById(R.id.mylistview);//or you may use ListActivity
ClientesListAdapter adapter = new ClientesListAdapter(this, clientes);//"this" or "getApplicationContext()"
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();//notify
// ---- code --- //
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "You have selected" + position + id ,
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MyActivity.this, ActivityB.class);
intent.putInt("cliente_id",adapter.getClienteId());
startActivity(intent);
}
Another example is with implementing an interface in the adapter like this:
//--code//
//Interface method
private OnSaveEditsListener saveEditsListener = null;
public void setOnSaveEditsListener(OnSaveEditsListener l) {
saveEditsListener = l;
}
//--code//
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//--code--//
//get clicked position of calendar (get clicked day)
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.requestFocusFromTouch();
currentAgendaPosition = position;
try{
saveEditsListener.onSaveEdits();
}catch(Exception ex){
ex.printStackTrace();
}
}
});
//returns current row
return row;
}
//--code--//
And from your MainActivity start the second activity like this:
adapter.setOnSaveEditsListener(new OnSaveEditsListener() {
#Override
public void onSaveEdits() {
//Start activity from here
//--code--//
startActivity(intent);
}
});
get the position of the item clicked and get the object present at that position from the arraylist and use it to get the required details.
use
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "You have selected" + position + id ,
Toast.LENGTH_SHORT).show();
// use this.clientes.get(position) and pass it to the next activity or fragment using putextras to where you need to pass and display this in the destination end using the same object by getting it using getExtra()
}
Your list is in the adapter:
private List<Cliente> clientes;
In onListItemClick, you can get the Cliente from this list using the position parameter.
You pass information to another activity when you call startActivity, passing it an Intent. The Intent may have additional information, in your case you could set the customer_id as an int extra, something like:
intent.putExtra(EXTRA_CUSTOMER_ID, customer_id);
I have a listview utilizing a custom adapter, now I want it to show the first five entries and load the others when I scroll down, what's the simplest way to do this?
If my code for the list is
public class Second extends Activity {
static final String Li_nk="LinkName:";
static final String Image_name="ImageName:";
//ListView list;
public final static String AUTH = "authentication";
static final String KEY_THUMB_URL = "thumb_image"; //Uri.decode("http://zeesms.info/android_app_images/Koala.jpg");
//JSONObject j2;
String wrd;
//ArrayList<HashMap<String,String>> mylist;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i2=getIntent();
wrd=i2.getStringExtra("entrd");
Log.v("keyis",wrd);
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 40000);
}
};
handler.postDelayed(runable, 10);
}public void LoadData(){
JSONObject j2=JSONfunctions.getJSONfromURL("/webservice_search.php?keyword="+wrd+"&format=json");
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
try{JSONArray jray=j2.getJSONArray("listings");
for(int i=0;i<jray.length();i++){
Log.v("state","json data being read");
JSONObject j3= jray.getJSONObject(i);
String first=j3.getString("listing");
Log.v("sublist", first);
JSONObject j4=j3.getJSONObject("listing");
String sec=j4.getString("links");
int maxLength = (sec.length() < 30)?sec.length():27;
sec.substring(0, maxLength);
String cutsec=sec.substring(0,maxLength);
Log.v("links are",cutsec);
String img=j4.getString("image_name");
Log.v("image name is ",img);
//Uri dimg=Uri.parse("http://zeesms.info/android_app_images/Koala.jpg");
HashMap<String,String> map=new HashMap<String,String>();
map.put("Id",String.valueOf(i));
map.put(Li_nk,cutsec);
map.put(Image_name,j4.getString("image_name"));
map.put(KEY_THUMB_URL,"http://zeesms.info/android_app_images/"+img);
mylist.add(map);
}
}
catch(JSONException e){
Log.e("loG_tag","Error parsing"+e.toString());
}
LazyAdapter adapter = new LazyAdapter(this,mylist);
adapter.notifyDataSetChanged();
// list.setSelection(positionToMove);
ListView list=(ListView)findViewById(R.id.lv1);
list.setEmptyView(findViewById(R.id.empty));
list.setAdapter(adapter);
// list.setStackFromBottom(true);
list.setItemsCanFocus(false);
// list.smoothScrollToPosition(3,5);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getApplicationContext(),"Click ListItem Number " + position, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.riffre.com/"));
startActivity(myIntent);
}
});
list.setOnScrollListener(new OnScrollListener(){
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
// TODO Auto-generated method stub
}
});
}
and the code for the adapter class extending baseadapter is
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
Collections.reverse(d);
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.custom_row_view1, null);
TextView title = (TextView)vi.findViewById(R.id.linkname); // merchnts name
TextView artist = (TextView)vi.findViewById(R.id.imagename); // address
//TextView duration = (TextView)vi.findViewById(R.id); // distance
ImageView thumb_image=(ImageView)vi.findViewById(R.id.mClogo); // logo
HashMap<String, String> jsn = new HashMap<String, String>();
jsn = data.get(position);
// Setting all values in listview
title.setText(jsn.get(Second.Li_nk));
artist.setText(jsn.get(Second.Image_name));
//duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(jsn.get(Second.KEY_THUMB_URL), thumb_image);
return vi;
}
}
and I have a different class for parsing the json data in the list. So what would be the simplest way to implement endless scrolling?
Any help would be greatly appreciated...
If you load your items from network(so time delay is expected), check this library project : https://github.com/chrisbanes/Android-PullToRefresh
This is an awesome pull-to-refresh listview project, but it also provides pull to refresh from bottom. So you can use that feature to load more items. But this feature need explicit pull action from user.
Found the solution by declaring my list as a global variable. Thanks anyway for your help.