My problem is that my listView doesn't show any items. I entered multi columns data to my SQLite database and I want to show it in a custom listview, but my listView doesn't show anything. I think the the problem is in my custom adapter and specifically in the getView() method. I track the data flow with Log messages and and the data stored in the database into an ArrayList but seems that getView() don't put values into TextView. I tried many tutorials but it keeps make me made Custom Data Class and change my hole code. PLEASE help me. I have been in this problem for weeks.
My custom adapter
ListAdapter
import android.app.Activity;
import android.util.Log;
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 ListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> items;
public ListAdapter(Activity context, ArrayList<String> items) {
super(context, R.layout.custom_list, items);
// TODO Auto-generated constructor stub
this.context=context;
this.items=items;
}
#Override
public int getCount() {
return items.size();
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.custom_list, null,true);
TextView nameTV = rowView.findViewById(R.id.nameTV);
TextView priceTV = rowView.findViewById(R.id.priceTV);
//nameTV.setText(names[position]);
//priceTV.setText(prices[position].toString());
nameTV.setText(items.get(2*position));
priceTV.setText(items.get(2*position+1));
Log.d("ListAdapter", "nameTV.setText: items.get(2*position) "+nameTV+"/////////////////////////////");
Log.d("ListAdapter", "priceTV.setText: items.get(2*position) "+priceTV+"/////////////////////////////");
Log.d("ListAdapter", "getView : -----------------------------");
return rowView;
}
}
my main activity
ListDataActivity
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.support.v7.widget.SearchView;
import android.widget.Toast;
import java.util.ArrayList;
public class ListDataActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
ListView listView;
ArrayList<String> listData;
ListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
databaseHelper = new DatabaseHelper(this);
listView = findViewById(R.id.listView);
listData = new ArrayList<String>();
listAdapter = new com.example.barcodescanner.ListAdapter(this,listData);
listView.setAdapter(listAdapter);
popListView();
}
private void popListView() {
Log.d("ListDataActivity","Displaying data in the ListView");
//get data and append to a list
Cursor data = databaseHelper.getData();
listData = new ArrayList<>();
while (data.moveToNext()) {
//get the data from the columns
//then add it to the ArrayList
listData.add(data.getString(1));
listData.add(data.getString(2));
Log.d("DatabaseHelper", "addData: Adding "+data.getString(1)+"+++++++++++++++++++++++++++++");
Log.d("DatabaseHelper", "addData: Adding "+data.getString(2)+"+++++++++++++++++++++++++++++");
//create the list adapter and set the adapter
//final ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(listAdapter);
//set an OnClickListener to the listView
//we can use Object for data type here
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
String price = adapterView.getItemAtPosition(i).toString(); // we can use Object for data type here
Log.d("ListDataActivity", "onItemClick: You Clicked on " + name);
Cursor data = databaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()){
itemID = data.getInt(0);
}
if (itemID > -1){
Log.d("ListDataActivity","onItemClick: the ID is : "+itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this,EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
editScreenIntent.putExtra("price",price);
startActivity(editScreenIntent);
//finish();
}else {
toastMessage("No ID associate with this name");
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.search_menu,menu);
MenuItem searchItem = menu.findItem(R.id.item_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<String> userslist = new ArrayList<>();
for(String user : listData){
if(user.toLowerCase().contains(newText.toLowerCase())){
userslist.add(user);
}
}
//ArrayAdapter<String> adapter = new ArrayAdapter<>(ListDataActivity.this,
// android.R.layout.simple_list_item_1,userslist);
listView.setAdapter(listAdapter);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
//customized toast message
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
}
my custom list layout
custom_list
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/nameTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="20dp"
android:layout_marginRight="100dp"
android:layout_marginTop="5dp"
android:textColor="#4d4d4d"
/>
<TextView
android:id="#+id/priceTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:textColor="#4d4d4d"
/>
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
activity_list_data
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ListDataActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</ListView>
</android.support.constraint.ConstraintLayout>
In your onCreate method you are passing an empty ArrayList into your adapter. You then call popListView and then re-initialize your listData variable to a new object (new ArrayList()). So your adapter never receives any data.
Move the call to popListView up 2 lines to before you create your adapter.
UPDATE
Create a new class as follows:
class DataStructure {
private String name;
private String price;
DataStructure(String name, String price) {
this.name = name;
this.price = price;
}
String getName() {
return name;
}
String getPrice() {
return price;
}
}
Then change your adapter type with class ListAdapter extends ArrayAdapter<DataStructure>
Change listData to type ArrayList<DataStructure>.
When you read from the database create a new instance of DataStructure and add each instance to your list.
Related
I want to use the SearchView widget to filter Data.
The filtering doesnt work since i switched to a custom layout for the Listview. The ListView gets filled with all Songs i have but then doesnt update when something gets typed into the SearchView. I just want to get SearchView working for Custom ListView. If u have any Helpful Links pls share them with me.
Search Class:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SearchView;
import java.util.ArrayList;
import univie.g02.t06.tmsd.dummydata.DummyAPIData;
import univie.g02.t06.tmsd.dummydata.DummySong;
import univie.g02.t06.tmsd.MyAdapter;
public class Search extends AppCompatActivity {
ListView listV;
ArrayList<String> listItems = new ArrayList<String>();
ArrayList<String> titles = new ArrayList<String>();
ArrayList<DummySong> listSongs = new ArrayList<DummySong>();
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listV = (ListView) findViewById(R.id.list_view);
SearchView searchView = (SearchView) findViewById(R.id.search_view);
listSongs = DummyAPIData.getAllDummySongs();
for (int i = 0; i < listSongs.size(); i++) {
listItems.add(listSongs.get(i).getDummyArtistTitle());
titles.add(listSongs.get(i).getDummyTitle());
}
adapter = new MyAdapter(this,
android.R.layout.simple_list_item_1,
listItems);
listV.setAdapter(adapter);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
listV.setAdapter(adapter);
return true;
}
#Override
public boolean onQueryTextSubmit(String query){
return true;
}
});
}
}
MyAdapter Class:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MyAdapter extends ArrayAdapter implements Filterable {
private List<String> list;
ArrayList<String> origData = new ArrayList<String>();
private Context context;
public MyAdapter(Context context, int resources, ArrayList<String> list) {
super(context, resources, list);
this.list = list;
this.context = context;
this.origData = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.customlayout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
return view;
}
}
customlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="add" />
</RelativeLayout>
activitysearch.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="univie.g02.t06.tmsd.Search">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<SearchView
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true" />
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/search_view" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
SearchView searchView =(SearchView) findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
adapterQuote.getFilter().filter(s);
listView.setAdapter(adapterQuote);
return true;
}
#Override
public boolean onQueryTextChange(String s) {
adapterQuote.getFilter().filter(s);
return false;
}
});
I am learning to make a simple time table managing application.
I have a list of courses displayed. Each item in a list is a textview + a delete button. The onClick Listener in my list item isn't working as expected. When I click on the delete button, it is working fine. However, I want to open up some other activity when user clicks on the textview of the list item.
Code:
ShowAll.java (the main activity in which I am displaying a list of classes)
package com.example.android.mytimetable;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class ShowAll extends ActionBarActivity {
private ArrayAdapter<String> adapter ;
ArrayList <ClassDetail> classesDetail ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_all);
this.bindAdapter();
ListView listView = (ListView) this.findViewById(R.id.class_list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.v("Item", "clicked");
Intent intent = new Intent(view.getContext(), ShowAllClicked.class);
ClassDetail classDetail = classesDetail.get(i);
Bundle bundle = new Bundle();
bundle.putString("CLASS_NAME", classDetail.class_name);
bundle.putString("BUILDING", classDetail.building);
bundle.putString("MONDAY_START", classDetail.monday_start);
bundle.putString("MONDAY_END", classDetail.monday_end);
bundle.putString("TUESDAY_START", classDetail.tuesday_start);
bundle.putString("TUESDAY_END", classDetail.tuesday_end);
bundle.putString("WEDNESDAY_START", classDetail.wednesday_start);
bundle.putString("WEDNESDAY_END", classDetail.wednesday_end);
bundle.putString("THURSDAY_START", classDetail.thursday_start);
bundle.putString("THURSDAY_END", classDetail.thursday_end);
bundle.putString("FRIDAY_START", classDetail.friday_start);
bundle.putString("FRIDAY_END", classDetail.friday_end);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
void bindAdapter() {
DBHelper db = new DBHelper(this);
classesDetail = db.getClassesDetail();
ArrayList <String> classes = new ArrayList<>();
for(int i = 0 ; i < classesDetail.size() ; i++) {
Log.v("Adding ", classesDetail.get(i).class_name);
classes.add(classesDetail.get(i).class_name);
}
if(classes.size() == 0)
((TextView) this.findViewById(R.id.holiday)).setText(getString(R.string.noClass));
CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(classes, this);
((ListView) this.findViewById(R.id.class_list)).setAdapter(customArrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_show_all, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
}
activity_show_all.xml (the xml layout of ShowAll.java)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.android.mytimetable.ShowAll"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/class_list"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/holiday"/>
</LinearLayout>
CustomArrayAdapter.java (The custom array adapter file)
package com.example.android.mytimetable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Aman Goel on 02-08-2015.
*/
public class CustomArrayAdapter extends BaseAdapter implements ListAdapter {
private ArrayList <String> list = new ArrayList<String>();
private Context context;
public CustomArrayAdapter(ArrayList <String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
((TextView) view.findViewById(R.id.list_item)).setText(list.get(position));
Button deleteBtn = (Button) view.findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper db = new DBHelper(context);
db.deleteClass(list.get(position));
list.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
list_item.xml (The layout of each list view)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:id="#+id/list_item"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/delete"
android:id="#+id/delete"/>
</LinearLayout>
I tried to take help from here: Set onClickListener into custom adapter and here: Where should I place the onClickListener on a Custom ListView?
However, I am still not able to make the adapter work. Any help would be appreciated
set on custom adapter getview function
TextView lst_tv=(TextView)view.findViewById(R.id.list_item);
lst_tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
customArrayAdapter.setOnItemClickListener(...)
So I have a Listview full of rows, each with a textview and a spinner. I use an ArrayAdapter to fill in each row. There is a single layout for all the rows.
I want to have a button underneath all the rows that I can press so that it saves all the selections of the spinners in a Text file.
My problem though is I dont know how to reference the spinners anymore since I use the single layout approach. I no longer have unique IDs: (spinner1, spinner2, spinner3, etc.) for each one because they are filled in row by row.
Any advice on how to approach this problem so I can reference each spinner and call their "get text" method?
The more detail the better, thanks in advance!
This is how I would do it: If the model object type of your array doesn't have a variable for the current spinner selection, you need to update your model or extend your Adapter so that you can capture the current selection of the spinner for that item.
In your adapter's getView(), when you create the spinner, add an OnItemSelectedListener to it that updates the model for its corresponding item in the array.
Then when the save button is pressed, you simply loop through the items in the adapter's array and get all the current spinner values.
Here is a code example:
MainActivity.java
package com.example.spinnerdemo;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final String[] mValues = {
"Strongly Agree",
"Agree",
"Neutral",
"Disagree",
"Strongly Disagree"
};
public static class MyModel {
public String text;
public int spinnerVal;
public MyModel(String txt, int val) {
text = txt; spinnerVal = val;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<MyModel> items = createItemList();
ListView listView = (ListView) findViewById(R.id.listView1);
final MyListAdapter adapter = new MyListAdapter(this, items);
listView.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// here is where we get all the spinner values
Log.d(TAG, "------- save button clicked");
for (MyModel model : items) {
Log.d(TAG, model.text + " : " + mValues[model.spinnerVal]);
}
Log.d(TAG, "-------");
}
});
}
public static class MyListAdapter extends ArrayAdapter<MyModel> {
public MyListAdapter(Context context, List<MyModel> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
final MyModel model = (MyModel) getItem(position);
TextView textView = (TextView) convertView.findViewById(R.id.textView1);
textView.setText(model.text);
Spinner spinner = (Spinner) convertView.findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<String>(parent.getContext(),
android.R.layout.simple_spinner_dropdown_item,
android.R.id.text1, mValues));
// here is where the spinner gets the value from the model
spinner.setSelection(model.spinnerVal);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// here is where we update the model with the current position of the spinner
model.spinnerVal = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return convertView;
}
}
private List<MyModel> createItemList() {
List<MyModel> items = new ArrayList<MyModel>();
// initialize with "Neutral" spinner setting
items.add(new MyModel("question 1", 2));
items.add(new MyModel("question 2", 2));
items.add(new MyModel("question 3", 2));
items.add(new MyModel("question 4", 2));
items.add(new MyModel("question 5", 2));
return items;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.spinnerdemo.MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Save" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
I have a listView that's being populated with my existing database in my android app and above that listView, I have a searchView so that I can type in something and then query the database and then display those results in the listView. And at first before I type in anything I have it where it just displays me all items in my database. But when I put in something into the searchView for which it won't provide me any results and I click on the empty screen, the screen crashes, but it should not do that. I instead want to be able to click on it all I want but also display a message saying NO RESULTS FOUND. Also when I clear the searchView, I would like my original results, all the items to display again. I've posted my code below, so any help would be great.
shirtsActivity.java
package ankitkaushal.app.healthysizing;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
public class shirtsActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shirts);
final SearchView shirtViewShirts = (SearchView) findViewById(R.id.searchView3);
final DatabaseHelper dbhelper;
final ListView listView;
final ListAdapter shirtsAdapter;
dbhelper = new DatabaseHelper(getApplicationContext());
try {
dbhelper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
listView = (ListView) findViewById(R.id.listViewShirts);
//List<Item> shirtsList = dbhelper.getAllShirts();
ArrayList<Item> shirtsList = dbhelper.getAllShirts();
if (shirtsList != null) {
//shirtsAdapter = new ArrayAdapter<Item>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, shirtsList);
shirtsAdapter = new ListItemAdapter(getApplicationContext(), shirtsList);
listView.setAdapter(shirtsAdapter);
}
shirtViewShirts.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
query = query.toLowerCase();
query = Character.toString(query.charAt(0)).toUpperCase()+query.substring(1);
ListAdapter searchedShirtsAdapter;
Log.e("Brand: ", query);
ArrayList<Item> searchedShirtsList = dbhelper.getAllSearchedShirts(query);
if (searchedShirtsList != null) {
searchedShirtsAdapter = new ListItemAdapter(getApplicationContext(), searchedShirtsList);
listView.setAdapter(searchedShirtsAdapter);
}
else if (searchedShirtsList.isEmpty()) {
searchedShirtsAdapter = new ListItemAdapter(getApplicationContext(), searchedShirtsList);
listView.setAdapter(searchedShirtsAdapter);
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
}
listItemAdapter.java
package ankitkaushal.app.healthysizing;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public final class ListItemAdapter extends ArrayAdapter<Item> implements View.OnClickListener{
public ListItemAdapter(Context context, ArrayList<Item> shirtItems) {
super(context, 0, shirtItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Item item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout_shirts, parent, false);
}
// Lookup view for data population
TextView brand = (TextView) convertView.findViewById(R.id.txt_shirt_brand);
TextView price = (TextView) convertView.findViewById(R.id.txt_shirt_price);
TextView store = (TextView) convertView.findViewById(R.id.txt_shirt_store);
TextView description = (TextView) convertView.findViewById(R.id.txt_shirt_description);
// Populate the data into the template view using the data object
brand.setText("Brand:" + " " + item.getBrand());
price.setText("Price:" + " " + item.getPrice());
store.setText("Store:" + " " + item.getStore());
description.setText("Description:" + " " + item.getDescription());
// Return the completed view to render on screen
return convertView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
activity_shirts.xml
<?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="#29A9D2"
android:weightSum="1"
android:id="#+id/shirt"
android:onClick="onClickSearch">
<SearchView
android:layout_width="352dp"
android:layout_height="wrap_content"
android:id="#+id/searchView3"
android:background="#ffffffff"
android:queryHint="Search for a specific brand" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewShirts"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/list_empty_shirts"
android:text="No Results Found"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:textColor="#FFFFFF"
android:gravity="center"
android:textSize="40dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:visibility="invisible" />
</RelativeLayout>
</LinearLayout>
First, create a plain textview in the xml file with the message you want for your activity.
Then try adding this:
listView.setEmptyView(findViewById(R.id.___);
Fill in the ___ part in this line with the id for the textview you created.
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab on icon to start a Campaign" />
</LinearLayout>
Activity+list_demonstration.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Active Campaign"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#4AE56B" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Closed Campaign"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="130dp" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
I m trying to make an listview that is empty in the starting of the application.in which a textview will give information to tab on icon..,and when user tab and create an app.the data shown in the listview..bt listview is giving an error ,how to solve it..
Demo.java // custom adapter
package com.example.smscampaign;
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.LinearLayout;
import android.widget.TextView;
public class Demo extends ArrayAdapter{
private Campaign_Details list;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Demo(Context context, String[] values) {
super(context, R.layout.activity_list_demostration);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.text1);
ImageView btn=(ImageView)v.findViewById(R.id.imageView1);
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.text1);
return v;
}
}
Campaign_Details.java
package com.example.smscampaign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class Campaign_Details extends Activity {
private Demo selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
DataBaseHandler info= new DataBaseHandler(this);
info.open();
String data=info.getData();
info.close();
String[] values= new String[]{ data };
//txt.setText(data);
// Button next=(Button) findViewById(R.id.next);
// Map<String, String[]> storage = new HashMap<String, String[]>();
// String[] tableItems = storage.get("ContactTable");
// next.setOnClickListener(this);
// final ListView listview = (ListView) findViewById(R.id.listview);
ListView listview = (ListView) findViewById(R.id.listView1);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
listview .setEmptyView(emptyText);
// listview.setEmptyView((LinearLayout) findViewById(R.id.emptyText));
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < data.length(); ++i) {
selectedAdapter = new Demo(this,values);
selectedAdapter.setNotifyOnChange(true);
listview.setAdapter(selectedAdapter);
list.add(data);
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent n = new Intent(getApplicationContext(), SmsSend.class);
startActivity(n);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.nextPage:
Intent i = new Intent(this,SmsSend.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE:
You have done everything wrong. you need to change as follows.
public Demo(Context context, String[] values) {
super(context, R.layout.activity_list_demostration);
this.context = context;
this.values = values;
}
to
public Demo(Context context, String[] values) {
super(context, values);
this.context = context;
this.values = values;
}
In Campaign_Details Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_demostration);
ListView listview = (ListView) findViewById(R.id.listView1);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
According to your question finally you need to change here from
ListView listview = (ListView) findViewById(R.id.listView1);
to
ListView listview = (ListView) findViewById(R.id.listView);