I'm trying to create a 2-line list view in my activity but I've come across one error that I don't know how to fix. How can I achieve this the AppCompat way? I want to achieve something like in the screenshot attached. My error is on line 52.
public class WCLineActivity extends ActionBarActivity {
private class Sample {
private CharSequence title;
private CharSequence summary;
private Class<? extends Activity> activityClass;
public Sample(int titleResId, int summaryResId, Class<? extends Activity> activityClass) {
this.activityClass = activityClass;
this.title = getResources().getString(titleResId);
this.summary = getResources().getString(summaryResId);
}
#Override
public String toString() { return title.toString(); }
public String getSummary(){ return summary.toString(); }
}
private static Sample[] mSamples;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc_line);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.bank, R.string.zone_1, MainActivity.class),
new Sample(R.string.waterloo, R.string.zone_1, MainActivity.class)
};
setListAdapter(new MyAdapter(this, mSamples));
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView title;
TextView summary;
}
LayoutInflater inflater;
Sample[] mSamples;
public MyAdapter(Context contexts, Sample[] samples) {
this.mSamples = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mSamples.length;
}
#Override
public Object getItem(int position) {
return mSamples[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_dualline, null);
viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_title);
viewHolder.summary = (TextView) convertView.findViewById(R.id.list_item_subtitle);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(mSamples[position].title);
viewHolder.summary.setText(mSamples[position].getSummary());
return convertView;
}
}
}
setListAdapter is a method of ListActivity, and it is not available in Activity. To overcame it, you can declare a ListView in your layout, retrieve the ListView with findViewById and call setAdapter, on that object. E.g.
ListView listView = (ListView) findViewById(R.id.id_list);
listView.setAdapter(new MyAdapter(this, mSamples));
I tried with your code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc_line);
ListView listView = (ListView) findViewById(R.id.listView);
// Instantiate the list of samples.
mSamples = new Sample[]{
new Sample(R.string.bank, R.string.zone_1, MainActivity.class),
new Sample(R.string.waterloo, R.string.zone_1, MainActivity.class)
};
listView.setAdapter(new MyAdapter(this, mSamples));
}
Related
I have 3 classes relating to my checkbox section of my app in Android studio, atm the check box loads, but when selecting and deselecting the value doesn't save when I go bak into it from the main menu. any help would great!!!
public class WatchList extends AppCompatActivity {
ArrayList dataModels;
ListView listView;
private WatchListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("watchlist", "created watchlist activity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch_list);
listView = (ListView) findViewById(R.id.listview2);
dataModels = new ArrayList();
dataModels.add(new WatchListClass(R.drawable.kookaburra,"Kookaburra","Albury", false));
dataModels.add(new WatchListClass(R.drawable.cockatoo, "Cockatoo" , "Bathurst", true));
dataModels.add(new WatchListClass(R.drawable.emu,"Emu", "Echuca", true));
dataModels.add(new WatchListClass(R.drawable.magpie, "Magpie", "Sydney", true));
adapter = new WatchListAdapter(dataModels, getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
WatchListClass dataModel= (WatchListClass) dataModels.get(position);
dataModel.checked = !dataModel.checked;
adapter.notifyDataSetChanged();
}
});
}
}
public class WatchListAdapter extends ArrayAdapter {
private ArrayList dataSet;
Context mContext;
private static class ViewHolder {
TextView birdWatchName, birdWatchLocation;
ImageView birdWatchImage;
CheckBox checkBox;
}
public WatchListAdapter(ArrayList data, Context context) {
super(context, R.layout.watch_list, data);
this.dataSet = data;
this.mContext = context;
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public WatchListClass getItem(int position) {
return (WatchListClass) dataSet.get(position);
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.watch_list, parent, false);
viewHolder.birdWatchImage = (ImageView) convertView.findViewById(R.id.birdWatchImage);
viewHolder.birdWatchName = (TextView) convertView.findViewById(R.id.birdWatchName);
viewHolder.birdWatchLocation = (TextView) convertView.findViewById(R.id.birdWatchLocation);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
WatchListClass item = getItem(position);
viewHolder.birdWatchImage.setImageResource(item.birdWatchImage);
viewHolder.birdWatchName.setText(item.birdWatchName);
viewHolder.birdWatchLocation.setText(item.birdWatchLocation);
viewHolder.checkBox.setChecked(item.checked);
return result;
}
}
public class WatchListClass {
public String birdWatchName, birdWatchLocation;
int birdWatchImage;
boolean checked;
WatchListClass(int birdWatchImage, String birdWatchName,String birdWatchLocation, boolean checked) {
this.birdWatchName = birdWatchName;
this.birdWatchLocation = birdWatchLocation;
this.birdWatchImage = birdWatchImage;
this.checked = checked;
}
}
u can user shared preferences for check Box
try this one
How to save checkbox value with shared preferences?
you can use local database in app to store check box values and retrieve it back.
I have tried adding the adapter in the onCreate() as well and it throws a null pointer exception with an error 'Attempt to invoke listVIew.setAdapter on a null object reference.
Here is the code where I use notifyDataSetChange() inside my Main Activity;
import static com.name.sample.Tab1.adapter;
public class Requests extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Cursor c = myDB.rawQuery("SELECT * FROM requests", null);
int aIndex = c.getColumnIndex("name");
int bIndex = c.getColumnIndex("nick");
int cIndex = c.getColumnIndex("num");
name.clear();
nick.clear();
number.clear();
if (c.moveToFirst()){
do {
name.add(c.getString(aIndex));
nick.add(c.getString(bIndex));
number.add(c.getInt(cIndex));
} while (c.moveToNext());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter.notifyDataSetChanged();
}
}
Here is my Tab1 code
Here is the code for the Adapter
public class Tab1 extends Fragment {
static ListView listNotifications;
final static ArrayList<String> name = new ArrayList<>();
static ArrayList<Integer> number = new ArrayList<>();
static ArrayList<String> nick = new ArrayList<>();
static ImageAdapter adapter;
public static class ImageAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ImageAdapter (Context context, String[] values) {
super(context, R.layout.list_with_icons, 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.list_with_icons, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textViewName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imagePicture);
textView.setText(values[position]);
// Change the icon for Windows and iPhone
return rowView;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1layout, container, false);
String[] nameString = new String[name.size()];
nameString = name.toArray(nameString);
adapter = new ImageAdapter (getActivity(), nameString);
listNotifications =(ListView)rootView.findViewById(R.id.listNotifications);
listNotifications.setAdapter(adapter);
return rootView;
}}
Try using: adapterClass.this.notifyDataSetChanged() in onPostExcecute()
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
InvitedAdapter.this.notifyDataSetChanged();
}
you have added a wrong adapter in the listview. it should be like this in onCreateView():
listNotifications.setAdapter(adapter);
Try this :)
I am creating an app in android studio.
I need to update the list view with a new url that is sent via text message.
How do I add the new url to my list?
This is what I currently have for my main code.
public class MainActivity extends AppCompatActivity {
ListView list;
WebView webView;
ArrayList<String> sites = new ArrayList<>("https://www.google.com", "https://www.yahoo.com", "https://www.apple.com");
String [] url = {"https://www.google.com", "https://www.yahoo.com", "https://www.apple.com"};
MyBroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listview);
MyListAdapter adapter = new MyListAdapter(this, sites);
sites.add("new site");
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setDividerHeight(5);
webView = (WebView)findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient(){});
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
Toast.makeText(getApplicationContext(), sites.get(position), Toast.LENGTH_SHORT).show();
webView.loadUrl("https://www.google.com");
webView.loadUrl(url[position]);
}
});
receiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(receiver,filter);
}
}
This is myAdapterList:
public class MyListAdapter extends ArrayAdapter<String> {
private Activity context_;
private ArrayList<String> sites;
//constructor
public MyListAdapter(Activity context, ArrayList<String> sites){
super(context,R.layout.row,sites);
context_ = context;
this.sites = sites;
}
public View getView (int position, View convertView, ViewGroup parent){
if(convertView == null){
LayoutInflater inflater = context_.getLayoutInflater();
convertView = inflater.inflate(R.layout.row,null);
}
ViewHolder holder = (ViewHolder) convertView.getTag();
if(holder == null){
holder = new ViewHolder(convertView);
holder.tv_link.setText(sites.get(position));
}
else{
holder.tv_link.setText(sites.get(position));
}
return convertView;
}
private class ViewHolder{
TextView tv_link;
public ViewHolder(View row){
tv_link = (TextView) row.findViewById(R.id.tv_link);
}
}
}
I have a list view which brings numbers from a database. I need to multiply those numbers and get total of all numbers from my listview. But the problem is that the TextView where I have to set total is in the main activity and not on the adapter. How I can send the total from an adapter to the main activity?
Have I to use a loader ?
I have this in ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
int contador = 0;
public ListViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView name;
TextView marc, cant, prec;}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null){
convertView = inflater.inflate(R.layout.list_colum, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.marc = (TextView) convertView.findViewById(R.id.marc);
holder.cant = (TextView) convertView.findViewById(R.id.cant);
holder.prec = (TextView) convertView.findViewById(R.id.prec);
convertView.setTag(holder);
}
else{
holder=(ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.name.setText(map.get(FIRST_COLUMN));
holder.marc.setText(map.get(SECOND_COLUMN));
holder.prec.setText(map.get(THIRD_COLUMN));
holder.cant.setText(map.get(FOURTH_COLUMN));
return convertView;
}
And this in MainActivity
public class MAinActivity extends AppCompatActivity {
private ArrayList<HashMap<String, String>> list;
HashMap<String, String> temp = new HashMap<String, String>();
private Button scanBtn;
private TextView total;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<HashMap<String, String>>();
setContentView(R.layout.MainActivity);
total = (TextView)findViewById(R.id.total); //this is the TextView where I have to put the result coming from the adapter.
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
listView = (ListView)findViewById(R.id.listacompras);
ListViewAdapter adapter = new ListViewAdapter(this,list);
listView.setAdapter(adapter);
}
you can achieve it in this way.
Create a method in your main activity like this
public updateTextView(String text){
totla.setText(text);
}
and from adapter you can set text like this
((MAinActivity ) activity).updateTextView("New text From Adapter");
Or, you can add an interface in your ListViewAdapter
public class ListViewAdapter ...{
public interface Listener{
public void updateTotal(int total);
}
// also add a setter method for mListener
Listener mListener;
....
// call mListener.updateTotal() to show updated total
}
Then implement the listener interface in your MainActivity
public class MainActivity extends AppCompatActivity implements ListViewAdapter.Listener {
...
protected void onCreate(Bundle savedInstanceState) {
...
listViewAdapter.setListener(this);
}
public void updateTotal(int total){
// set total here
}
}
This is the skeleton of the code. You will need to adapt it to your code in order for it to work.
Good luck :)
I have implemented the Universal Image Loader into my app with a gridview layout.
When I press a button I want to add a new imageUrl to the Array of Urls.
I managed to do that, but when I refresh my imageList, I still only see the images that were in the Array on StartUp.
How can I update the gridView with the new Array?
EDIT
MainActivity
public class MainActivity extends Activity {
Button btnView;
private ListView listView;
Socket client;
PrintWriter printwriter;
EditText textField;
Button button;
String messsage;
ObjectInputStream input;
ObjectOutputStream output;
int counter = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.ac_home);
//startRunning();
}
public void onImageGridClick(View view) {
Intent intent = new Intent(this, ViewImages.class);
startActivity(intent);
}
public void onTakeImageClick(View view) throws IOException {
ViewImages.addImg();
}
}
And here is the ViewImage class
public class ViewImages extends Activity {
private ListView listView;
ImageLoader loader;
private static ImageListAdapter adapter;
private static List<String> mItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mItems = new ArrayList<String>();
mItems.add("http://195.178.234.228/images/image8.jpg");
mItems.add("http://195.178.234.228/images/image7.jpg");
adapter = new ImageListAdapter(this, mItems);
//
listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
}
public static void addImg(){
mItems.add("http://195.178.234.228/images/image10.jpg");
adapter.notifyDataSetChanged();
}
}
ImageListAdapter
public class ImageListAdapter extends BaseAdapter {
List<String> list;
int size;
private Context context;
private ImageLoader imageLoader;
public ImageListAdapter(Context context,List<String> list) {
this.context = context;
this.list = list;
imageLoader = ImageLoader.getInstance();
imageLoader.clearDiscCache();
imageLoader.clearMemoryCache();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View v = convertView;
ViewHolder vh = null;
if (v == null) {
v = View.inflate(context, R.layout.list_item, null);
vh = new ViewHolder();
vh.imageView = (ImageView) v.findViewById(R.id.imageView);
v.setTag(vh);
}
else {
vh = (ViewHolder)v.getTag();
}
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.build();
imageLoader.displayImage(list.get(position), vh.imageView, options);
return v;
}
private class ViewHolder {
ImageView imageView;
}
}
Use notifyDataSetChanged on gridView Adapter to reflect changes in the gridview. Whenever there is a new imageUrl added to array of URL's refresh the adapter by :
adapter.notifyDataSetChanged();