I'm looking in a article regarding a listviews and buttons. Now I have copied the code that he wrote. But unfortunetaly I get an error.
I have a activity_main, Child_listview, ListAdapter.java and MainActivity.java.
In the last one I'm getting a error.I have put the errors in Bold lettering.
Error 1 says: ListAdapter is abstract; cannot be instantiated
Error 2 says: Cannot resolve method. I'm guessing this because it is looking for the method in the wrong javafile. It is looking for it in MainAcitivity instead of ListAdapter.
private ListView listView;
ListAdapter adapter;
ArrayList<String> dataItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] dataArray = getResources().getStringArray(R.array.listdata);
List<String> dataTemp = Arrays.asList(dataArray);
dataItems.addAll(dataTemp);
listView = (ListView) findViewById(R.id.listView);
adapter = **new ListAdapter(MainActivity.this, dataItems)**;
adapter.**setCustomButtonListner**(MainActivity.this);
listView.setAdapter(adapter);
If you keep scrolling on this article, you will find out that he create this ListAdapter (which is a terrible name for a Custom adapter)
Here is the code of his class
package com.example.articalonlistiner;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ListAdapter extends ArrayAdapter<String> {
customButtonListener customListner;
public interface customButtonListener {
public void onButtonClickListner(int position,String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
private ArrayList<String> data = new ArrayList<String>();
public ListAdapter(Context context, ArrayList<String> dataItem) {
super(context, R.layout.child_listview, dataItem);
this.data = dataItem;
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.child_listview, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView
.findViewById(R.id.childTextView);
viewHolder.button = (Button) convertView
.findViewById(R.id.childButton);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position,temp);
}
}
});
return convertView;
}
public class ViewHolder {
TextView text;
Button button;
}
}
This is clearly a lack of attention on your part. You can't copy a piece of code and hope that it will work if you don't read everything.
EDIT (from the comments below) :
This is also important to make sur that you use the correct ListAdapter. You need to import the custom ListAdapter and not the one from the Android widget package.
Related
I'm trying to create nested listviews in multiple fragments using adapter. I'm able to create it in single activity but I couldn't do it in fragments using adapter. Refer second fragment as fragment2 and second list as listview2.
package com.example.admin.volleyrequestandresponse.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.admin.volleyrequestandresponse.R;
import com.example.admin.volleyrequestandresponse.activities.NavigationActivity;
import com.example.admin.volleyrequestandresponse.fragments.HomeFragment;
import java.util.ArrayList;
public class HomeFragmentAdapter extends BaseAdapter {
private ArrayList<String> stringArray;
private ArrayList<String> integerArray;
int[] logos;
Context context;
NavigationActivity navigationActivity;
public HomeFragmentAdapter(Context context, ArrayList<String> stringArray, ArrayList<String> integerArray, int[] logos) {
this.context = context;
this.stringArray = stringArray;
this.integerArray = integerArray;
this.logos = logos;
navigationActivity = new NavigationActivity();
}
#Override
public int getCount() {
return integerArray.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.home_adapter, null);
holder = new ViewHolder();
holder.imageview = (ImageView) convertView.findViewById(R.id.indeximg);
holder.txtTitle = (TextView) convertView.findViewById(R.id.indexname);
holder.text = (TextView) convertView.findViewById(R.id.indexvalue);
holder.relativeLayout = (RelativeLayout) convertView.findViewById(R.id.home_adapter);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.imageview.setImageResource(logos[position]);
holder.txtTitle.setText(stringArray.get(position));
holder.text.setText(integerArray.get(position));
return convertView;
}
private class ViewHolder {
RelativeLayout relativeLayout;
TextView text;
TextView txtTitle;
ImageView imageview;
}
}
Fragment code to call the adapter
homeFragmentAdapter = new HomeFragmentAdapter(getActivity(),index_string,index_values,index_logo);
listview_HomeFragment.setAdapter(homeFragmentAdapter);
I'm making some listview based app with ability to delete specific row with a button in it, like on screenshot below: Screenshot
Here are my classes:
MainActivity:
package com.example.patryk.notes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
LayoutInflater layoutInflater;
ArrayList<Item> itemList = new ArrayList<Item>();
ItemArrayAdapter itemArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemArrayAdapter = new ItemArrayAdapter(this, R.layout.list_item, itemList);
listView = (ListView) findViewById(R.id.item_list);
listView.setAdapter(itemArrayAdapter);
layoutInflater = getLayoutInflater();
ViewGroup footer = (ViewGroup) layoutInflater.inflate(R.layout.list_view_footer, listView, false);
listView.addFooterView(footer);
itemList.add(new Item("Item", 1));
}
public void addRow(View v) {
itemList.add(new Item("Item", itemList.size() + 1));
Log.d("add", "metoda add row");
itemArrayAdapter.notifyDataSetChanged();
}
}
ItemArrayAdapter
package com.example.patryk.notes;
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.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by patryk on 04.01.2018.
*/
public class ItemArrayAdapter extends ArrayAdapter<Item> {
private int listItemLayout;
ImageButton deleteButton;
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Item item = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(listItemLayout,parent, false);
// viewHolder.item = (TextView) convertView.findViewById(R.id.row_item);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
deleteButton = (ImageButton) convertView.findViewById(R.id.xButtonID);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**here expected to do something**
}
});
return convertView;
}
private static class ViewHolder {
TextView item;
}
}
item
package com.example.patryk.notes;
/**
* Created by patryk on 04.01.2018.
*/
public class Item {
private String name;
private double value;
public Item(String name, double value) {
this.value = value;
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I've tried many ideas from Stack Overflow but always there has been my clue missing. Firstly I wanted to make delete action on OnclickListener method in ItemArrayAdapter class, but the problem was to access ArrayList "itemList" located in MainActivity class, so I couldn't perform itemList.remove(position).
On the other hand I wanted to make deleteRow method in MainActivity and attach it to delete button on ItemArrayAdapter class by adding android:onClick="deleteRow" tag, but that makes exception similar to that: IllegalStateException
I'd rather chose first idea, so I would like to know how to get access to this ArrayList within adapter class
cheers :)
Reference variable of ArrayList is send to the adapter class. So you can easily do this:
public class ItemArrayAdapter extends ArrayAdapter<Item> {
private int listItemLayout;
ImageButton deleteButton;
private ArrayList<Item> itemList;
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
this.itemList = itemList;
}
Then
deleteButton = (ImageButton) convertView.findViewById(R.id.xButtonID);
deleteButton.setTag(position);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) v.getTag();
itemList.remove(pos);
notifyDataSetChanged();
notifyDataSetInvalidated();
}
});
You don't need to access the MainActivity, item list is available in the constructor
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
}
You better assign to a variable and use it.
Like this
Private ArrayList <Item> itemList;
public ItemArrayAdapter(Context context, int layoutId, ArrayList<Item> itemList) {
super(context, layoutId, itemList);
listItemLayout = layoutId;
this.itemList = itemList
}
After remove please call notifytheDataSetChange method to refresh the list view.
I am able to change the background of a selected item in a listview. I want the first item's background highlighted when the list is created. The code below gives an error when I try to perform a "performItemClick".
I have seen suggestions to modify my getView in the array adapter. However, I get the error "no default construction in Android.widget.ArrayAdapter when I try to create the class MyCustomAdapter in my java code.
So, if I need to create an extention of my ArrayAdapter class to do this, how do I get around this error. If there is another way I am open to suggestions.
Thanks
package com.hofficer.aclsfast;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.lang.reflect.Array;
public class NarrowChild extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_narrow_child);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//fix orientation
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//MyCustomAdapter adapter = new MyCustomAdapter();
createList();
}
/*
class MyCustomAdapter extends ArrayAdapter{
}*/
void createList(){
String[] narrowChoices = {"aFib/Flutter", "Narrow Cmplx Tachycardia", "PSVT", "Junctional Tachycardia", "Multifocal Tachycardia"};
ListAdapter theAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, narrowChoices);
final ListView listview = (ListView) findViewById(R.id.narrowListView);
listview.setAdapter(theAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//clear menu and highlight selected item
for (int i = 0; i < 5; i++) {
listview.getChildAt(i).setBackgroundColor(Color.WHITE);
}
listview.getChildAt(position).setBackgroundColor(Color.CYAN);
}
});
Boolean result = listview.performItemClick(listview,0,0); //THIS GIVES ERROR NULL POINT EXCEPTION
}
}
in your MyCustomAdapter you have to override the one or more of the constructors of ArrayAdapter or create your own. and example of custom Adapter is :
public class WeatherAdapter extends ArrayAdapter<Weather>{
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] 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;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
more info from the source
in your case you need to check the position if it is 0 and then return the desired item.
I can't test it right now but can't you just call listview.getChildAt(0).setBackgroundColor(Color.CYAN); instead of Boolean result = listview.performItemClick(listview,0,0);?
Try this:
Boolean result = listview.performItemClick(listview.getAdapter().getView(0),0,0);
or:
Boolean result = listview.performItemClick(listview.getAdapter().getView(0, null, null),0,0);
See this question and check the docs.
EDIT
I think your problem is the getChildAt() method. You should look at this question.
I'm having some trouply with my application using Parse. In order to populate a LitsView with parse objects, I have used the following adapter class. The problem is, i get an error at
ParseObject statusObject = mStatus.get(position);
The error reads: Error:(44, 47) error: incompatible types: Object cannot be converted to ParseObject
What's happening here?
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 com.parse.ParseObject;
import java.util.List;
public class StatusAdapter extends ArrayAdapter {
protected Context mContext;
protected List mStatus;
public StatusAdapter(Context context, List status) {
super(context, R.layout.homepage, status);
mContext = context;
mStatus = status;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.homepage, null);
holder = new ViewHolder();
holder.usernameHomepage = (TextView) convertView
.findViewById(R.id.usernameHP);
holder.statusHomepage = (TextView) convertView
.findViewById(R.id.statusHP);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject statusObject = mStatus.get(position);
// title
String username = statusObject.getString("user");
holder.usernameHomepage.setText(username);
// content
String status = statusObject.getString("newStatus");
holder.statusHomepage.setText(status);
return convertView;
}
public static class ViewHolder {
TextView usernameHomepage;
TextView statusHomepage;
}
}
You are not using generic list (List<E>). Either you should cast object:
ParseObject statusObject = (ParseObject) mStatus.get(position);
or use a list like:
protected List<ParseObject> mStatus;
Then you will not need to caste it. You will also need to modify the contructor:
public StatusAdapter(Context context, List<ParseObject> status) {
super(context, R.layout.homepage, status);
mContext = context;
mStatus = status;
}
Im using an array adapter with a list view as follows:
ArrayList<Store> allStores = dm.getAll(Store.class);
ArrayAdapter<Store> adapter = new ArrayAdapter<Store>(context,R.layout.listview_layout, R.id.textView1, allStores);
ListView mylist = (ListView) view.findViewById(R.id.listViewFromDb);
mylist.setAdapter(adapter);
The array that I pass into the listview is an array of objects. At the minute the list prints out all of the attributes of the object is it possible to just print the first attribute of the object so "name". Please help
Extend the ArrayAdapter and override the getView method, using the position argument to access the element in the array. Here is an example from Vogella:
The following example doesn't recycle views, so keep that in mind as it will affect performance (a great deal on some devices).
package de.vogella.android.listactivity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.rowlayout, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
// Change the icon for Windows and iPhone
String s = values[position];
if (s.startsWith("iPhone")) {
imageView.setImageResource(R.drawable.no);
} else {
imageView.setImageResource(R.drawable.ok);
}
return rowView;
}
}