I'm trying to build a ListView in android, where each item of ListView is composed for one ImgeView and 4 TexView. The getView of my class extended BaseAdapter is defined as follows:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(vi == null) {
LayoutInflater inflater = (LayoutInflater) Activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.item_lista_restaurantes, null);
holder = new ViewHolder();
holder.nombreRestaurante= (TextView) vi.findViewById(R.id.etiquetaNombreResItemRes);
holder.direccionRestaurante = (TextView) vi.findViewById(R.id.etiquetaDireccionResItemRes);
holder.ciudadRestaurante = (TextView) vi.findViewById(R.id.etiquetaCiudadResItemRes);
holder.telefonoRestaurante = (TextView) vi.findViewById(R.id.etiquetaTelResItemRes);
holder.lineaLogo = (TextView) vi.findViewById(R.id.etiquetaLineaLogo);
vi.setTag(holder);
}
else
{
holder = (ViewHolder)vi.getTag();
}
itemRestaurante item= this.itemR.get(position);
ImageView image = (ImageView) vi.findViewById(R.id.imageLogoItemRestaurante);
int imageResource = this.Activity.getResources().getIdentifier(item.getRutaImaLogo(), null, this.Activity.getPackageName());
image.setImageDrawable(this.Activity.getResources().getDrawable(imageResource));
holder.nombreRestaurante.setText(item.getNombreR());
holder.direccionRestaurante.setText(item.getDireccionR());
holder.ciudadRestaurante.setText(item.getCiudadR());
holder.telefonoRestaurante.setText(item.getTelR());
holder.lineaLogo.setText(item.getDireccionR());
return vi;
}
the code line on getView:
ImageView image = (ImageView) vi.findViewById(R.id.imageLogoItemRestaurante);
int imageResource = this.Activity.getResources().getIdentifier(item.getRutaImaLogo(), null, this.Activity.getPackageName());
image.setImageDrawable(this.Activity.getResources().getDrawable(imageResource));
this is the itemRestaurantes class where i return the rutaImagenLogo value
package clasesExtras;
public class itemRestaurante {
private long idRestaurante;
private String nombreRestaurante;
private String direccionRestaurante;
private String ciudadRestaurante;
private String telefonoRestaurante;
private String rutaImagenLogo;
//private String rutaImagenGo;
//private String rutaImagenLineaLogo;
/*Constructor*/
public itemRestaurante(long id, String nombre, String direccion, String ciudad,
String telefono, String rutaLogo){
this.idRestaurante= id;
this.nombreRestaurante= nombre;
this.direccionRestaurante= direccion;
this.ciudadRestaurante= ciudad;
this.telefonoRestaurante= telefono;
this.rutaImagenLogo= rutaLogo;
//this.rutaImagenGo= rutaGo;
//this.rutaImagenLineaLogo = rutaLineaLogo;
}
public long getId(){
return this.idRestaurante;
}
public void setId(long id){
this.idRestaurante= id;
}
public String getNombreR(){
return this.nombreRestaurante;
}
public void setNombreR(String nombre){
this.nombreRestaurante=nombre;
}
public String getDireccionR(){
return this.direccionRestaurante;
}
public void setDireccionR(String direccion){
this.direccionRestaurante=direccion;
}
public String getCiudadR(){
return this.ciudadRestaurante;
}
public void setCiudadR(String ciudad){
this.ciudadRestaurante= ciudad;
}
public String getTelR(){
return this.telefonoRestaurante;
}
public void setTelR(String telefono){
this.telefonoRestaurante= telefono;
}
public String getRutaImaLogo(){
return this.rutaImagenLogo;
}
public void setRutaImaLogo(String imagenLogo){
this.rutaImagenLogo= imagenLogo;
}
this is the activity class where i fill the ArrayList with the information of each item of ListView
package appetite.apptitud;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import clasesExtras.ArrayAdapterRestaurantes;
import clasesExtras.itemRestaurante;
public class ListaRestaurantes extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_restaurantes);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); //forza a android a ocultar el teclado virtual
ListView lista = (ListView)findViewById(R.id.listaRestaurantes);
ArrayList<itemRestaurante> itemRestaurante = obtenerItems();
ArrayAdapterRestaurantes adapter = new ArrayAdapterRestaurantes(this, itemRestaurante);
lista.setAdapter(adapter);
}
//Método para llenar la lista de los restaurantes.
private ArrayList<itemRestaurante> obtenerItems(){
ArrayList<itemRestaurante> items = new ArrayList<itemRestaurante>();
items.add(new itemRestaurante(1, "Frisby", "Cra. 7a 24-74", "Pereira", "3168899", "drawable/frisby_logo"));
items.add(new itemRestaurante(2, "Big Pollo", "Cra. 5a 34-12", "Pereira", "3147152", "drawable/bigpollo"));
items.add(new itemRestaurante(3, "Wingz", "Cra. 8a 18-62", "Pereira", "3391000", "drawale/wingz"));
items.add(new itemRestaurante(4, "Sir Pollo", "Cra. 7a 20-04", "Pereira", "3357913", "drawable/sirpollo"));
return items;
}
the code shown above make reference a the image path where it is stored (drawable folder), and i want to show this image in each item of listview, but this jumps to the following error:
FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException:Resource ID #0x0
at android.content.res.Resources.getValue(Resources.java:1014)
at android.content.res.Resources.getDrawable(Resources.java:659)
at clasesExtras.ArrayAdapterRestaurantes.getView(ArrayAdapterRestaurantes.java:56)
Some people tell me that the imageResource value is 0. And 0 is not a valid resource ID.
how can i do to fix this value?
Help me please, i don't understand it
I think that imageResource is 0. Check this value.
getIdentifier Returns int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)
You will have to create a custom adapter for the list View
this would be Restaurant.java
public class Restaurant{
public int icon;
public String someText;
public String moreText;
public String someMoreText;
public String evenMoreText;
public Restaurant(int icon, String someText, String moreText, String somMoreText, String evenMoreText)
super.();
this.someText = someText;
this.moreText = moreText;
this.someMoreText = someMoreText;
this.evenMoreText = evenMoreText;
this.icon = icon;
}
Here is the custom adapter RestaurantAdapter.java
public class RestaurantAdapter extends<Restaurant> }
Context context;
int layoutResourceId;
Restaurant data[] = null;
public RestaurantAdapter(Context context, int layoutResourceId, Restaurant[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RestaurantHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RestaurantHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtID1 = (TextView)row.findViewById(R.id.txtID1);
holder.txtID2 = (TextView)row.findViewById(R.id.txtID2);
holder.txtID3 = (TextView)row.findViewById(R.id.txtID3);
holder.txtID4 = (TextView)row.findViewById(R.id.txtID4);
row.setTag(holder);
}
else
{
holder = (RestauantHolder)row.getTag();
}
Restaurant restaurant = data[position];
holder.txtID1.setText(restaurant.someText);
holder.txtID1.setText(restaurant.moreText);
holder.txtID1.setText(restaurant.someMoreText);
holder.txtID1.setText(restaurant.evenMoreText);
holder.imgIcon.setImageResource(restarant.icon);
return row;
}
}
static class RestaurantHolder
{
ImageView imgIcon;
TextView txtID1;
TextView txtID2;
TextView txtID3;
TextView txtID4;
}
Now in your activity it will be a call like this
Restaurant restaurant_data[] = new Restaurant[]
{
new Restaurant(R.drawable.pic1, "some text", "more text", "some more text". "even more text"),
new Restaurant(R.drawable.pic2, "text", "more", "some more", "blah"),
new Restaurant(R.drawable.pic3, "blah1", "blah2", "blah3" "blah3"),
new Restaurant(R.drawable.pic4, "you get the idea", "blah", "blah", "blah"),
};
RestaurantAdapter adapter = new RestaurantAdapter(this,
R.layout.listview_item_row, restaurant_data);
listView1 = (ListView)findViewById(R.id.listView1);
Credit goes to http://www.ezzylearning.com/tutorial.aspx?tid=1763429
You will just have to change around some of the names.
Related
This is my code in my activity
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_list);
try{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
displaypatientinfo = (ListView)findViewById(R.id.lv_patientlist);
mydb = new DatabaseHelper(getApplicationContext());
sqLiteDatabase = mydb.getReadableDatabase();
String selection = "pat_type=? OR pat_type=? AND is_active=?";
String[] selectionargs = {"Infant","Mother","1"};
cursor = mydb.getallpatient(sqLiteDatabase,selection,selectionargs);
listDataAdapter = new ListDataAdapter(this, R.layout.resource_patientlist);
displaypatientinfo.setAdapter(listDataAdapter);
if(cursor.moveToFirst()){
do{
String id, firstname, middlename, lastname, birthdate;
id = cursor.getString(0);`enter code here`
firstname = cursor.getString(1);
middlename = cursor.getString(2);
lastname = cursor.getString(3);
birthdate = cursor.getString(4);
DataProvider dataProvider = new DataProvider(id, firstname, middlename, lastname, birthdate);
listDataAdapter.add(dataProvider);
}while(cursor.moveToNext());
}else{
}
displaypatientinfo.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
// just wanna ask your help here that if the user click item on listview it will return the id from the database
}
});
}catch (Exception e){
e.printStackTrace();
}
}
This is my code in my List Adapter
package com.example.asus.wombapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.asus.wombapp.onclicklistener.PatientList_Listener;
import java.util.ArrayList;
import java.util.List;
/**
* Created by asus on 11/04/2018.
*/
public class ListDataAdapter extends ArrayAdapter {
private Context context;
List list = new ArrayList();
public ListDataAdapter( Context context, int resource) {
super(context, resource);
this.context = context;
}
static class LayoutHandler
{
TextView id, name, birthdate;
ImageView patientimage,edit,delete;
}
#Override
public void add(Object object){
super.add(object);
list.add(object);
}
#Override
public int getCount(){
return list.size();
}
#Override
public Object getItem(int position){
return list.get(position);
}
#Override
public View getView( int position, View ConvertView, ViewGroup parent){
ImageView delete;
View row = ConvertView;
LayoutHandler layoutHandler;
DataProvider dataprovider = (DataProvider) this.getItem(position);
if(row == null){
LayoutInflater layoutInflater= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.resource_patientlist,parent,false);
layoutHandler = new LayoutHandler();
final PatientList patientList = new PatientList();
layoutHandler.id = (TextView)row.findViewById(R.id.tv_id);
layoutHandler.name = (TextView)row.findViewById(R.id.tv_patientname);
layoutHandler.birthdate = (TextView)row.findViewById(R.id.tv_actualbirthdate);
layoutHandler.patientimage = (ImageView) row.findViewById(R.id.image_patient);
layoutHandler.edit = (ImageView)row.findViewById(R.id.image_edit);
layoutHandler.delete = (ImageView)row.findViewById(R.id.image_delete);
layoutHandler.delete.setOnClickListener(new PatientList_Listener(this.context,dataprovider.getId()));
layoutHandler.edit.setOnClickListener(new PatientList_Listener(this.context,dataprovider.getId()));
row.setTag(layoutHandler);
}else{
layoutHandler = (LayoutHandler)row.getTag();
}
//set value from database to resourceview
layoutHandler.id.setText(dataprovider.getId());
layoutHandler.name.setText(dataprovider.getFirtsname() + " " + dataprovider.getMiddlename() +" " + dataprovider.getLastname());
layoutHandler.birthdate.setText(dataprovider.getBirthdate());
layoutHandler.patientimage.setImageResource(R.drawable.picture);
layoutHandler.delete.setImageResource(R.drawable.delete_data);
layoutHandler.edit.setImageResource(R.drawable.edit_data);
return row;
}
}
Hope you can help be in my activity i have a listview wherein all the data is from the database i just wanna ask your help how to get ID of the item on the listview. once the user click item on the listview i can get the primary key of that item please help me the id that iam trying to get is the dataprovider.getId() in the listAdapter please hope anyone can help
You could use the following:
((DataProvider)listDataAdapter.getItem(position)).getId();
First, get the listDataAdapter to return the DataProvider by position and then get its Id like this:
displaypatientinfo.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
String id = listDataAdapter.get(position).getId();
}
});
I have been trying to learn how to make custom ArrayAdapters to use in some of my Android apps by using this tutorial, but adapting it slightly so that I could fit it with my own application.
I've tested it a couple times now on my phone, but I've found the performance speed to be incredibly slow (when loading and scrolling through the listview). The other activities which do not use this custom ArrayAdapter have a normal performance speed.
I'm not really sure what the problem could be or where in my code it would be, so below, I've posted all of my custom ArrayAdapter class:
package com.mycompany.myapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomArrayAdapter extends ArrayAdapter<String> {
private static class ViewHolder {
TextView tv_Id;
TextView tv_Name;
TextView tv_Group;
}
private Context context;
private ArrayList<String> arr_items;
public CustomArrayAdapter(Context context, ArrayList<String> arr_items) {
super(context, R.layout.listview_advanced, arr_items);
this.context = context;
this.arr_items = arr_items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Person person = new Person(context, arr_items.get(position));
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // View lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_advanced, parent, false);
viewHolder.tv_Id = (TextView) convertView.findViewById(R.id.lvAdv_text1);
viewHolder.tv_Name = (TextView) convertView.findViewById(R.id.lvAdv_text2);
viewHolder.tv_Group = (TextView) convertView.findViewById(R.id.lvAdv_text3);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.tv_Id.setText(person.getIDAsString());
viewHolder.tv_Name.setText(person.getName());
if (person.getGroup().equals("")) {
viewHolder.tv_Group.setText("");
} else {
viewHolder.tv_Group.setText("(" + person.getGroup() + ")");
}
// Return the completed view to render on screen
return convertView;
}
}
Any help would be much appreciated. Thanks.
UPDATE:
Also, before calling the CustomArrayAdapter, I add data to an ArrayList<String> by going through rows of a .csv file and getting that data. At the moment, when reading the .csv file, I have this:
...
ArrayList<String> arr_person = new ArrayList<>(); // Global variable
...
// In a method:
String data = inputStream.nextLine();
String[] line = data.split(",");
if (line.length >1) {
arr_person.add(line[1]);
}
...
CustomArrayAdapter adapter = new CustomArrayAdapter(getActivity(), arr_person);
lv_main.setAdapter(adapter);
How would I adapt this for objects?
UPDATE 2:
My Person object works like this:
private Context context;
private String person, group, someAttribute, ... ;
private int idNumber, scoreOne, scoreTwo, scoreThree, scoreFour, scoreFive, scoreSix, scoreTotal, ... ;
private double ... ;
public Person(Context context, String person) {
this.context = context;
this.person = person;
loadInformation();
}
private void loadInformation() {
InputStreamReader inputStreamReader;
try {
inputStreamReader = new InputStreamReader(context.getAssets().open("PersonsList.csv"));
Scanner inputStream = new Scanner(inputStreamReader);
inputStream.nextLine(); // Ignores the first line
while (inputStream.hasNext()) {
String data = inputStream.nextLine(); // Gets a whole line
String[] line = data.split(","); // Splits the line up into a string array
if (line.length > 1) {
if (line[1].equals(person)) {
idNumber = Integer.parseInt(line[0]);
person = line[1];
group = line[2];
someAttribute = line[3];
scoreOne = Integer.parseInt(line[4]);
scoreTwo = Integer.parseInt(line[5]);
scoreThree = Integer.parseInt(line[6]);
scoreFour= Integer.parseInt(line[7]);
scoreFive = Integer.parseInt(line[8]);
scoreSix = Integer.parseInt(line[9]);
scoreTotal = scoreOne + scoreTwo + scoreThree + scoreFour + scoreFive + scoreSix;
// Same code pattern for defining about 10 more attributes
}
}
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getID() {
return idNumber;
}
public String getIDAsString() {
return format(idNumber);
}
private String format(int number) {
String str_num = String.valueOf(number);
switch (str_num.length()) {
case 1:
str_num = "00" + str_num;
break;
case 2:
str_num = "0" + str_num;
break;
case 3:
// Leave it how it is;
break;
}
return str_num;
}
public String getName() {
return person;
}
public String getGroup() {
return group;
}
public String getSomeAttribute() {
return someAttribute;
}
public int getScoreOne() {
return scoreOne;
}
public int getScoreTwo() {
return scoreTwo;
}
...
Base your array and ArrayAdapter on Person instead of String and make a list of Persons before you set up the adapter. This way you only run the Person constructor once instead of every time you display its view.
ArrayList<Person> arr_person = new ArrayList<>(); // Global variable
...
String data = inputStream.nextLine();
String[] line = data.split(",");
if (line.length > 1) {
Person person = new Person(context, line[1]);
arr_person.add(person);
}
...
CustomArrayAdapter adapter = new CustomArrayAdapter(getActivity(), arr_person);
lv_main.setAdapter(adapter);
...
package com.mycompany.myapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomArrayAdapter extends ArrayAdapter<Person> {
private static class ViewHolder {
TextView tv_Id;
TextView tv_Name;
TextView tv_Group;
}
private Context context;
private ArrayList<Person> persons;
public CustomArrayAdapter(Context context, ArrayList<Person> persons) {
super(context, R.layout.listview_advanced, arr_items);
this.context = context;
this.persons = persons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Person person = persons.get(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // View lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_advanced, parent, false);
viewHolder.tv_Id = (TextView) convertView.findViewById(R.id.lvAdv_text1);
viewHolder.tv_Name = (TextView) convertView.findViewById(R.id.lvAdv_text2);
viewHolder.tv_Group = (TextView) convertView.findViewById(R.id.lvAdv_text3);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.tv_Id.setText(person.getIDAsString());
viewHolder.tv_Name.setText(person.getName());
if (person.getGroup().equals("")) {
viewHolder.tv_Group.setText("");
} else {
viewHolder.tv_Group.setText("(" + person.getGroup() + ")");
}
// Return the completed view to render on screen
return convertView;
}
}
I have tried to inplement the "Picasso Framework" in my MainActivity, but it keeps giving me an error. It is in this line "Picasso.with(MainActivity.this)", the "Picasso" has an red line under it. Can someone please help me. I have imported the jar.file.
Please look at my code:
package com.chrfugl.xxxx;
import java.util.List;
import java.util.Vector;
import com.chrfugl.studenterhuset.R;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
public static final String[] title = new String[] {
"1",
"2",
"3",
"4",
"5,
"6",
};
public static final String[] detail = new String[] {
"Text",
"Text",
"Text",
"Text",
"Text",
"Text",
};
public static Integer[] imgid = {
R.drawable.1, R.drawable.2,
R.drawable.3, R.drawable.4,
R.drawable.5, R.drawable.6,
};
public static final String[] footer = new String[] {
"Text",
"Text",
"\Text",
"\Text",
"\Text",
"\Text",
};
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for (int i = 0; i < title.length; i++) {
try {
rd = new RowData(i, title[i], detail[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list_item, R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
RowData(int id, String title, String detail) {
mId = id;
mTitle = title;
mDetail = detail;
}
#Override
public String toString() {
return mId + " " + mTitle + " " + mDetail;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11 = null;
RowData rowData = getItem(position);
if (null == convertView) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
detail = holder.getdetail();
detail.setText(rowData.mDetail);
i11 = holder.getImage();
Picasso.with(MainActivity.this)
.load(imgid[rowData.mId])
.placeholder(android.R.color.black)
.error(android.R.color.black)
.resize(100, 100)
.centerCrop()
.into(i11);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11 = null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if (null == title) {
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail() {
if (null == detail) {
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage() {
if (null == i11) {
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
Try this-
Edit your CustomAdapter class by adding a private Context variable. Then, in the constructor of the CustomAdapter, initialize that variable.
Then you will have a Context to reference every time you need to make a Picasso call.
So, Custom Adapter should look like this:
private class CustomAdapter extends ArrayAdapter<RowData> {
private Context mContext;
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
mContext = context;
}...
Then make Picasso calls in getView() like this"
Picasso.with(mContext)... and add whatever else you need.
Hope this helps!
I cant seem to find out how to get my ListView (OnListItemClick), to open different activity´s. I know i somehow need to get some row-id for my ListView, but i dont know how to. Right now every row in my ListView just opens up the same activity.
Sorry for my bad English, hope You understand.
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static final String[] title = new String[] {
"Text",
"Text",
"Text",
;
static final String[] detail = new String[] {
"Image1",
"Image2",
"Image3",
};
private Integer[] imgid = {
R.drawable.spektr,
R.drawable.spektr,
R.drawable.sleep,
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],detail[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position,
long id) {
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("id", item.mId);
startActivity(intent);
}
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
RowData(int id,String title,String detail){
mId=id;
mTitle = title;
mDetail=detail;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mDetail;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
detail = holder.getdetail();
detail.setText(rowData.mDetail);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail() {
if(null == detail){
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
And my NewActivity looks like this:
import android.app.Activity;
import android.os.Bundle;
public class NewActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.poetry);
getIntent().getExtras().getInt("id");
}}
You don't need to get the "row ID of the ListView", you need to get the "row ID of the item that was clicked in the Listview"
Luckily, Android gives you the row ID right there as the last parameter of onListItemClick(), where you're currently using the position:
public void onListItemClick(ListView parent, View v, int position, long id) {
Intent intent = new Intent(this, NewActivity.class);
// intent.putExtra("position", position); // not what you want
intent.putExtra("id", id); // more likely what you want
startActivity(intent);
}
If you do not have an ID, you can also get the actual item, i.e. a RowData object in your case, from the ListAdapter:
public void onListItemClick(ListView parent, View v, int position, long id) {
RowData item = (RowData) getListAdapter().getItem(position);
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("id", item.mId);
startActivity(intent);
}
In both cases, you have to change your code in NewActity so you extract the ID, not position, from the extra bundle.
Another update:
Lets say my list have 10 items, item 1, item 2, item 3 and so on. When item 1 is clicked i want that to open a new activity, let's call that NewActivityOne, and NewActivityOne will refer to a layout with some text called layoutone. Item 2 will also open a new activity, NewActivityTwo, which will refer to a new layout called layouttwo. And that's how I want it to be for all my items.
If your detail activities differ only in the layout (i.e. not in any behavior/code), just use putExtra() to pass an R.layout.* ID (let's call it "layoutId") to your NewActivity and use that in setContentView(getIntent().getExtras().getInt("layoutId"));.
If your detail activities differ more widely, create a separate Activity class for every list item, and in onListItemClick() create an Intent with the respestive activity class you want to display.
In either case, you can store the details to display (int layoutId or Class<Activity>) in your RowData class so you can easily access it in onListItemClick().
I have a problem with my Android Application. In my Application I have a ListView and each item in it contains some text and an image. I want each of the items to open up a different layout. These layouts will just contain some simple text. But I can't seem to find out how to get my items (in the ListView) to open different layouts. Please help!
package com.xxxxx;
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static final String[] title = new String[] {
"text",
"text",
"text",
"text",
"text",
};
static final String[] detail = new String[] {
"text",
"text",
"text",
"text",
"text",
};
private Integer[] imgid = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],detail[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
RowData item = (RowData) getListAdapter().getItem(position);
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("id", item.mId);
startActivity(intent);
}
}
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
RowData(int id,String title,String detail){
mId=id;
mTitle = title;
mDetail=detail;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mDetail;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
detail = holder.getdetail();
detail.setText(rowData.mDetail);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail() {
if(null == detail){
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
Here is my New Activity
import android.app.Activity;
import android.os.Bundle;
public class NewActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.poetry);
getIntent().getExtras().getInt("id");
}
}
you need to listen to the click on the item, so something like following before you return the convertview
convertView.setOnClickListenere(new OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewActivity.class);
startActivity(intent);
}
});