Android Studio : Problems accessing Sub-Item in non activity class - java

Update :
the Grid is now displayed correctly, but the content is missing
I checked
String text[] = getResources().getStringArray(R.array.main_table);
and text is filled with the Strings and if I use the code in the activity file the data is shown.
Any ideas
Original Question
I am having problems using findViewById() in non-activity classes.
If I am on the top Level, it is no problem.
((Activity)context).findViewById(R.id.statistic_grid);
But when I am trying to reference child views, I am getting "null"
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view.findViewById(R.id.statistic_cell_text);
Can please anybody help me out.
Thanks in advance
Lars
public class MainStatisticGridView extends GridView {
public MainStatisticGridView(Context context) {
super(context);
GridView statistic = (GridView) ((Activity)context).findViewById(R.id.statistic_grid);
String[] from = new String[]{"text"};
int[] to = new int[]{R.id.statistic_cell_text};
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
String text[] = getResources().getStringArray(R.array.main_table);
for (int i = 0; i < text.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("text", text[i]);
fillMaps.add(map);
}
SimpleAdapter adapter = new MyCursorAdapter(((Activity)context), fillMaps, R.layout.calendar_title_cell, from, to);
statistic.setAdapter(adapter);
}
private class MyCursorAdapter extends SimpleAdapter {
public MyCursorAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Set<Integer> VALUES = new HashSet<Integer>(Arrays.asList(
new Integer[]{0, 1, 2, 3, 4, 5, 10, 15, 20}
));
View view = super.getView(position, convertView, parent);
if (VALUES.contains(Integer.valueOf(position))) {
view.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
TextView tv = (TextView) view.findViewById(R.id.statistic_cell_text);
tv.setTextColor(getResources().getColor(R.color.statistic_title));
view.setPadding(0, 0, 0, 0);
} else {
view.setBackground(getResources().getDrawable(R.drawable.border_intern));
}
return view;
}
}
}

You need to inflate the layout, like this. Once you inflate the layout you can get the child items.
private class MyCursorAdapter extends SimpleAdapter {
//private variables
Context context;
LayoutInflater inflater;
public MyCursorAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
this.context = context;
//get layoutinflater
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Set<Integer> VALUES = new HashSet<Integer>(Arrays.asList(
new Integer[]{0, 1, 2, 3, 4, 5, 10, 15, 20}
));
//inflate your layout
if(convertView==null)
{
convertView = inflater.inflater(layoutfile, parent,false);
}
if (VALUES.contains(Integer.valueOf(position))) {
convertView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
TextView tv = (TextView) convertView.findViewById(R.id.statistic_cell_text);
tv.setTextColor(getResources().getColor(R.color.statistic_title));
convertView.setPadding(0, 0, 0, 0);
} else {
convertView.setBackground(getResources().getDrawable(R.drawable.border_intern));
}
return convertView;
}
}
Please note I did not test this.

Related

List view does not diplay items from custom array adapter

i have created a custom array adapter for my list view but for some reason the data is not getting displayed in listview item. even the log cat doesnt show anything when i put log statement in getView method of the custom adapter which extends ArrayAdapter.
This is the activity that holds listview
public class booktable extends AppCompatActivity {
ListView mylv;
int[] array = new int[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booktable);
mylv = findViewById(R.id.mylv);
array = new int[]{1, 0, 0, 0, 1};
ListAdapter la = new customadapter(getApplicationContext(),R.layout.activity_booktable,array);
mylv.setAdapter(la);
}
}
this is my custom adapter
public class customadapter extends ArrayAdapter {
LayoutInflater li;
int[] table = new int[5];
public customadapter(#NonNull Context context,int resource, int [] array) {
super(context,resource);
li = LayoutInflater.from(context);
table = array;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = li.inflate(R.layout.custom_row,parent);
ImageView img = v.findViewById(R.id.img);
TextView tv = v.findViewById(R.id.tv);
if(table[position]==0)
{
tv.setText("FULL");
tv.setTextColor(Color.RED);
}
if(table[position]==1)
{
tv.setText("AVAILABLE");
tv.setTextColor(Color.GREEN);
}
return v;
}
}
try to pass the parameter array or collection to ArrayAdapter constructor, Looks like this:
public customadapter(#NonNull Context context,int resource, int [] array) {
super(context, resource, array);
li = LayoutInflater.from(context);
table = array;
}

No data shown in GridView when created in non Activity class

When I use following code in an Activity class, it works fine but when moved into a separate class, the Table is drawn, but no content is shown.
String text[] = getResources().getStringArray(R.array.main_table);
I checked all variables (text, fillMaps, from to), and the correct data is available. Also if I use the standard SimpleAdapter, the result is the same.
If anybody has an idea, I would be grateful.
public class MainStatisticGridView extends GridView {
public MainStatisticGridView(Context context) {
super(context);
GridView statistic = (GridView) ((Activity)context).findViewById(R.id.statistic_grid);
String[] from = new String[]{"text"};
int[] to = new int[]{R.id.statistic_cell_text};
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
String text[] = getResources().getStringArray(R.array.main_table);
for (int i = 0; i < text.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("text", text[i]);
fillMaps.add(map);
}
SimpleAdapter adapter = new MyCursorAdapter(context, fillMaps, R.layout.calendar_title_cell, from, to);
statistic.setAdapter(adapter);
}
private class MyCursorAdapter extends SimpleAdapter {
//private variables
Context context;
LayoutInflater inflater;
public MyCursorAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.statistic_cell, parent, false);
}
Set<Integer> VALUES = new HashSet<Integer>(Arrays.asList(
new Integer[]{0, 1, 2, 3, 4, 5, 10, 15, 20}
));
if (VALUES.contains(Integer.valueOf(position))) {
convertView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
TextView tv = (TextView) convertView.findViewById(R.id.statistic_cell_text);
tv.setTextColor(getResources().getColor(R.color.statistic_title));
convertView.setPadding(0, 0, 0, 0);
} else {
convertView.setBackground(getResources().getDrawable(R.drawable.border_intern));
}
return convertView;
}
}
}

Android ListView Adapter not working correctly

I've been attempting to upgrade an old app I made in college, including adding a listview to show data from Last.FM. The idea is having a main text with subtext under it, but the adapter I put together just isn't working. I've tried a good number of options, and the most recent is giving me a "Attempt to invoke virtual method on a null object reference" error, a previous try got a "Cannot cast Activity to Application" error.
Relevant code sections:
Main Activity adapter section:
ListView lv;
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.summarylayout);
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT);
lv = (ListView) dialog.findViewById(R.id.itemList); //Listview name
artistAdapter = new itemAdapter(getApplicationContext(), //Changed from ArrayAdapter<Item>
R.layout.custom_listview, //R.layout.custom_listview if itemAdapter works
result.toArray(new Item[] {}));
lv.setAdapter(artistAdapter);
lv.setOnItemClickListener(new MyOIListener());
Button closeButton = (Button) dialog
.findViewById(R.id.closeBtn);
// if button is clicked, close the custom dialog
closeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tracks = false;
dialog.dismiss();
}
});
The custom Adapter itself (Commented sections are previous attempts):
public class itemAdapter extends ArrayAdapter<Item>{
Context context;
int layoutResourceId;
Item data[] = null;
public itemAdapter(Context context, int layoutResourceId, Item[] 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;
// ItemHolder holder = null;
Item rowIn = new Item();
TextView main;
TextView sub;
if(row == null)
{
//LayoutInflater inflater = ((Application)context).getLayoutInflater();
//row = inflater.inflate(layoutResourceId, parent, false);
//row = LayoutInflater.from(getActivity()).inflate(R.layout.custom_listview, parent, false);
LayoutInflater inflater = LayoutInflater.from(this.getContext());
row = inflater.inflate(layoutResourceId, parent, false);
//holder = new ItemHolder();
//rowIn = new Item();
}
else
{
rowIn = (Item) row.getTag();
}
main = (TextView)row.findViewById(R.id.mainText);
sub = (TextView)row.findViewById(R.id.subText);
row.setTag(rowIn);
Item temp = data[position];
main.setText(temp.getTitle());
sub.setText(temp.getExtra());
return row;
}
/* static class ItemHolder
{
TextView mainText;
TextView subText;
}*/
}
The "Item" class is simply a holder for text/URLs parsed from the Last.FM api request.
I realize this is a question asked often, but 3 days of attempts and searching hasn't helped me out much. Any help would be appreciated
You're passnig the applicationContext to your adapter. Pass your Activity by:
artistAdapter = new itemAdapter(MainActivity.this, //Changed from ArrayAdapter<Item>
R.layout.custom_listview, //R.layout.custom_listview if itemAdapter works
result.toArray(new Item[] {}));
Your getView method was wrong, actually you will face a null variable there when getting the data from the tag.
This one should work for you, it is using ViewHolder Pattern
public class itemAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
Item data[] = null;
public itemAdapter(Context context, int layoutResourceId, Item[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemHolder holder = null;
if (convertView == null) {
//LayoutInflater inflater = ((Application)context).getLayoutInflater();
//row = inflater.inflate(layoutResourceId, parent, false);
//row = LayoutInflater.from(getActivity()).inflate(R.layout.custom_listview, parent, false);
LayoutInflater inflater = ((Activity) this.context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
holder = new ItemHolder();
holder.mainText = row.findViewById(R.id.mainText);
holder.subText = row.findViewById(R.id.subText);
convertView.setTag(holder);
} else {
holder = (ItemHolder) convertView.getTag();
}
Item temp = data[position];
if(temp != null) {
holder.mainText.setText(temp.getTitle());
holder.subText.setText(temp.getExtra());
}
return convertView;
}
static class ItemHolder {
TextView mainText;
TextView subText;
}
}
And as #vinitius said, pass your Activity context to the adapter.

How to paint ListView depending on content

I'm trying to paint rows int ListView depending on it's content.
I have array of int - int[] State= new int[] {1,1,1,1,1,1,0,0,0,0};
And I need to paint each row in red or green color depending on value in array. Green's flag is 0, Red's flag is 1.
For example: int[] State= new int[] {1,1,1,1,1,1,0,0,0,0};
Rows with number 0-5 must be red, 5-9 must be red.
I have adapter:
public class SpecialAdapter extends SimpleAdapter {
private int[] colors = new int[] {Color.RED, Color.GREEN };
private int[] State= new int[] {1,1,1,1,1,1,0,0,0,0};
public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
super(context, items, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
///It makes my list red-green, like zebra, but I need to paint depending on flags in State
int colorPos = position % colors.length;
view.setBackgroundColor(colors[colorPos]);
return view;
}
}
In main activity:
SpecialAdapter adapter = new SpecialAdapter(getBaseContext(), myArrList, R.layout.list_item,
new String[] {"State", "Name"},
new int[] {R.id.text1, R.id.text2});
ListView lvMain = (ListView)findViewById(R.id.listView1);
lvMain.setAdapter(adapter);
You should change your getView mehtod. int colorPos = position % colors.length; returns "0" or "1". So colors[colorPos] return red and green in order. Please try this;
public class SpecialAdapter extends SimpleAdapter {
private int[] colors = new int[] {Color.RED, Color.GREEN };
private int[] State= new int[] {1,1,1,1,1,1,0,0,0,0};
public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
super(context, items, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setBackgroundColor(colors[State[position]]);
return view;
}
}

Consultation about painting row in mt ListView

How do I paint every value that under 100 in red in my ListView?
i have ListView that connect to my_list.xml
i connect the cursor like this:
public void update_list(String NN) {
c = db.rawQuery(NN, null);
startManagingCursor(c);
String[] from = new String[]{"_id","Store","Makat","Des","Qty" };
int[] to = new int[]{R.id.txtID, R.id.txtStore,R.id.txtMakat ,R.id.txtDes ,R.id.txtQty};
SimpleCursorAdapter notes = new SimpleCursorAdapter (this, R.layout.my_list, c, from, to);
setListAdapter(notes);
}
How to do it ?
My suggestion would be to make your own adapter which would extend SimpleCursorAdapter. In it, you should override the getView method which creates every row view.
class MyCustomAdapter extends SimpleCursorAdapter{
private Context context;
private Cursor c;
public MyCustomAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
}
#Override
public View getView(int pos, View inView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
this.c.moveToPosition(pos);
//get the value from cursor, evaluate it, and set the color accordingly
int columnIndexOfQty = 4;
int qty = c.getInt(columnIndexOfQty);
if(qty < 100){
rowView.setBackgroundColor(Color.RED);
}
return rowView;
}
}
There may be some errors, but I think that you must get the idea.

Categories