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();
}
}
}
Related
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);
}
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])
I'm tired already with my code. I'm writing chat application. My app consist of two activity. First activity has a listview of wich each row contain a last message which was send for the user while a second activity contain the whole conversation. In my app I used socket.io for android. My app works fine. Listview is refresh when a data is receive but when I press back button and then come back to the activity a listview not refresh itself already. In logs console I see that a data has received and "changed" method is called but listview is not refresh. What is wrong in belows code?
package com.example.seadog.fb_dialog;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import java.util.ArrayList;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends Activity {
public static ArrayList arrayList = new ArrayList();
public ListView listView;
public MyBaseAdapter adapter;
public TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Get Socket.io Object
*/
SocketIO socketIo = new SocketIO();
Socket mSocket = socketIo.getSocket(); // get socket
Integer id = socketIo.getId(); // get Website ID
if(mSocket == null) {
socketIo.Connection();
mSocket = socketIo.getSocket();
mSocket.on("message", new Emitter.Listener() {
/*
* Message Listener
*/
#Override
public void call(Object... args) {
Boolean isset = false;
try {
JSONObject object = (JSONObject) args[0];
String _id = object.getString("_id");
String message = object.getString("message");
JSONObject obj = new JSONObject();
obj.put("direction", "fb-lt");
obj.put("message", message);
obj.put("date", "2017-05-29T12:15:49.245Z");
for(int i = 0; i < arrayList.size(); i++){
ListData ld = (ListData) arrayList.get(i);
String id = ld.getId();
if(_id.equals(id)){
JSONArray Data = ld.getData();
Data.put(obj);
ld.setDescription(message);
arrayList.set(i, ld);
isset = true;
Log.d("LOG", message);
}
}
if(!isset) {
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
ListData ld = new ListData();
ld.set_id(_id);
ld.setID(1);
ld.setTitle("Klient:");
ld.setDescription(message);
ld.setData(jsonArray);
arrayList.add(ld);
}
} catch (JSONException e) {
e.printStackTrace();
}
changed();
}
});
}
/*
* Populate a listview
*/
listView = (ListView) findViewById(R.id.listView);
adapter = new MyBaseAdapter(this, arrayList);
listView.setAdapter(adapter);
/*
* OnItemClickListener
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Conversation.class);
intent.putExtra("item", position);
startActivity(intent);
TextView textView = (TextView) view.findViewById(R.id.descitem);
textView.setTypeface(null, Typeface.NORMAL);
}
});
textView = (TextView) findViewById(R.id.count);
}
private void changed() {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
Log.d("LOG:", "adapter refresh");
}
});
}
}
MyBaseAdapter Class:
package com.example.seadog.fb_dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyBaseAdapter extends BaseAdapter {
Context context;
ArrayList<ListData> items = new ArrayList();
LayoutInflater inflater;
int id = 0;
public MyBaseAdapter(Context context, ArrayList items) {
this.context = context;
this.items = items;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return items.size();
}
#Override
public ListData getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
ListData currentListData = getItem(position);
id = position > 0 ? getItem(position - 1).getID() : 0;
mViewHolder.Title.setText(currentListData.getTitle());
mViewHolder.Desc.setText(currentListData.getDescription());
if(1==1){
mViewHolder.Title.setVisibility(View.GONE);
}else {
if (id != currentListData.getID()) {
mViewHolder.Title.setVisibility(View.VISIBLE);
} else {
mViewHolder.Title.setVisibility(View.GONE);
}
}
return convertView;
}
private class MyViewHolder {
TextView Title, Desc;
public MyViewHolder(View item) {
Title = (TextView) item.findViewById(R.id.txtitem);
Desc = (TextView) item.findViewById(R.id.descitem);
Typeface title = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf");
Title.setTypeface(title);
Typeface desc = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf");
Desc.setTypeface(desc, Typeface.BOLD);
}
}
}
#Override
protected void onRestart() {
Intent intentBack = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intentBack);
super.onRestart();
}
you did not have any callback after you back to this activity .
You can either override onResume() method or startActivityForResult and do something in the onAcitvityForResult method.
I have been trying to learn how to make custom ArrayAdapters to use in some of my Android apps by using this tutorial, but adapting it slightly so that I could fit it with my own application.
I've tested it a couple times now on my phone, but I've found the performance speed to be incredibly slow (when loading and scrolling through the listview). The other activities which do not use this custom ArrayAdapter have a normal performance speed.
I'm not really sure what the problem could be or where in my code it would be, so below, I've posted all of my custom ArrayAdapter class:
package com.mycompany.myapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomArrayAdapter extends ArrayAdapter<String> {
private static class ViewHolder {
TextView tv_Id;
TextView tv_Name;
TextView tv_Group;
}
private Context context;
private ArrayList<String> arr_items;
public CustomArrayAdapter(Context context, ArrayList<String> arr_items) {
super(context, R.layout.listview_advanced, arr_items);
this.context = context;
this.arr_items = arr_items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Person person = new Person(context, arr_items.get(position));
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // View lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_advanced, parent, false);
viewHolder.tv_Id = (TextView) convertView.findViewById(R.id.lvAdv_text1);
viewHolder.tv_Name = (TextView) convertView.findViewById(R.id.lvAdv_text2);
viewHolder.tv_Group = (TextView) convertView.findViewById(R.id.lvAdv_text3);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.tv_Id.setText(person.getIDAsString());
viewHolder.tv_Name.setText(person.getName());
if (person.getGroup().equals("")) {
viewHolder.tv_Group.setText("");
} else {
viewHolder.tv_Group.setText("(" + person.getGroup() + ")");
}
// Return the completed view to render on screen
return convertView;
}
}
Any help would be much appreciated. Thanks.
UPDATE:
Also, before calling the CustomArrayAdapter, I add data to an ArrayList<String> by going through rows of a .csv file and getting that data. At the moment, when reading the .csv file, I have this:
...
ArrayList<String> arr_person = new ArrayList<>(); // Global variable
...
// In a method:
String data = inputStream.nextLine();
String[] line = data.split(",");
if (line.length >1) {
arr_person.add(line[1]);
}
...
CustomArrayAdapter adapter = new CustomArrayAdapter(getActivity(), arr_person);
lv_main.setAdapter(adapter);
How would I adapt this for objects?
UPDATE 2:
My Person object works like this:
private Context context;
private String person, group, someAttribute, ... ;
private int idNumber, scoreOne, scoreTwo, scoreThree, scoreFour, scoreFive, scoreSix, scoreTotal, ... ;
private double ... ;
public Person(Context context, String person) {
this.context = context;
this.person = person;
loadInformation();
}
private void loadInformation() {
InputStreamReader inputStreamReader;
try {
inputStreamReader = new InputStreamReader(context.getAssets().open("PersonsList.csv"));
Scanner inputStream = new Scanner(inputStreamReader);
inputStream.nextLine(); // Ignores the first line
while (inputStream.hasNext()) {
String data = inputStream.nextLine(); // Gets a whole line
String[] line = data.split(","); // Splits the line up into a string array
if (line.length > 1) {
if (line[1].equals(person)) {
idNumber = Integer.parseInt(line[0]);
person = line[1];
group = line[2];
someAttribute = line[3];
scoreOne = Integer.parseInt(line[4]);
scoreTwo = Integer.parseInt(line[5]);
scoreThree = Integer.parseInt(line[6]);
scoreFour= Integer.parseInt(line[7]);
scoreFive = Integer.parseInt(line[8]);
scoreSix = Integer.parseInt(line[9]);
scoreTotal = scoreOne + scoreTwo + scoreThree + scoreFour + scoreFive + scoreSix;
// Same code pattern for defining about 10 more attributes
}
}
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getID() {
return idNumber;
}
public String getIDAsString() {
return format(idNumber);
}
private String format(int number) {
String str_num = String.valueOf(number);
switch (str_num.length()) {
case 1:
str_num = "00" + str_num;
break;
case 2:
str_num = "0" + str_num;
break;
case 3:
// Leave it how it is;
break;
}
return str_num;
}
public String getName() {
return person;
}
public String getGroup() {
return group;
}
public String getSomeAttribute() {
return someAttribute;
}
public int getScoreOne() {
return scoreOne;
}
public int getScoreTwo() {
return scoreTwo;
}
...
Base your array and ArrayAdapter on Person instead of String and make a list of Persons before you set up the adapter. This way you only run the Person constructor once instead of every time you display its view.
ArrayList<Person> arr_person = new ArrayList<>(); // Global variable
...
String data = inputStream.nextLine();
String[] line = data.split(",");
if (line.length > 1) {
Person person = new Person(context, line[1]);
arr_person.add(person);
}
...
CustomArrayAdapter adapter = new CustomArrayAdapter(getActivity(), arr_person);
lv_main.setAdapter(adapter);
...
package com.mycompany.myapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomArrayAdapter extends ArrayAdapter<Person> {
private static class ViewHolder {
TextView tv_Id;
TextView tv_Name;
TextView tv_Group;
}
private Context context;
private ArrayList<Person> persons;
public CustomArrayAdapter(Context context, ArrayList<Person> persons) {
super(context, R.layout.listview_advanced, arr_items);
this.context = context;
this.persons = persons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Person person = persons.get(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // View lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_advanced, parent, false);
viewHolder.tv_Id = (TextView) convertView.findViewById(R.id.lvAdv_text1);
viewHolder.tv_Name = (TextView) convertView.findViewById(R.id.lvAdv_text2);
viewHolder.tv_Group = (TextView) convertView.findViewById(R.id.lvAdv_text3);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.tv_Id.setText(person.getIDAsString());
viewHolder.tv_Name.setText(person.getName());
if (person.getGroup().equals("")) {
viewHolder.tv_Group.setText("");
} else {
viewHolder.tv_Group.setText("(" + person.getGroup() + ")");
}
// Return the completed view to render on screen
return convertView;
}
}
I have created a listActivity with my own ListAdapter. The problem is that the list is viewed in order once launched. But When I scroll down, or go back from another activity, the listView is completely out of order.
I thought the problem was in ArrayList but no, the list is sorted and i'm sure of it because when I loop over all elements in the ArrayList they are printed in the log the same way I inserted them.
I pasted the adapter code below in case anyone would like to check it.
package com.anubis.mail;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class EmailAdapter extends BaseAdapter {
private ArrayList<EmailModel> elements;
private Context c;
public EmailAdapter(Context c, ArrayList<EmailModel> Emails) {
this.elements = Emails;
this.c = c;
}
public int getCount() {
return elements.size();
}
public Object getItem(int position) {
return elements.get(position);
}
public long getItemId(int id) {
return id;
}
public void Remove(int id) {
notifyDataSetChanged();
}
public void Add(EmailModel email) {
this.elements.add(email);
for (EmailModel e : elements){
Log.v("EmailAdapter", e.getSubject());
}
notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowLayout;
EmailModel email = elements.get(position);
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(c).inflate (R.layout.inbox_item, parent, false);
TextView subject_textview = (TextView)rowLayout.findViewById(R.id.subject_textview);
subject_textview.setText(email.getSubject());
String body_hint = " - " + email.getBodyHint();
TextView bodyhint_textview = (TextView)rowLayout.findViewById(R.id.body_hint_textview);
bodyhint_textview.setText(body_hint);
String sender_name = get_sender_name(email.getSender());
TextView sender_name_textview = (TextView)rowLayout.findViewById(R.id.sender_textview);
sender_name_textview.setText(sender_name);
TextView date_time_textview = (TextView)rowLayout.findViewById(R.id.date_time_textview);
date_time_textview.setText(email.getTime());
} else {
rowLayout = (LinearLayout) convertView;
}
return rowLayout;
}
private String get_sender_name(String from) {
String[] sender = from.split("<");
String sender_name;
try {
sender_name = sender[0];
} catch (Exception e) {
sender_name = sender[1];
}
return sender_name;
}
}
You need to move code after the IF
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(c).inflate (R.layout.inbox_item, parent, false);
} else {
rowLayout = (LinearLayout) convertView;
}
TextView subject_textview = (TextView)rowLayout.findViewById(R.id.subject_textview);
subject_textview.setText(email.getSubject());
String body_hint = " - " + email.getBodyHint();
TextView bodyhint_textview = (TextView)rowLayout.findViewById(R.id.body_hint_textview);
bodyhint_textview.setText(body_hint);
String sender_name = get_sender_name(email.getSender());
TextView sender_name_textview = (TextView)rowLayout.findViewById(R.id.sender_textview);
sender_name_textview.setText(sender_name);
TextView date_time_textview = (TextView)rowLayout.findViewById(R.id.date_time_textview);
date_time_textview.setText(email.getTime());
return rowLayout;