Android ListView, OnListItemClick, find row id? - android

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

Related

How to get gridview multiple positions and store into array variable

Now I am displaying images in grid-view, it working fine. In that grid-view i am going to select few images, i want store selected multiple images position in array variable (example: if i select position 1, 4 ,10. i want that particular position id and i want to store it array like 1,4,10,15,). I will put my activity and adapter code below. Thank you in advance.
Activity
public class EM_event_total_userSeats extends AppCompatActivity implements RestCallback,AdapterView.OnItemClickListener {
String user_id,first_name,last_name,name,emailid,contact_no,gender1,date_of_birth,country_id,postal_code,rolename,profession_response,Street_Address,City,photo;
GridView GridUserSeats;
;
TextView textView1,textView2,Tvposition;
ImageView Ivseats;
public static EM_event_total_userseatsAdapter adapter;
ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist;
View savedView;
View previous = null;
String event_id = "EVEPRI62";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.em_event_total_user_seats);
initviews();
callSeatsApi();
GridUserSeats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
String a = String.valueOf(position);
Toast.makeText(EM_event_total_userSeats.this, a + "#Selected", Toast.LENGTH_SHORT).show();
v.setBackgroundColor(Color.GREEN);
adapter.notifyDataSetChanged();
}
});
}
private void initviews() {
GridUserSeats=(GridView)findViewById(R.id.GridUserSeats);
GridUserSeats.setOnItemClickListener(this);
textView1=(TextView) findViewById(R.id.textView1);
// textView2=(TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
first_name = intent.getStringExtra("first_name");
last_name = intent.getStringExtra("last_name");
}
private void callSeatsApi() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("events", event_id);
RestService.getInstance(EM_event_total_userSeats.this).getUserSeats(map, new MyCallback<ArrayList<EM_event_total_UserSeatsModel>>(EM_event_total_userSeats.this,
EM_event_total_userSeats.this, true, "Finding seats....", GlobalVariables.SERVICE_MODE.EM_SEATS));
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode)
{
switch (mode)
{
case EM_SEATS:
EMeventuserseatslist = (ArrayList<EM_event_total_UserSeatsModel>)response.body();
adapter = new EM_event_total_userseatsAdapter(EMeventuserseatslist, getApplicationContext());
GridUserSeats.setAdapter(adapter);
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
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 android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import cfirst.live.com.R;
import cfirst.live.com.model.BasketModel;
import cfirst.live.com.model.EM_event_total_UserSeatsModel;
public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist = new ArrayList<EM_event_total_UserSeatsModel>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private String[] mobileValuesD;
private static class ViewHolder {
TextView TvEmUserSeats;
ImageView IvUsreSeats,available,selctedimag;
}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();
public EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
super(context, R.layout.list_em_get_seats, data);
this.dataSet = data;
this.mContext=context;
}
public int getTagFromPosition(int position) {
return tagCollection[position];
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(tagCollection[position]);
EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel) object;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
EM_event_total_UserSeatsModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);
viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
String blue_available = "seat3.png";
String red_booked = "seat1.png";
String get_seat = dataModel.getBookedStatus();
viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
if(Integer.parseInt(get_seat) == 1){
Picasso.with(mContext).load("imageurl + red_booked).into(viewHolder.IvUsreSeats);
}else
{
Picasso.with(mContext).load("imageurl + blue_available).into(viewHolder.IvUsreSeats);
}
return convertView;
}
}
It's simple. You can use SparseBooleanArray for this purpose. Just add the following methods as is in your adapter:
public void toggleSelection(int item) {
if (selectedItems.get(item, false)) {
selectedItems.delete(item);
} else {
selectedItems.put(item, true);
}
notifyDataSetChanged();
}
public void setSelectedItems(List<Object> objects) {
if (objects != null) {
for (Object object : objects) {
toggleSelection(object.getId());
}
notifyDataSetChanged();
}
}
public void clearSelections() {
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<Integer>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
Use the set selection method to store the selected status of your item.
Don't forget to initialize SparseBooleanArray in your constructor.
SparseBooleanArray SparseBooleanArray = new SparseBooleanArray();
After that, use toggleSelection(position); to change the selected status of an item, then after performing selections, call getSelectedItem() to get the selected items in an array.
// create an Arraylist and add the selected position in a list
List <int> selectedArray = new ArrayList<>();
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int click = (int) parent.getItemAtPosition(position);
selectedArray.add(click);
}

Android ListAdapter, Passing selected list items to new activity, creating ParseRelation

In my app, I have the goal of, when a user selects a list item, that ParseObject becomes associated with that user. I am using a ListAdapter to create a CustomList.
Here is my List Activity:
package android.bignerdranch.com.mobilemidwife;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseQueryAdapter;
public class MidwifeResultList extends ListActivity {
private ParseQueryAdapter<ParseObject> mainAdapter;
private CustomMidwifeAdapter midwifeListAdapter;
//calls Adapter; Adapter manages data model
//adapts it to individual entries in widget
//inflates, assigns it to rows
ArrayAdapter<String> madapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//initialize main ParseQueryAdapter
mainAdapter = new CustomMidwifeAdapter(this);
//which keys in Midwife object
mainAdapter.setTextKey("practicename");
mainAdapter.setTextKey("education");
mainAdapter.setTextKey("yearsinpractice");
mainAdapter.setTextKey("practicephilosophy");
setListAdapter(mainAdapter);
mainAdapter.loadObjects();
}
protected void onListItemClick (ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(this, SelectedMidwife.class);
intent.putExtra("practicename", "practicename");
startActivity(intent);
}
}
I have this Adapter:
public class CustomMidwifeAdapter extends ParseQueryAdapter<ParseObject> {
public CustomMidwifeAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
// Here we can configure a ParseQuery to display
// midwives
ParseQuery query = new ParseQuery("midwifefirm");
query.whereEqualTo("userType", "midwife");
return query;
}
});
}
#Override
public View getItemView(ParseObject object, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.activity_midwife_result_list, null);
}
//use midwifefirm as item view/list
super.getItemView(object, view, parent);
// find in layout the practice name
TextView titleTextView = (TextView) view.findViewById(R.id.practicename);
//in the midwifefirm data model, call getPracticename
titleTextView.setText(object.getString("practicename"));
// Add education view
TextView EducationView = (TextView) view.findViewById(R.id.education);
EducationView.setText(object.getString("education"));
// Add yearsexperience view
TextView ExperienceView = (TextView) view.findViewById(R.id.yearsinpractice);
ExperienceView.setText(object.getString("yearsinpractice"));
//Add practice philosophy view
TextView PracticePhilosophyView = (TextView) view.findViewById(R.id.practicephilosophy);
PracticePhilosophyView.setText(object.getString("practicephilosophy"));
return view;
}
}
Ordinarily, I would setup a for loop, loop through the listitems..not sure where to start.
Thanks for any help.
Michael
Here is how I have handled custom adapters with listviews using parse. Hopefully this helps.
//setting up the listview
mYourListView = (ListView) findViewById(R.id.yourListView);
mYourCustomAdapter = new YourCustomAdapter(yourActivity.this, new ArrayList<whateverYourParseClassIs>());
mYourListView.setAdapter(mYourCustomAdapter);
YourCustomAdapter.java
public class YourCustomAdapter extends ArrayAdapter<whateverYourClassIs> {
private final Context mContext;
private List<whateverYourClassIs> mNumbers;
private TextView mNumber1;
private TextView mNumber2;
public YourCustomAdapter(Context context, List<whateverYourClassIs> objects) {
super(context, R.layout.your_layout_for_adapter, objects);
this.mContext = context;
this.mNumbers = objects;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null) {
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.your_layout_for_adapter, null);
}
final whateverYourClassIs individualRecord = mNumbers.get(position);
mNumber1 = (TextView) convertView.findViewById(R.id.number1);
mNumber2 = (TextView) convertView.findViewById(R.id.number2);
mNumber1.setText(String.valueOf(individualRecord.get("whatever you want")));
mNumber2.setText(String.valueOf(individualRecord.get("whatever you want")));
return convertView;
}
}
YourQuery
public void updateYourData() {
ParseQuery<whateverYourClassIs> query = ParseQuery.getQuery(YourParseClass.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<whateverYourParseclass>() {
#Override
public void done(List<whateverYourParseclass> objects, ParseException error) {
if (objects != null) {
mYourCustomAdapter.add(objects.get(0));
mYourCustomAdapter.notifyDataSetChanged();
}
}
});
}
Or a query that has a loop
public void updateYourData() {
ParseQuery<whateverYourClassIs> query = ParseQuery.getQuery(YourParseClass.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<whateverYourParseclass>() {
#Override
public void done(List<whateverYourParseclass> objects, ParseException error) {
if (objects != null) {
mYourCustomAdapter.clear();
for (int i = 0; i < objects.size(); i++) {
mYourCustomAdapter.add(objects.get(i));
mYourCustomAdapter.notifyDataSetChanged();
}
}
In your adapter you simply get the objects (and it's position) passed into it by your query and query specific column names you want to get information from. Let me know if this helps or if you need any clarification.

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