ListItems ArrayList ListView - java

Guys I'm trying to make the below code store multiple items in exampleArray but it's only grabbing the first SectionOutageListItem. Do I need to create another listItem Array to loop through it again?
SectionOutageListItem[] exampleArray = new SectionOutageListItem[outnums.size()];
for(int i = 0; i < outnums.size(); i++) {
exampleArray[i] =
new SectionOutageListItem("Impact", impacted.get(i), "Outage No. " + outnums.get(i)),
new SectionOutageListItem("status", status.get(i), "Outage No. " + outnums.get(i));
}
CustomOutageDetailListAdapter adapter = new CustomOutageDetailListAdapter(this, exampleArray);
sectionAdapter = new SectionOutageListAdapter(getLayoutInflater(),
adapter);
UPDATE:
I have a custom adapter which adds sections to a listview, the SectionOutageListItem determines how many rows are in that section. The outnums.get(i) creates multiple sections which should add the impact and status as rows for each section. It is only adding the first new SectionOutageListItem as a row and not the second one.
Custom List Adapter code
public class CustomOutageDetailListAdapter extends ArrayAdapter<SectionOutageListItem> {
private Activity context;
private SectionOutageListItem[] items;
//private final ArrayList<String> itemname;
public CustomOutageDetailListAdapter(Activity context, SectionOutageListItem[] items) {
super(context, R.layout.mylistoutagedetails, items);
this.items= items;
this.context = context;
}
#Override
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.mylistoutagedetails, null,true);
final SectionOutageListItem currentItem = items[position];
if (currentItem != null) {
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
TextView txtName = (TextView) rowView.findViewById(R.id.name);
if (txtTitle != null) {
txtTitle.setText(currentItem.item.toString());
}
if (txtName != null) {
txtName.setText(currentItem.name.toString());
}
}
return rowView;
};

As #Trobbins points out ,
You may need to change the code as follows,
SectionOutageListItem[][] exampleArray = new SectionOutageListItem[outnums.size()][2];
for(int i = 0; i < outnums.size(); i++) {
exampleArray[i][0] =
new SectionOutageListItem("Impact", impacted.get(i), "Outage No. " + outnums.get(i));
exampleArray[i][1] = new SectionOutageListItem("status", status.get(i), "Outage No. " + outnums.get(i));
}
CustomOutageDetailListAdapter adapter = new CustomOutageDetailListAdapter(this, exampleArray);
sectionAdapter = new SectionOutageListAdapter(getLayoutInflater(),
adapter);
You can also go with a Map specifically LinkedHashMap if you want to maintain the insertion order or else HashMap

Related

Android how to append custom listView using SharedPreferences

i want to update my ListView using SharedPreferences get from API response...
I did something like this:
First i inintial the Strings[]:
String First[] = {"aa"};
String Second[] = {"aa"};
String Third[] = {"aa"};
String Four[] = {"aa"};
Integer Five[] = {1};
I want to update this using the Shared Preferences
SharedPreferences settings;
settings = getSharedPreferences("Number_List", Context.MODE_PRIVATE);
String uFirst = settings.getString("uFirst", "NONE");
String uSecond = settings.getString("uSecond", "NONE");
String uThird = settings.getString("uThird", "NONE");
String uFour = settings.getString("uFour", "NONE");
int uFive= settings.getInt("uFive", 0);
First = Arrays.copyOf(First, First.length + 1);
Second= Arrays.copyOf(Second, Second.length + 1);
Third= Arrays.copyOf(Third, Third.length + 1);
Four= Arrays.copyOf(Four, Four.length + 1);
Five= Arrays.copyOf(Five, Five.length + 1);
First[First.length -1] = uFirst;
Second[Second.length -1] = uSecond;
Third[Third.length -1] = uThird;
Four[Four.length -1] = uFour;
Five[Five.length -1] = uFive;
adapter.notifyDataSetChanged();
And this code never refreshing the listview... Im totally without any ideas how to make it more automatically.. Every time when im adding another things in list eg. First[] = {"aaa","bbbb"}; it works properly...
Can someone take the time to help?
Adapter:
class listDataAdapter extends ArrayAdapter<String> {
Context context;
String rFirst[];
String rSecond[];
String rThird[];
String rFour[];
Integer Five[];
listDataAdapter(Context c, String rFirst[], String rSecond[], String rThird[], String rFour[], Integer Five[]) {
super(c, R.layout.listview_row_orders, R.id.data_zal_text, rFirst);
this.context = c;
this.rFirst = rFirst;
this.rSecond = rSecond;
this.rThird = rThird;
this.rFour = rFour;
this.Five = Five;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.listview_row_orders, parent, false);
TextView myFirst = row.findViewById(R.id.data_zal_text_data);
TextView mySecond = row.findViewById(R.id.data_rozl_text_data);
TextView myThird = row.findViewById(R.id.place_zal_text_data);
TextView myFour = row.findViewById(R.id.place_rozl_text_data);
ProgressBar myOrderProgress = row.findViewById(R.id.progress_order_status);
myFirst.setText(rFirst[position]);
mySecond.setText(rSecond[position]);
myThird.setText(rThird[position]);
myFour.setText(rFour[position]);
myOrderProgress.setProgress(Five[position]);
return row;
}
```
The problem is that you have updated the values in you activity, but in the adapter you still have the old values so notifyDataSetChanged will just work with the same values, you need to replace the old array values on the adapter with the new array values, you can create a simple helper method to do that in the adapter class for example
public void updateData(String[] firstArray) {
this.first = firstArray;
notifyDataSetChanged();
}

Custom array push data with loop

I have a custom class to data set User.java
public class User {
public int icon;
public String title;
public User(){
super();
}
public User(int icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
Also have a custom adapter UserAdapter.java
public class UserAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
User data[] = null;
public UserAdapter(Context context, int layoutResourceId, User[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.list_image);
holder.txtTitle = (TextView)row.findViewById(R.id.title);
row.setTag(holder);
}
else
{
holder = (UserHolder)row.getTag();
}
User User = data[position];
holder.txtTitle.setText(User.title);
holder.imgIcon.setImageResource(User.icon);
return row;
}
static class UserHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
I am trying to push data from webservice with the code
public User user_data[] = new User[500];
try {
JSONObject object_exc = response;
JSONArray jArray = object_exc.getJSONArray("exercise");
for (int i = 0; i < jArray.length(); i++) {
JSONObject object = jArray.getJSONObject(i);
user_data[i] = new User(R.drawable.nopic, object.getString("name"));
}
}catch (Exception e){
}
But it is returning null exception where as
User user_data[] = new User[]
{
new User(R.drawable.weather_cloudy, "Cloudy"),
new User(R.drawable.weather_showers, "Showers"),
new User(R.drawable.weather_snow, "Snow"),
new User(R.drawable.weather_storm, "Storm"),
new User(R.drawable.weather_sunny, "Sunny")
};
this is working fine. Please some one help
Try to use ArrayList instead of User[] array.
ArrayList<User> list = new ArrayList<User>();
To add a user to this list.
Just like:
list.add(new User(xxx, yyy));
IMHO there are a couple of problem in your code.
1 - Json file source
JSONArray jArray = object_exc.getJSONArray("exercise");
The constructor request a string that represent a json string. Obviously "exercise" is not a valid json. So you will never find "name" field..so the problem is here!!!
Improvements
2 - Using pure array structure
Maybe is better use an ArrayList is a better option for next manipulation data. (for example sorting!)
3 - object.getString(String abc)
I suggest you to use
object.optString("name", "no_name")
in this way you can put a default return value and avoid other problems. read this SO thread
JSON: the difference between getString() and optString()

Get the ID of checkbox from custom adapter in android?

I have a Custom ArrayList as follows.
public class sendivitesadapter extends ArrayAdapter<Item>{
private Context context;
private ArrayList<Item> items;
private qrusers qrusers;
private LayoutInflater vi;
public sendivitesadapter(Context context,ArrayList<Item> items) {
super(context, 0,items);
this.context= context;
this.qrusers =(qrusers) context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return super.getCount();
}
#Override
public Item getItem(int position) {
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());
}else{
sendItem ei = (sendItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
final TextView title = (TextView)v.findViewById(R.id.contactname);
final TextView subtitle = (TextView)v.findViewById(R.id.companyname);
final CheckBox checkBox=(CheckBox)v.findViewById(R.id.checboxlist);
if (title != null)
title.setText(ei.contactname);
if(subtitle != null)
subtitle.setText(ei.companyname);
}
}
return v;
}
and it looks like following image.
My java file is as follows.
#Override
protected void onPostExecute(String result) {
JSONArray jarray;
try {
jarray= new JSONArray(result);
name= new String[jarray.length()];
company=new String[jarray.length()];
for (int i=0;i<jarray.length();i++){
JSONObject jobj = jarray.getJSONObject(i);
name[i]= jobj.getString("Name");
company[i]=jobj.getString("Company");
items.add(new sendItem(name[i], company[i], checkBox));
adapter = new sendivitesadapter(qrusers.this,items);
listView.setAdapter(adapter);
Now I get the names from webservice which I am diplaying it in a listview as shown above.
With every name I get a USerID. So my question is whenever the user checks the checkbox in any sequence and click on add user I want the UserID of the checked checkboxes in array. How can I achieve this?
Sounds like it's a good candidate for View.setTag(). You could set the tag on each CheckBox to the id of the user [when you create it, or assign the Name and Company values]. Then in an OnClick or OnChecked type event, you can call view.getTag() to retrieve the id of the currently checked box.
You need to use OnCheckedChangeListener to get the cheched CheckBox ID. This SO will help you- How to handle onCheckedChangeListener for a RadioGroup in a custom ListView adapter . You need to modify the onCheckedChangeListener according to your need.
In your adapter set the position in check box like
checkBox.setTag(position);
And as i think you have to add checked user on click of Add User button. So on click of that button write following code.
public void onClick(View v) {
// TODO Auto-generated method stub
String categoryArray = "";
String[] categoryId;
if(v == AddUser){
int count = 0;
for(int i = 0; i < listViewRightSlideMenu.getChildCount(); i ++){
RelativeLayout relativeLayout = (RelativeLayout)listViewRightSlideMenu.getChildAt(i);
CheckBox ch = (CheckBox) relativeLayout.findViewById(R.id.checkBoxCategory); //use same id of check box which you used in adapter
if(ch.isChecked()){
count++;
categoryArray = categoryArray+ch.getTag()+",";
}
}
if(categoryArray.length() > 0) {
categoryArray = categoryArray.substring(0, categoryArray.length() - 1);
String[] array = categoryArray.split(",");
categoryId = new String[array.length];
for(int i = 0; i< array.length; i++) {
categoryId[i] = listCategory.get(Integer.valueOf(array[i])).getId();
}
for(int i = 0; i < categoryId.length; i++){
String a = categoryId[i];
System.out.println("category id is: "+a);
}
System.out.println("array position: "+categoryId);
}
}

Set bind view in simple adapter?

I want to setup view binder in simple adapter to show photos from contacts, however I set two text view's with name and number with Hash Map, so third value is Image View where I want to put contact photo corresponding to contact ID.
Thank you in advance, Wolf.
Here is my code :
ArrayList<HashMap<String, String>> mapa = new ArrayList<HashMap<String, String>>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cur.getCount() > 0){
while(cur.moveToNext()){
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String photoUri = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
if(Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
final Cursor numCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
for(numCur.moveToFirst(); !numCur.isAfterLast(); numCur.moveToNext()){
brTel = numCur.getString(numCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ime = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
tmpIme = new String[] {ime};
for(int i = 0; i < tmpIme.length; i++){
HashMap<String, String> imeMapa = new HashMap<String, String>();
imeMapa.put("imeLista", ime);
imeMapa.put("checkBox", photoUri);
imeMapa.put("Mobilni", brTel);
mapa.add(imeMapa);
}
}
numCur.close();
}
} // While
}
SimpleAdapter sa = new SimpleAdapter(getApplicationContext(), mapa, R.layout.imenik, new String[] {"imeLista", "checkBox", "Mobilni"}, new int[] {R.id.tvImeImenik, R.id.cbOznaci, R.id.tvSamoProba});
sa.setViewBinder(simpleSlika);
lImenik.setAdapter(sa);
and my view binder is :
private final SimpleAdapter.ViewBinder simpleSlika = new SimpleAdapter.ViewBinder() {
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if (view instanceof ImageView && data instanceof Bitmap) {
ImageView v = (ImageView)view;
v.setImageBitmap((Bitmap)data);
// return true to signal that bind was successful
return true;
}
return false;
}
};
but it's not working.
Help please???
Yes its possible, you just create your own adapter (extends BaseAdapter), override getView method and there add bitmap to imageview.
public ContactAdapter(Activity a,ArrayList<Object> list)
{
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View v=convertView;
if(convertView==null)
v = inflater.inflate(R.layout.contact, null);
ImageView image = (ImageView)v.findViewById(R.id.img);
}
Something like this. You have to extends this.
Check also : Lazy load of images in ListView

Sorting a ListView with ArrayAdapter<String>

I have a custom ListView, each list item has four TextViews showing bank name, amount, date and time. This data is stored in a database. The idea is that on the Activity there is a quick action dialog which opens on clicking the sort button. The Dialog has three options as "Sort by bank name" ascending order, "Sort by Date" newest first and "Sort by amount" larger amount in the top of the list. I don't have any idea of how to proceed with the sorting task to be written in onItemClick(int pos). Can anyone please help me on this?
public class TransactionMenu extends Activity implements OnItemClickListener, OnActionItemClickListener {
String[] TransId ;
String[] mBankName;
String[] mAmount;
String[] mDate;
String[] mTime;
Button SortButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transaction_screen);
SortButton = (Button)findViewById(R.id.sortKey);
//Bank Name action item
ActionItem bName = new ActionItem();
bName.setTitle("Bank Name");
bName.setIcon(getResources().getDrawable(R.drawable.bank_256));
//Amount action item
ActionItem amt = new ActionItem();
amt.setTitle("Amount");
amt.setIcon(getResources().getDrawable(R.drawable.cash));
//date action item
ActionItem date = new ActionItem();
date.setTitle("Date");
date.setIcon(getResources().getDrawable(R.drawable.calender));
//create quickaction
final QuickAction quickAction = new QuickAction(this);
quickAction.addActionItem(bName);
quickAction.addActionItem(amt);
quickAction.addActionItem(date);
quickAction.setOnActionItemClickListener(this);
SortButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
//quickAction.setAnimStyle(QuickAction.ANIM_REFLECT);
}
});
DBAdapter lDBAdapter = new DBAdapter(this);
lDBAdapter.open();
/* getTransDetails() returns all the detials stored in the transaction table*/
Cursor mCursor =lDBAdapter.getAllTransDetails();
System.out.println("cur..........."+mCursor);
lDBAdapter.close();
if (mCursor != null) {
int size = mCursor.getCount();
if (mCursor.moveToFirst()) {
TransId = new String[size];
mAmount = new String[size];
mBankName = new String[size];
mDate = new String[size];
mTime = new String[size];
for (int i = 0; i < size; i++, mCursor.moveToNext()) {
TransId[i] = mCursor.getString(0);
mAmount[i] = mCursor.getString(1);
mBankName[i] = mCursor.getString(3);
mDate[i] = mCursor.getString(2);
mTime[i] = mCursor.getString(4);
}
}
}
for (int i = 0; i < mCursor.getCount(); i++) {
System.out.println("TransId is+++++++++++++++ "+TransId[i]);
System.out.println("amount is+++++++++++++++ "+mAmount[i]);
System.out.println("bankName is+++++++++++++++ "+mBankName[i]);
System.out.println("date is+++++++++++++++ "+mDate[i]);
System.out.println("time is+++++++++++++++ "+mTime[i]);
}
ListView myListView = (ListView) findViewById(R.id.transactionListView);
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
myListView.setAdapter(myAdapterObj);
myListView.setOnItemClickListener((OnItemClickListener) this);
}
private class MyBaseAdapter extends ArrayAdapter<String> {
public MyBaseAdapter(Context context, int textViewResourceId, String[] transId) {
super(context, textViewResourceId, transId);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_item, parent, false);
TextView label = (TextView)row.findViewById(R.id.textview1);
label.setText("Amount: "+mAmount[position]);
TextView label1 = (TextView) row.findViewById(R.id.textview2);
label1.setText("Bank Name: "+mBankName[position]);
TextView label2 = (TextView) row.findViewById(R.id.textview3);
label2.setText("Date: "+mDate[position]);
TextView label3 = (TextView) row.findViewById(R.id.textview4);
label3.setText("Time: "+mTime[position]);
return row;
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("arg2 is++++++++++++++"+arg2);
int lRowId = Integer.parseInt(TransId[arg2]);
}
public void onItemClick(int pos) {
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
if (pos == 0) {
Toast.makeText(TransactionMenu.this, "Bank name item selected", Toast.LENGTH_SHORT).show();
}
else if (pos ==1) {
Toast.makeText(TransactionMenu.this, "amount item selected", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(TransactionMenu.this, "Date item selected", Toast.LENGTH_SHORT).show();
}
}
}
I will give you the way i would do this, not the best probably but it will work fine.
Fisrt of all as user7777777777 said it's better to keep related infos into the same object so i'd define BankInfo class as shown below:
private class BankInfo{
String TransId ;
String mBankName;
String mAmount;
String mDate;
String mTime;
public BankInfo(String TransId,String mBankName,String mAmount,String mDate,String mTime)
{
//fields init
}
}
once you have this you will define an Array of this object BankInfo[] trans. In the adapter you can use this array to bind values into views.
then to manage to implement the sorting function the thing i would do is to put a static variable into the BankInfo class and override the CompareTo() method to use that field:
static int AMMOUNT = 0;
static int DATE = 1;
static int NAME = 2;
static public int sort_by;
public int compareTo(BankInfo info){
switch (sorty_by){
case(AMMOUNT):
return //compare by ammount
case(DATE):
return //compare by date
case(NAME):
return //compare by name
}
}
with this inside of BankInfo you will have only to add your array to a TreeSet<BankInfo> and all your item will be sortet using the compareTo() method.
Inside the adapter put this method to sort elements in the adapter
public void sort_datas(int sort_by);
{
//set the type of sort you want
BankInfo.sortBy = sort_by;
//build a Sorted treeSet by the BankInfo array
TreeSet<BankInfo> sorted_info = new TreeSet<BankInfo>();
list.addAll(Arrays.asList(trans));
//replace the BankInfo array with the new sorted one
trans = (BankInfo[])sorted_info.toArray();
//notify to the adapter that the data set changed
notifyDataSetChanged();
}
You can use the following code. You need to maintain the bank info in a BankInfo object. Create an ArrayList of BankInfo objects and then you can use this code. Its not a good practice to keep related info into separate arrays.
Collections.sort(mBankInfoArrayList, new Comparator<BankInfo>() {
int compare(BankInfo obj1, BankInfo obj2) {
return obj1.getBankName().compareToIgnoreCase(obj2.getBankName());
}
});

Categories