Android Picasso Framework, load images asynchronously - android

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!

Related

List view with custom Layout

I have created a list with a custom row but I do not know what's wrong.
This is the main activity
package com.example.fahdmana.lest;
public class MainActivity extends AppCompatActivity{
ListView listView;
final int[] movie_poster_resouce = {
R.drawable.apple,
R.drawable.banana,
R.drawable.cherry,
R.drawable.mango,
R.drawable.orange,
R.drawable.strawberry,
R.drawable.tomato
};
String[]movies_title;
String[]movies_rating;
MovieAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.List1);
movies_title = getResources().getStringArray(R.array.Movies_names);
movies_rating = getResources().getStringArray(R.array.Ratings);
int i =0;
for (String titles : movies_title){
MovieDataProvider dataProvider =
new MovieDataProvider(movie_poster_resouce[i],titles,movies_rating[i]);
i++;
adapter = new MovieAdapter(getApplicationContext(),R.layout.row);
listView.setAdapter(adapter);
adapter.add(dataProvider);
}
}
}
And this is my adapter
package com.example.fahdmana.lest;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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 java.util.ArrayList;
import java.util.List;
public class MovieAdapter extends ArrayAdapter {
final List list = new ArrayList();
public MovieAdapter( Context context, int resource) {
super(context, resource);
}
static class DataHandeler{
ImageView poster;
TextView title;
TextView rating;
}
#Nullable #Override
public void add( Object object) {
super.add(object);
list.add(object);
}
#Nullable #Override
public int getCount() {
return list.size();
}
#Nullable #Override
public Object getItem(int position) {
return this.list.get(position);
}
#Nullable #Override
public View getView (int position,
#NonNull View convertView,
#NonNull ViewGroup parent) {
View row;
row = convertView;
DataHandeler handler;
if (convertView ==null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row, parent, false);
handler = new DataHandeler();
handler.poster = (ImageView) row.findViewById(R.id.image_view);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.rating = (TextView) row.findViewById(R.id.movie_rating);
row.setTag(handler);
} else {
handler = (DataHandeler) row.getTag();
}
MovieDataProvider dataProvider;
dataProvider = (MovieDataProvider)this.getItem(position);
handler.poster.setImageResource(dataProvider.
getMovie_poster_resource());
//here i get some warning
handler.title.setText(dataProvider.getMovie_title());
handler.rating.setText(dataProvider.getMovie_rating());
return row;
}
}
And this is my data provider
package com.example.fahdmana.lest;
public class MovieDataProvider {
private int movie_poster_resource;
private String movie_title;
private String movie_rating;
public MovieDataProvider(int movie_poster_resource, String movie_title, String movie_rating){
this.setMovie_poster_resource(movie_poster_resource);
this.setMovie_title(movie_title);
this.setMovie_rating(movie_rating);
}
public int getMovie_poster_resource() {
return movie_poster_resource;
}
public void setMovie_poster_resource(int movie_poster_resource) {
this.movie_poster_resource = movie_poster_resource;
}
public String getMovie_title() {
return movie_title;
}
public void setMovie_title(String movie_title) {
this.movie_title = movie_title;
}
public String getMovie_rating() {
return movie_rating;
}
public void setMovie_rating(String movie_rating) {
this.movie_rating = movie_rating;
}
}
I am pretty sure this is your problem.
for (String titles : movies_title){
MovieDataProvider dataProvider =
new MovieDataProvider(movie_poster_resouce[i],titles,movies_rating[i]);
i++;
adapter = new MovieAdapter(getApplicationContext(),R.layout.row);
listView.setAdapter(adapter);
adapter.add(dataProvider);
}
You have this in your main activity. You really dont want to loop through your list and inside of that loop call your adapter.
You want to create a list of your objects and then call the adapter .... something like this...
ListViewAdapterResults adapter = new ListViewAdapterResults(listView.getContext(), scheduleModelList);
listView.setAdapter(adapter);
Where scheduleModelList is my list of objects. Hopefully that makes sense.
Happy coding.
Looking through your code, you may want to do something like this....
Put this at the top
List<MovieDataProvider> list;
Then this right after your setContentView
list = new ArrayList<>();
Replace that loop you have with this:
for (int i = 0; i < movie_title.length; i++) {
list.add(new MovieDataProvider(movie_poster_resouce[i],titles,movies_rating[i]));
}
MovieAdapter adapter = new MovieAdapter(listView.getContext(), list);
listView.setAdapter(adapter);
Let me know if you have any questions.
MovieAdapter (this is your adapter class)
listView.getContext() (this is the ID of your listview [you may have it named something else])
It's been a very long time since I have worked with Arrays.... you have have to +1 or -1 inside of the for loop. (i < movie_title.length [maybe +1 or -1])

error in ListView with image

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.

Android ListView, OnListItemClick, find row id?

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().

Android. Open new Activity through ListView?

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);
}
});

Android-Listview ClickListener

I have a list in which each object is of type Task. I have created a list that sows all the task details in the row of the list.
My code is given below:
lv=this.getListView();
if(createtaskSubList().size() != 0)
{
//createTaskSubList gives me the List of taskObjects
MyCustomAdapter adapter = new MyCustomAdapter(this,createtaskSubList());
lv.setAdapter(adapter);
lv.setDividerHeight(2);
lv.invalidateViews();
}
}
private ArrayList<Task> createtaskSubList() {
// TODO Auto-generated method stub
ArrayList<Task> taskSubList= new ArrayList<Task>();
String[] values={ Integer.toString(userId),Integer.toString(number),Integer.toString(page)};
String taskList = Helper.getfromUrl(taskDataFetch,values);
if(taskList.length()!=0)
{
String delims = ("[|]");
String[] tasks = taskList.split(delims);
int i=0;
//Splitting Task series into individual items
for (i = 0; i < tasks.length; i++) {
String limit = ("','");
String[] taskItem = tasks[i].split(limit);
taskSubList.add(new Task(taskItem[1],Integer.parseInt(taskItem[2]),Integer.parseInt(removeCharAt(taskItem[0],0)),Integer.parseInt(taskItem[4]),Integer.parseInt(taskItem[5]),taskItem[6],Integer.parseInt(taskItem[3])));
}
}
return taskSubList;
}
Now my arrayadpter class is:
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyCustomAdapter extends ArrayAdapter<Task> {
private final Activity context;
ArrayList<Task> taskSubList =new ArrayList<Task>();
public MyCustomAdapter(Activity context,ArrayList<Task> taskSubList) {
super(context, R.layout.teammember, taskSubList);
this.context = context;
this.taskSubList=taskSubList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.teammember, null, true);
final TextView text = (TextView) rowView.findViewById(R.id.label);
final TextView status = (TextView) rowView.findViewById(R.id.status);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//time.setText(formatTime(taskSubList.get(position).getTimeSpent()));
text.setText(taskSubList.get(position).getName());
if(taskSubList.get(position).isCompleted()==0)
{
status.setText("Not Completed");
status.setTextColor(Color.RED);
}
else
{
status.setText("Completed");
status.setTextColor(Color.parseColor("#468765"));
}
return rowView;
}
I need to change it such a way that list should contain only names and when I click on these names an intent has to be called which gives a layout showing the details of that particular TaskObject.Details here means the properties of that task object which should be shown in the form of text views in new layout.Not a dialog or Toast..
In your getView()
status.setOnClickListener(new MyClickListener(position));
public class MyClickListener implements OnClickListener {
private int posi;
public MyClickListener(int position) {
this.posi = position;
}
public void onClick(View v) {
CustomDialog customDialog = new CustomDialog(ViewDetials.this);
customDialog.show();
// Toast.makeText(getBaseContext(), "text view clicked",Toast.LENGTH_SHORT).show();
}
}
}

Categories

Resources