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;
Related
I am not getting anything in the listview when i am running this code.
I am trying to get value from server in text view,i am getting value from server in payload object.but still my list view is not showing anything and there is no error in logcat.
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.zalonstyles.app.zalon.Model.Services;
import com.zalonstyles.app.zalon.Model.ViewHolder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
This is the class where i am getting data from server
public class popup_massage extends AppCompatActivity {
public static final String URL = "http://52.41.72.46:8080/service/get_category";
public final String serviceid = "6";
private ListView mainListView;
private Button check;
private List<Services> massagelist = new ArrayList<>();
private Services massageservice[];
private Context context;
public ArrayAdapter<Services> listAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_massage);
SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String value=(mSharedPreference.getString("AppConstant.AUTH_TOKEN", "DEFAULT"));
Log.e("accesslog",value);
mainListView = (ListView) findViewById(R.id.listView4);
check = (Button) findViewById(R.id.button4);
final JSONObject params = new JSONObject();
try {
params.put("service_id",serviceid);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("access_token", value);
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.v("updateUPVolleyRes1",response);
try {
JSONObject jobject = new JSONObject(response);
JSONArray payload = jobject.getJSONArray("payload");
Log.e("payloaddata", String.valueOf(payload));
for (int i = 0; i < payload.length(); i++) {
try{
JSONObject obj = payload.getJSONObject(i);
Services service = new Services();
service.setName(obj.getString("name"));
service.setcategotry_id(obj.getString("id"));
massagelist.add(service);
}finally {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("updateUPVolleyErr", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params1 = new HashMap<String, String>();
params1.put("payload", params.toString());
Log.v("updateUPVolleyParams", params1.toString());
return params1;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id)
{
Services massageservice = listAdapter.getItem(position);
Log.e("CHECKADAPTOR", String.valueOf(massageservice));
massageservice.toggleChecked();
ViewHolder viewHolder =(ViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(massageservice.isChecked());
}
});
//Services[] massageService = (Services[]) getLastNonConfigurationInstance();ArrayList<Services> massagelist = new ArrayList<Services>();
//massagelist.addAll(Arrays.asList(massageService));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new massageArrayAdapter(this,massagelist);
mainListView.setAdapter(listAdapter);
check.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
for (int i = 0; i < listAdapter.getCount(); i++)
{
Services massage = listAdapter.getItem(i);
if (massage.isChecked())
{
Toast.makeText(getApplicationContext(),
massage.getName() + " is Checked!!",
Toast.LENGTH_SHORT).show();
Log.v("My Custom Tag", massage.getName());
}
}
}
});
}
//arrayadapter class//
private static class massageArrayAdapter extends ArrayAdapter<Services>
{
private LayoutInflater inflater;
public massageArrayAdapter(Context context, List<Services> massagelist)
{
super(context, R.layout.customlist_massage, R.id.massagetextview, massagelist);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from((Context) context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// services to display
Services massage = (Services) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null)
{
convertView = inflater.inflate(R.layout.customlist_massage,null );
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.massagetextview);
checkBox = (CheckBox) `enter code here`convertView.findViewById(R.id.checkBox4);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new ViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
Services massage = (Services) cb.getTag();
massage.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else
{
// Because we use a ViewHolder, we avoid having to call
// findViewById().
ViewHolder viewHolder = (ViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the service it is displaying,
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(massage);
// Display planet data
checkBox.setChecked(massage.isChecked());
textView.setText(massage.getName());
return convertView;
}
}
}
My Service class used to store services
public class Services
{
private String name = "";
private boolean checked = false;
private String categotry_id="";
public Services()
{
}
public Services(String name)
{
this.name = name;
}
public Services(String name, boolean checked,String categotry_id)
{
this.name = name;
this.categotry_id = categotry_id;
this.checked = checked;
}
public Services(String name,String categotry_id)
{
this.name = name;
this.categotry_id = categotry_id;
}
public String getCategory_id(String id)
{
return categotry_id;
}
public void setcategotry_id(String categotry_id)
{
this.name = categotry_id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isChecked()
{
return checked;
}
public void setChecked(boolean checked)
{
this.checked = checked;
}
public String toString()
{
return name;
}
public void toggleChecked()
{
checked = !checked;
}
}
View holder class for storing views
public class ViewHolder
{
private CheckBox checkBox;
private TextView textView;
public ViewHolder()
{
}
public ViewHolder(TextView textView, CheckBox checkBox)
{
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox()
{
return checkBox;
}
public void setCheckBox(CheckBox checkBox)
{
this.checkBox = checkBox;
}
public TextView getTextView()
{
return textView;
}
public void setTextView(TextView textView)
{
this.textView = textView;
}
}
my xml class where list view is there
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3F51B5">
<ListView
android:id="#+id/listView4"
android:layout_width="match_parent"
android:layout_height="0px"
android:background="#fff"
android:layout_weight="1" >
</ListView>
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="313dp"
android:text="Continue" />
</LinearLayout>
Please help me through this I need to submit this by tomorrow.
Use this
convertView = inflater.inflate(R.layout.customlist_massage,null ,false );
Instead this
convertView = inflater.inflate(R.layout.customlist_massage,null );
Why you are extending the adapter class ArrayAdapter.
If You want to show something on listview you have to extend it to BaseAdapter OR Recyclerview Adapter.
You dont have any getCount() method in ArrayAdapter see this example::
public class Adapter extends BaseAdapter {
LayoutInflater li;
ArrayList<String> title, details;
Context con;
DataBaseHelper db;
TextView txttitle, txtdetails, txtDate;
Intent in;
public static int i = 1;
View view;
public Adapter (Context cont, ArrayList<String> news_id, ArrayList<String> news) {
this.title = news_id;
this.details = news;
this.con = cont;
li = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
System.out.println("title.size() " + title.size());
return title.size();
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
arg1 = li.inflate(R.layout.adapter_daycare, null);
txttitle = (TextView) arg1.findViewById(R.id.title);
txtdetails = (TextView) arg1.findViewById(R.id.details);
txtDate = (TextView) arg1.findViewById(R.id.txtdate);
view = (View) arg1.findViewById(R.id.view);
}
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println(" formattedDate " + date);
txttitle.setText(title.get(arg0).toString());
txtdetails.setText(details.get(arg0).toString());
txtDate.setText(date);
return arg1;
}
}
I'm trying to update my TextView when my onItenClick event fires, I have several TextViews, they are created as many I want inside my row template, but here goes the problem, when I try to set this TextView value it's acctually getting setted, but another textview, is also setted, with the same value I have on idea of the why to this behavior, but have no idea how to fix it.
My idea:
I my getRowView method (when I scroll the list), I'm seeing an
unusual behavior, once after I set some value to one of my itens, it
keep changing the text view that got this value. So I think here is
the core of the problem.
PS: I'm using the component HeaderListView, if you get another suggestion of framework to do the same thing, I would really appreciate.
PS2: Here goes my code:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import br.com.soutsapp.souts.R;
import br.com.soutsapp.souts.model.Menu;
import br.com.soutsapp.souts.model.Product;
import br.com.soutsapp.souts.model.modelview.OrderItem;
import br.com.soutsapp.souts.userInterface.activity.SectionAdapter;
import br.com.soutsapp.souts.userInterface.adapter.HeaderListView;
public class MenuFragment extends Fragment {
private Context mContext;
private List<OrderItem> itens;
private Menu menu;
public MenuFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_menu, container, false);
mContext = getContext();
itens = new ArrayList<>();
menu = new Menu();
final String[] sec1 = {"aaaaaaaa","aaaaaaaa","aaaaaaaa","aaaaaaaa","aaaaaaaa","aaaaaaaa","aaaaaaaa"};
final String[] sec2 = {"bbbbbbbb","bbbbbbbb","bbbbbbbb","bbbbbbbb","bbbbbbbb","bbbbbbbb","bbbbbbbb"};
final String[] sec3 = {"cccccccc","cccccccc","cccccccc","cccccccc","cccccccc","cccccccc","cccccccc"};
final String[] sec4 = {"dddddddd","dddddddd","dddddddd","dddddddd","dddddddd","dddddddd","dddddddd"};
HeaderListView lv = (HeaderListView) v.findViewById(R.id.lv_menu_items);
lv.setAdapter(new SectionAdapter() {
#Override
public int numberOfSections() {
return menu.getMenuSessions().size();
}
#Override
public int numberOfRows(int section) {
return menu.getMenuSessions().get(section).size();
}
#Override
public Object getRowItem(int section, int row) {
return menu.getMenuSessions().get(section).get(row);
}
#Override
public boolean hasSectionHeaderView(int section) {
return true;
}
#Override
public View getRowView(int section, int row, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(getResources().getLayout(R.layout.menu_item_row), null);
}
//Product product = (Product)getRowItem(section, row);
//convertView.setId(product.getId());
TextView tvMenuItemName = (TextView) convertView.findViewById(R.id.tv_menu_item_name);
TextView tvMenuItemPrice = (TextView) convertView.findViewById(R.id.tv_price);
String itemName = ((Product)getRowItem(section,row)).getName();
tvMenuItemName.setText(itemName);
String itemPrice = String.valueOf(((Product) getRowItem(section, row)).getPrice());
tvMenuItemPrice.setText(itemPrice);
final int mySection = section;
final int myRow = row;
final TextView tvQuantity = (TextView) convertView.findViewById(R.id.tv_quantity);
tvQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Product product = (Product) getRowItem(mySection, myRow);
if (tvQuantity.getText().equals("1") && !tvQuantity.getText().equals("")){
tvQuantity.setText("");
OrderItem itenToRemove = null;
for(OrderItem item: itens){
if(item.getProductId() == product.getId()){
itenToRemove = item;
break;
}
}
itens.remove(itenToRemove);
}
else{
for(OrderItem item: itens){
if(item.getProductId() == product.getId()){
int quantity = item.getQuantity();
item.setQuantity(--quantity);
tvQuantity.setText(String.valueOf(item.getQuantity()));
break;
}
}
}
}
});
return convertView;
}
#Override
public int getSectionHeaderViewTypeCount() {
return 1;
}
#Override
public int getSectionHeaderItemViewType(int section) {
return section % 1;
}
#Override
public View getSectionHeaderView(int section, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = (TextView) getActivity().getLayoutInflater().inflate(getResources().getLayout(android.R.layout.simple_list_item_1), null);
}
if (getSectionHeaderItemViewType(section) == 0) {
((TextView) convertView).setText("Header for section " + section);
} else {
((TextView) convertView.findViewById(android.R.id.text1)).setText("Header for section " + section);
}
switch (section) {
case 0:
convertView.setBackgroundColor(getResources().getColor(R.color.Blue_Jay));
break;
case 1:
convertView.setBackgroundColor(getResources().getColor(R.color.Yellow));
break;
case 2:
convertView.setBackgroundColor(getResources().getColor(R.color.Red_Wine));
break;
}
return convertView;
}
#Override
public void onRowItemClick(AdapterView<?> parent, View view, int section, int row, long id) {
super.onRowItemClick(parent, view, section, row, id);
//Product p = (Product)view.getTag();
TextView tvQuantity = (TextView) view.findViewById(R.id.tv_quantity);
Product p = menu.getMenuSessions().get(section).get(row);
//Product p = (Product) getRowItem(section, row);
boolean exist = false;
for(OrderItem item : itens){
if(item.getProductId() == p.getId()){
int actualQuantity = item.getQuantity();
item.setQuantity(++actualQuantity);
tvQuantity.setText(String.valueOf(item.getQuantity()));
exist = true;
}
}
if(!exist){
itens.add(new OrderItem(p.getId(), 1));
tvQuantity.setText("1");
}
}
});
return v;
}
}
Here goes on screenshot, I had touch the "Smirnoff dose" item, and both "Smirnoff dose" and "Água" have their textviews values changed.
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 am facing the problem to view the checked item of the listview and after if user want to modify the checked item to other item then he can modify check-box. After modify he again want to view what i checked in list. My code not working correct to view what he checked. Please help and it much appreciate
Here is my adapter class:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.kns.model.CategoryModel;
import com.sunil.selectmutiple.R;
public class CategoryAdapter extends BaseAdapter{
private final List<CategoryModel> list;
private final Activity context;
private LayoutInflater mInflater=null;
ArrayList<CategoryModel> list1 = new ArrayList<CategoryModel>();
private static final String TAG="CategoryAdapter";
String catid1;
String catid2;
String catid3;
public CategoryAdapter(Activity context, List<CategoryModel> list, String catid1, String catid2, String catid3) {
// super(context, R.layout.listcheck, list);
mInflater = context.getLayoutInflater();
this.context = context;
this.list = list;
this.catid1=catid1;
this.catid2=catid2;
this.catid3=catid3;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int arg0) {
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = mInflater.inflate(R.layout.cate_list_item, parent, false);
}
CategoryModel p = getProduct(position);
TextView text = (TextView) view.findViewById(R.id.textView_custname);
CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkBox1);
checkbox.setOnCheckedChangeListener(myCheckChangList);
checkbox.setTag(position);
String catid=p.getCat_id();
Log.v(TAG, "Cat id is: "+catid);
Log.v(TAG, "Cat id1 is: "+catid1);
Log.v(TAG, "Cat id2 is: "+catid2);
Log.v(TAG, "Cat id3 is: "+catid3);
if (catid1.trim().equalsIgnoreCase("0") && catid2.trim().equalsIgnoreCase("0") && catid3.trim().equalsIgnoreCase("0")) {
checkbox.setChecked(p.isIsselected());
}
else{
if (catid.trim().equalsIgnoreCase(catid1)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else if (catid.trim().equalsIgnoreCase(catid2)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else if (catid.trim().equalsIgnoreCase(catid3)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else{
checkbox.setChecked(false);
}
}
text.setText(p.getCat_name());
// checkbox.setChecked(p.isIsselected());
return view;
}
CategoryModel getProduct(int position) {
return ((CategoryModel) getItem(position));
}
public ArrayList<CategoryModel> getChecked() {
ArrayList<CategoryModel> list1 = new ArrayList<CategoryModel>();
for (CategoryModel details : list) {
if (details.isIsselected())
list1.add(details);
}
return list1;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ArrayList<CategoryModel> list1=getChecked();
Log.v(TAG, "checked size is: "+list1.size());
if (isChecked) {
if (list1.size() >= 3) {
buttonView.setChecked(false);
//getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
Toast.makeText(context, "Please select max 3 Categories.", Toast.LENGTH_LONG).show();
}
else{
getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
}
}
else{
getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
}
}
};
}
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();
}
}
}