Android. Open new Activity through ListView? - android

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

Related

How to get selected items in spinner when It is inside custom adapter and selection of items are in activity

I have a customer adapter where my layouts such as buttons edittext,textview,spinner are there.I'm getting all the value of the items in my Activity where there is an action for button of saving.Now I.m having problem on how to get the value inside my spinner because it gets a null value.here's my code
MyAdapter.java
package com.functions;
import java.util.ArrayList;
import java.util.List;
import com.example.senditem.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
String adapter;
private final Activity context;
private final int id;
int listPosition;
public MyAdapter(Activity context, List<Model> list, int id){
super(context, R.layout.userproduct, list);
this.context = context;
this.list = list;
this.id = id;
}
class ViewHolder{
protected TextView text;
EditText quantity;
protected TextView amount;
TextView ext;
Spinner uom;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
listPosition = position;
ViewHolder viewHolder = null;
if(convertView == null){
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.userproduct, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.text.setFocusable(true);
viewHolder.quantity = (EditText) convertView.findViewById(R.id.inputQty);
viewHolder.amount = (TextView) convertView.findViewById(R.id.inputAmt);
viewHolder.uom = (Spinner) convertView.findViewById(R.id.inputUom);
viewHolder.ext = (TextView) convertView.findViewById(R.id.inputTamt);
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.inputQty, viewHolder.quantity);
convertView.setTag(R.id.inputAmt, viewHolder.amount);
convertView.setTag(R.id.inputTamt, viewHolder.ext);
convertView.setTag(R.id.inputUom, viewHolder.uom);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
SqliteHelper db = new SqliteHelper(context);
viewHolder.text.setText(list.get(position).getName());
viewHolder.quantity.setId(position);
viewHolder.amount.setText(String.valueOf(list.get(position).getAmt()));
viewHolder.amount.setId(position);
viewHolder.ext.setId(position);
viewHolder.uom.setId(position);
viewHolder.text.setId(position);
String data = db.getAllDetails(id, list.get(position).getitemId());
String data2 = db.getExt(id,list.get(position).getitemId());
if(data==null)
{
viewHolder.quantity.setText(list.get(position).quantity);
}
else{
viewHolder.quantity.setText(data);
}
if(data2==null)
{
viewHolder.ext.setText(String.valueOf(list.get(position).ext));
}
else{
viewHolder.ext.setText(data2);
}
viewHolder.quantity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final EditText Caption = (EditText) v;
list.get(position).quantity = Caption.getText().toString();
}
}
});
viewHolder.ext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final TextView Caption = (TextView) v;
list.get(position).ext = (float) Integer.parseInt((Caption.getText().toString()));
}
}
});
List<Model> uomlist = (List<Model>) db.selectUom(list.get(position).getitemId());
List<String> myuom = new ArrayList<String>();
for(int j=0;j<uomlist.size();j++){
myuom.add(uomlist.get(j).getUom());
}
ArrayAdapter<String> uomadapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item,myuom);
uomadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.uom.setAdapter(uomadapter);
return convertView;
}
}
UserItemDetailActivity
package com.example.senditem;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.example.senditem.UserMainActivity.ViewHolder;
import com.functions.Model;
import com.functions.MyAdapter;
import com.functions.SqliteHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class UserItemDetailActivity extends Activity {
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
ListView listView;
Button btnSave;
TextView textname;
EditText textqty;
TextView textamt;
Spinner uom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.useritemdetail);
Intent i=getIntent();
final Bundle b = i.getExtras();
final SqliteHelper db = new SqliteHelper(this);
listView = (ListView) findViewById(R.id.detail_list);
btnSave = (Button) findViewById(R.id.btnSave);
adapter = new MyAdapter(this, getModel(), Integer.parseInt(b.get("id").toString())
);
listView.setAdapter(adapter);
uom = (Spinner) findViewById(R.id.inputUom);
Toast.makeText(getBaseContext(), b.get("itemname").toString(),Toast.LENGTH_SHORT).show();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final String currentDateandTime = sdf.format(new Date());
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(final View v) {
listView.clearFocus();
AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
alert.setTitle("Save Details?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
for (int i = 0; i < list.size(); i++) {
if(list.get(i).getQuantity()!=null)
{
float amt = list.get(i).getAmt();
int iqty = Integer.parseInt(list.get(i).getQuantity());
float tamt = amt * iqty;
list.get(i).setTamount(tamt);
list.get(i).setUom(String.valueOf(uom.getSelectedItem()));
db.addItem(new
Model(Integer.parseInt(b.get("id").toString()), list.get(i).getitemId(), list.get(i).getQuantity(),list.get(i).getUom(),list.get(i).getAmt(),list.get(i).getTamount(),currentDateandTime));
}
}
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
}
});
}
private List<Model> getModel() {
Intent i=getIntent();
final Bundle b = i.getExtras();
SqliteHelper db = new SqliteHelper(this);
list = db.getProduct(b.get("itemname").toString());
return list;
}
}
Try this way,hope this will help you to solve your problem.
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
String adapter;
private final Activity context;
private final int id;
int listPosition;
public MyAdapter(Activity context, List<Model> list, int id){
super(context, R.layout.userproduct, list);
this.context = context;
this.list = list;
this.id = id;
}
class ViewHolder{
protected TextView text;
EditText quantity;
protected TextView amount;
TextView ext;
Spinner uom;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
listPosition = position;
ViewHolder viewHolder = null;
if(convertView == null){
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.userproduct, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.text.setFocusable(true);
viewHolder.quantity = (EditText) convertView.findViewById(R.id.inputQty);
viewHolder.amount = (TextView) convertView.findViewById(R.id.inputAmt);
viewHolder.uom = (Spinner) convertView.findViewById(R.id.inputUom);
viewHolder.ext = (TextView) convertView.findViewById(R.id.inputTamt);
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
SqliteHelper db = new SqliteHelper(context);
viewHolder.text.setText(list.get(position).getName());
viewHolder.quantity.setId(position);
viewHolder.amount.setText(String.valueOf(list.get(position).getAmt()));
viewHolder.amount.setId(position);
viewHolder.ext.setId(position);
viewHolder.uom.setId(position);
viewHolder.text.setId(position);
String data = db.getAllDetails(id, list.get(position).getitemId());
String data2 = db.getExt(id,list.get(position).getitemId());
if(data==null)
{
viewHolder.quantity.setText(list.get(position).quantity);
}
else{
viewHolder.quantity.setText(data);
}
if(data2==null)
{
viewHolder.ext.setText(String.valueOf(list.get(position).ext));
}
else{
viewHolder.ext.setText(data2);
}
viewHolder.quantity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
list.get(position).quantity = ((EditText) v).getText().toString();
}
}
});
viewHolder.ext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
list.get(position).ext = (float) Integer.parseInt((((TextView) v).getText().toString()));
}
}
});
List<Model> uomlist = (List<Model>) db.selectUom(list.get(position).getitemId());
List<String> myuom = new ArrayList<String>();
for(int j=0;j<uomlist.size();j++){
myuom.add(uomlist.get(j).getUom());
}
ArrayAdapter<String> uomadapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item,myuom);
uomadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.uom.setAdapter(uomadapter);
return convertView;
}
}

Custom ListView with picture. I can not click on an item and send me to another activity

By clicking on the item, nothing happens. Prompt where I have not correctly implemented method OnItemClickListener.
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.lessons.Lesson1;
public class Lesson extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lesson);
ListView lista = (ListView) findViewById(R.id.itemlist);
ArrayList<Manager> arraydir = new ArrayList<Manager>();
Manager manager;
Resources res = getResources();
// Вводим данные
manager = new Manager(res.getDrawable(R.drawable.lesson1), res.getString(R.string.lesson1), res.getString(R.string.lessonname1));
arraydir.add(manager);
manager = new Manager(res.getDrawable(R.drawable.lesson2), res.getString(R.string.lesson2), res.getString(R.string.lessonname2));
arraydir.add(manager);
AdapterLesson adapter = new AdapterLesson(this, arraydir);
lista.setAdapter(adapter);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) {
TextView textView = (TextView) itemClicked.findViewById(R.id.lessonname);
String strText = textView.getText().toString();
if (strText.equalsIgnoreCase(getResources().getString(R.string.lesson1))) {
// Launch the lesson1 Activity
startActivity(new Intent(Lesson.this, Lesson1.class));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Adapter
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class AdapterLesson extends BaseAdapter{
protected Activity activity;
protected ArrayList<Manager> items;
public AdapterLesson(Activity activity, ArrayList<Manager> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int position) {
return items.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Создаем convertView для эффективности
View v = convertView;
//Связываем формат списка, который мы создали
if(convertView == null){
LayoutInflater inf = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inf.inflate(R.layout.itemlist, null);
}
// Создаем объект директивы
Manager dir = items.get(position);
//Вводим фото
ImageView foto = (ImageView) v.findViewById(R.id.foto);
foto.setImageDrawable(dir.getFoto());
//Вводим номер урока
TextView lessonnumber = (TextView) v.findViewById(R.id.lessonnumber);
lessonnumber.setText(dir.getLessonnumber());
//Вводим название урока
TextView lessonname = (TextView) v.findViewById(R.id.lessonname);
lessonname.setText(dir.getLessonname());
// Возвращаем
return v;
}
}
Manager
import android.graphics.drawable.Drawable;
public class Manager {
protected Drawable foto;
protected String lessonnumber;
protected String lessonname;
protected long id;
public Manager(Drawable foto, String lessonnumber, String lessonname) {
super();
this.foto = foto;
this.lessonnumber = lessonnumber;
this.lessonname = lessonname;
}
public Manager(Drawable foto, String lessonnumber, String lessonname, long id) {
super();
this.foto = foto;
this.lessonnumber = lessonnumber;
this.lessonname = lessonname;
this.id = id;
}
public Drawable getFoto() {
return foto;
}
public void setFoto(Drawable foto) {
this.foto = foto;
}
public String getLessonnumber() {
return lessonnumber;
}
public void setLessonnumber(String lessonnumber) {
this.lessonnumber = lessonnumber;
}
public String getLessonname() {
return lessonname;
}
public void setLessonname(String lessonname) {
this.lessonname = lessonname;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
use this code for click on listitem and go to next extivity..
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch(position){
case 0:
Intent firstIntent = new Intent(yourclass.this, firstitem.class);
startActivity(firstIntent);
break;
case 1:
Intent secondintent = new Intent(yourclass.this, seconditem.class);
startActivity(secondintent);
break;
Try This code only change get view method part
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Создаем convertView для эффективности
View v = convertView;
//Связываем формат списка, который мы создали
if(convertView == null){
LayoutInflater inf = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inf.inflate(R.layout.itemlist, null);
}
// Создаем объект директивы
Manager dir = items.get(position);
//Вводим фото
ImageView foto = (ImageView) v.findViewById(R.id.foto);
foto.setImageDrawable(dir.getFoto());
//Вводим номер урока
TextView lessonnumber = (TextView) v.findViewById(R.id.lessonnumber);
lessonnumber.setText(dir.getLessonnumber());
//Вводим название урока
TextView lessonname = (TextView) v.findViewById(R.id.lessonname);
lessonname.setText(dir.getLessonname());
v.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Intent firstIntent = new Intent(yourclass.this, firstitem.class);
startActivity(firstIntent);
} });
// Возвращаем
return v;
}

Android Picasso Framework, load images asynchronously

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!

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-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