ListView setOnItemClickListener isn't working - android

Like the title says, my setOnItemClickListener isn't working. I looked through everything I've seen so far on SO and couldn't find my error.
This is the code:
This is the problematic class. It isn't the main class, but is called from an intent:
package...;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
public class GroupActivity extends Activity {
String group_id = "";
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
context = this;
Intent intent = getIntent();
group_id = intent.getStringExtra("group_id");
Log.i("bla", "Launched GroupActivity for group_id " + group_id);
final SubAdapter adapter = new SubAdapter(this, group_id);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setClickable(true);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int idx, long lidx) {
Log.i("print here", "blaa " + idx);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is the SubAdapter class:
package...;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class SubAdapter extends BaseAdapter {
private static final int thumb_width = 128;
private static final int thumb_hight = 128;
private static Bitmap default_thumb = null;
private static LayoutInflater inflater = null;
private final String group_id_;
private final Activity activity;
private final SubAdapter t = this;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SubAdapter(Activity a, final String group_id) {
Drawable d = a.getResources().getDrawable(R.drawable.ic_contact_picture);
default_thumb = ((BitmapDrawable) d).getBitmap();
activity = a;
group_id_ = group_id;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int idx, View convertView, ViewGroup parent) {
Log.i("bla2", "getting view with index " + idx);
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.sub_list_item, null);
vi.setClickable(true);
}
TextView tv1 = (TextView)vi.findViewById(R.id.textView1);
TextView tv2 = (TextView)vi.findViewById(R.id.textView2);
ImageView img = (ImageView)vi.findViewById(R.id.imageView1);
tv1.setText("first name" + " " + "last name");
tv2.setText("some date");
// put thumbnail
Bitmap thumb = default_thumb;
img.setImageBitmap(thumb);
Log.i("bla3", "index is " + idx + "selected index is " + selectedPos);
if(selectedPos == idx){
Log.i("bla4", "inside if");
}
return vi;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
This is the activity_group 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".GroupActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusableInTouchMode="false"
android:focusable="false" >
</ListView>
</RelativeLayout>
This is the sub_list_item 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"
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:layout_toLeftOf="#+id/toggleButton1"
android:layout_toRightOf="#+id/imageView1"
android:text="some text"
android:textAppearance="?android:attr/textAppearance" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_toLeftOf="#+id/toggleButton1"
android:text="more text"
android:textAppearance="?android:attr/textAppearance" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:text="present" />
</RelativeLayout>
Apart from the click listener, everything else seems to work. The SubAdapter opens properly and the list is populated.
Basically what I'm looking for is to get the message "Log.i("print here", "blaa " + idx);" to print - it is the log from the ListView's setOnItemClickListener (look above)
Please let me know if there is any other relevant code missing
Thanks!!!

In your GroupActivity class please add the following code before findViewById method:
now you get the view same and change your code
ListView lv = (ListView) findViewById(R.id.listView1);
to
final View v = inflater.inflate(R.layout.rescuer_no_dialog, null);
ListView lv = (ListView)v.findViewById(R.id.listView1);

You should probably remove the call to
vi.setClickable(true); in your SubAdapter class, because your convertView will consume the click before you onItemClick listener.

Change this
ListView lv = (ListView) findViewById(R.id.listView1);
to
lv = getListView()
Extend ListActivity and declare lv outside methods.

Related

Set RadioButton for Custom Adapter and GridView

I have a project in which i wanted to set my custom View, not simple Android GridView.
I did that, now i want to set RadioButton for each row.
I saw this
But i could not specify the Boolean Array in this Reply.
Here is my Code.
First Items Layout.
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:layout_marginTop="30dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Small Text"
android:id="#+id/textView2"
android:layout_x="12dp"
android:layout_y="2dp"
android:textColor="#000"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginLeft="20dp"
android:id="#+id/textView"
android:layout_x="157dp"
android:layout_y="0dp"
android:textColor="#000"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radiogroup"></RadioGroup>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton"
android:layout_x="302dp"
android:layout_y="0dp"
android:checked="false" />
</AbsoluteLayout>
And simple GridView with a Button.
<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" 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=".DisplayActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:weightSum="1"
android:layout_marginTop="30dp">
<GridView
android:layout_width="wrap_content"
android:layout_height="387dp"
android:id="#+id/gridView"
android:background="#abc"
android:layoutDirection="ltr"
android:choiceMode="singleChoice"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:id="#+id/button" />
</LinearLayout>
In my Adapter Class :
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.RadioButton;
public class CarAdapter extends ArrayAdapter<Car> {
RadioButton radioButton;
RadioGroup radioGroup;
ArrayList<Boolean> booleans = new ArrayList<Boolean>();
public CarAdapter(Context context, int resource, ArrayList<Car> carArrayList, ArrayList<Boolean> mlist) {
super(context, resource, carArrayList);
this.booleans = mlist;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Car car = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_car, parent, false);
}
RadioGroup radioGroup = (RadioGroup)convertView.findViewById(R.id.radiogroup);
radioButton = (RadioButton)convertView.findViewById(R.id.radioButton);
TextView carName = (TextView) convertView.findViewById(R.id.textView2);
TextView carSIM = (TextView) convertView.findViewById(R.id.textView);
carName.setText(car.getName());
carSIM.setText(car.getSIM());
return convertView;
}
RadioButton.OnCheckedChangeListener mListener = new RadioButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
booleans.set((Integer) buttonView.getTag(), isChecked); // get the tag so we know the row and store the status
}
};
}
I tried this in getView Method :
radioButton.setTag(Integer.valueOf(position));
radioButton.setChecked(booleans.get(position));
radioButton.setOnCheckedChangeListener(mListener);
And mListener is :
RadioButton.OnCheckedChangeListener mListener = new RadioButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
booleans.set((Integer) buttonView.getTag(), isChecked); // get the tag so we know the row and store the status
}
};
But it gives me
java.lang.IndexOutOfBoundsException at line `radioButton.setChecked(booleans.get(position));`
Here is Main Activity :
import android.app.Activity;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class DisplayActivity extends Activity {
CarAdapter carAdapter;
Car car;
Car car2;
ArrayList<Car> carArrayList;
GridView gridView;
Button test;
ArrayList<Boolean> booleans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
carArrayList = new ArrayList<Car>();
car = new Car("Davie", "Smith");
car2 = new Car("Enrique", "Wall");
carArrayList.add(car);
carArrayList.add(car2);
booleans = new ArrayList<Boolean>(carArrayList.size());
carAdapter = new CarAdapter(getApplicationContext(), android.R.layout.simple_list_item_checked, carArrayList, booleans);
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(carAdapter);
test = (Button) findViewById(R.id.button);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (gridView.isItemChecked(gridView.getCheckedItemPosition())) {
String name = (carAdapter.getItem(gridView.getCheckedItemPosition())).getName();
Toast.makeText(getApplicationContext(), "Here is " + name, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "This is not true", Toast.LENGTH_SHORT).show();
}
}
});
}
}
In your CarAdapter modify this...
public CarAdapter(Context context, int resource, ArrayList<Car> carArrayList, ArrayList<Boolean> mlist) {
super(context, resource, carArrayList);
mlist = this.booleans;
}
to
public CarAdapter(Context context, int resource, ArrayList<Car> carArrayList, ArrayList<Boolean> mlist) {
super(context, resource, carArrayList);
this.booleans= mlist ;
}
You are assigning booleans ArrayList to mlist ArrayList which can be empty and so you are getting IndexOutOfBoundsException..you have to assign mlist to booleans ArrayList
mlist = this.booleans;
should be..
this.booleans = mlist;
in your CarAdapter constructor.

Android ListView working on emulator, but not on device

I am using ListView with a custom ArrayAdapter, and everything is working fine when I run my app in AVD emulator, but when I install it on my phone my app crashes when I touch any ListView item.
Activity 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"
android:background="#drawable/login_background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.frequentbuyer.ui.activity.ShoppingListListActivity" >
<ListView
android:id="#+id/shoppingListsListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/addShoppingListButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:cacheColorHint="#00000000" >
</ListView>
<Button
android:id="#+id/addShoppingListButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/shoppingListsListView"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/shoppingListsListView"
android:text="#string/add_shopping_list" />
</RelativeLayout>
List item 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"
android:background="#drawable/list_item_gradient" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:background="#drawable/border_rectangle_shape"
android:orientation="horizontal" >
<TextView
android:id="#+id/shoppingListName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<TextView
android:id="#+id/shoppingListItemsNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</RelativeLayout>
Activity class
package com.frequentbuyer.ui.activity;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import roboguice.inject.ContentView;
import roboguice.inject.InjectExtra;
import roboguice.inject.InjectView;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import com.frequentbuyer.R;
import com.frequentbuyer.exception.DataAccessException;
import com.frequentbuyer.model.ShoppingList;
import com.frequentbuyer.model.User;
import com.frequentbuyer.service.contract.IShoppingListService;
import com.frequentbuyer.ui.adapters.ShoppingListListViewAdapter;
import com.google.inject.Inject;
#ContentView(R.layout.activity_shoppinglist_list)
public class ShoppingListListActivity extends AbstractBaseActivity {
/* shopping list list activity UI components */
#InjectView(R.id.shoppingListsListView)
private ListView shoppingListsListView;
#InjectView(R.id.addShoppingListButton)
private Button addShoppingListButton;
/* shopping list list activity injected services */
#Inject
private IShoppingListService shoppingListService;
/* shopping list list activity received extras */
// received from login activity
#InjectExtra(ActivityParameterNames.AUTHENTICATED_USER)
User loggedInUser;
private List<ShoppingList> allShoppingLists;
/* activity events */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeShoppingListView();
// add listeners
addListeners();
registerForContextMenu(shoppingListsListView);
}
#Override
public void onBackPressed() {
showExitDialog();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
if (view.getId() == R.id.shoppingListsListView) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle(allShoppingLists.get(info.position).getName());
menu.add(Menu.NONE, 0, 0, R.string.delete_shopping_list);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
try {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
long shoppingListToDeleteId = info.id;
shoppingListService.deleteShoppingList(this, shoppingListToDeleteId);
reloadCurrentActivity();
} catch (DataAccessException e) {
showErrorMessageDialog(e.getLocalizedMessage());
}
return true;
}
/* activity methods */
private void initializeShoppingListView() {
try {
allShoppingLists = shoppingListService.getAllShoppingListsForUser(ShoppingListListActivity.this, loggedInUser.getId());
// pass context and data to the custom shopping list list adapter
ShoppingListListViewAdapter shoppingListListViewAdapter = new ShoppingListListViewAdapter(this, allShoppingLists);
// set shopping list list adapter
shoppingListsListView.setAdapter(shoppingListListViewAdapter);
} catch (DataAccessException e) {
showErrorMessageDialog(e.toString());
}
}
private void addListeners() {
shoppingListsListView.setOnItemClickListener(shoppingListListItemOnClickListener);
addShoppingListButton.setOnClickListener(addShoppingListButtonOnClickListener);
}
/* activity listeners */
private OnItemClickListener shoppingListListItemOnClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long shoppingListId) {
try {
HashMap<String, Serializable> activityParametersMap = new HashMap<String, Serializable>();
activityParametersMap.put(ActivityParameterNames.SELECTED_SHOPPING_LIST, shoppingListService.getShoppingListById(ShoppingListListActivity.this, shoppingListId));
activityParametersMap.put(ActivityParameterNames.AUTHENTICATED_USER, loggedInUser);
startAnotherActivity(ShoppingListListActivity.this, EditShoppingListActivity.class, activityParametersMap);
} catch (DataAccessException e) {
showErrorMessageDialog(e.getLocalizedMessage());
}
}
};
View.OnClickListener addShoppingListButtonOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, Serializable> shoppingListListActivityParametersMap = new HashMap<String, Serializable>();
shoppingListListActivityParametersMap.put(ActivityParameterNames.AUTHENTICATED_USER, loggedInUser);
ShoppingListListActivity.startAnotherActivity(ShoppingListListActivity.this, CreateShoppingListActivity.class, shoppingListListActivityParametersMap);
}
};
}
Custom adapter class
package com.frequentbuyer.ui.adapters;
import java.util.List;
import android.annotation.SuppressLint;
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.frequentbuyer.R;
import com.frequentbuyer.model.ShoppingList;
public class ShoppingListListViewAdapter extends ArrayAdapter<ShoppingList> {
private final Context context;
private final List<ShoppingList> shoppingLists;
public ShoppingListListViewAdapter(Context context, List<ShoppingList> shoppingLists) {
super(context, R.layout.shoppinglist_list_item, shoppingLists);
this.context = context;
this.shoppingLists = shoppingLists;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// create inflater
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// get rowView from inflater
View rowView = inflater.inflate(R.layout.shoppinglist_list_item, parent, false);
// get the two text view from the rowView
TextView shoppingListNameView = (TextView) rowView.findViewById(R.id.shoppingListName);
// set the text for textView
shoppingListNameView.setText(shoppingLists.get(position).getName());
// get the two text view from the rowView
TextView shoppingListItemNumberView = (TextView) rowView.findViewById(R.id.shoppingListItemsNumber);
// set the text for textView
int shoppingListSize = shoppingLists.get(position).getShoppingItems().size();
shoppingListItemNumberView.setText("(" + shoppingListSize + " item" + (shoppingListSize == 1 ? ")" : "s)"));
// return rowView
return rowView;
}
#Override
public long getItemId(int position) {
return shoppingLists.get(position).getId();
}
}
In some previous version of the app I used ListView in the same way on my phone without any problems, and now it is causing my app to crash.
Any idea why this is happening?
I used USB debugging, and found NullPointerException in logcat. It was thrown in getItemId method of my custom adapter, because my entities had null value for id field in database, for some reason. I defined id fields by using ORMLite with:
#DatabaseField(generatedId = true)
private Long id;
I changed type of id fields from Long to int and reinstalled app on phone and it worked, id fields were populated.

Correctly displaying a message when listView is empty

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.

Android ListView setOnItemClickListener not registering click with custom adapter

Well, I am not sure what is up. I've been through many SO "answers" without any results. I have a custom adapter running on my listview. I want to be able to click on the list item to "see more" but I cannot even get the click to register.
Here is my activity:
import java.util.ArrayList;
import java.util.List;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.XmlDom;
public class MainActivity extends SherlockActivity {
private AQuery aq;
private ProgressDialog dialog;
private static final String TAG = "INCIWEB";
private ListView lv;
protected Object IncidentAdapter;
EditText inputSearch;
String url;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_main);
getSupportActionBar().setSubtitle("Incidents across the USA");
aq = new AQuery(this);
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setInverseBackgroundForced(false);
dialog.setCanceledOnTouchOutside(true);
dialog.setMessage("Fetching Latest...");
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.USStates, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.stateSpinner);
s.setAdapter(adapter);
s.setPrompt("Select a location...");
final String USStates = s.getSelectedItem().toString();
Log.e("STATE", USStates);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
try {
getFeed(position);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
}
public void getFeed(int num) {
if (num == 0) {
// latest updates - front page
url = "http://inciweb.org/feeds/rss/incidents/";
} else {
// states
url = "http://inciweb.org/feeds/rss/incidents/state/" + num + "/";
}
Log.e("URL", url);
long expire = -1;
aq.progress(dialog).ajax(url, XmlDom.class, expire, this,
"getFeedCallback");
}
public void getFeedCallback(String url, XmlDom xml, AjaxStatus status) {
List<XmlDom> entries = xml.tags("item");
List<Incidents> incidents = new ArrayList<Incidents>();
for (XmlDom entry : entries) {
incidents.add(new Incidents(entry.text("title"),
entry.text("link"), entry.text("description"), entry
.text("published"), entry.text("geo:lat"), entry
.text("geo:long"), entry.text("georss:point")));
}
lv = (ListView) findViewById(R.id.list);
lv.setTextFilterEnabled(true);
lv.setAdapter(new IncidentAdapter(this,
android.R.layout.simple_list_item_1, incidents));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Toast.makeText(MainActivity.this, id + "' was clicked.",
Toast.LENGTH_LONG).show();
}
});
}
private class IncidentAdapter extends ArrayAdapter<Incidents> {
private List<Incidents> items;
public IncidentAdapter(Context context, int textViewResourceId,
List<Incidents> items) {
super(context, textViewResourceId, items);
this.items = items;
}
// Create a title and detail
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.incidents_item, null);
}
Incidents o = items.get(position);
if (o != null) {
TextView title = (TextView) v.findViewById(R.id.title);
TextView published = (TextView) v.findViewById(R.id.published);
TextView link = (TextView) v.findViewById(R.id.link);
link.setMovementMethod(LinkMovementMethod.getInstance());
TextView description = (TextView) v
.findViewById(R.id.description);
TextView geoLat = (TextView) v.findViewById(R.id.geoLat);
TextView geoLon = (TextView) v.findViewById(R.id.geoLon);
TextView geoLatLon = (TextView) v.findViewById(R.id.geoLatLon);
if (title != null) {
title.setText(o.getTitle());
}
if (published != null) {
published.setText(o.getPublished());
}
if (link != null) {
link.setText(o.getLink());
}
if (description != null) {
description.setText(o.getDescription());
}
if (geoLat != null) {
geoLat.setText(o.getGeoLat());
}
if (geoLon != null) {
geoLon.setText(o.getGeoLon());
}
if (geoLatLon != null) {
geoLatLon.setText(o.getGeoLatLon());
}
}
return v;
}
}
}
What am I missing?
edit:
Here is my XML files...
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Spinner
android:id="#+id/stateSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/inputSearch" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/stateSpinner" />
</RelativeLayout>
incident_items.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textSize="20sp" />
<TextView
android:id="#+id/published"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLatLon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
EDIT:
What I'd like to do is show the Title from the XML, then show the other XML fields onClick of the XML title from the listview...
Maybe your custom Views in ListView has clickable items and consume click event?
Make sure your ListView has the focus and there are no other clickable items that could steal the click events.
Well I cannot be 100% sure why it is working now, however, I think it has to do with going back through my XML and making sure nothing was missing or even a bit off according to Eclipse.
Thanks for all the comments.
For future folks: CHECK YOUR XML.

Restarting application when try to scroll the listview

I am developing the program that used ListActivity. So, when i scroll the listview to down, it cause to restart application and start from first activity. My code is as follows :
package com.daarkoob.food;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Window;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class FoodListActivity extends ListActivity {
private ArrayList<Food> M_foods = new ArrayList<FoodListActivity.Food>();
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.foodlist);
SQLiteDatabase sqliteDatabase = SQLiteDatabase.openOrCreateDatabase(
"/data/data/" + this.getPackageName() + "/data.db", null);
Cursor cursor = sqliteDatabase.rawQuery("SELECT * FROM FOOD", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
M_foods.add(new Food(cursor.getString(2), cursor.getString(1)));
cursor.moveToNext();
}
FoodAdapter adapter = new FoodAdapter(this);
setListAdapter(adapter);
cursor.close();
sqliteDatabase.close();
}
public class Food {
public Food(String foodName, String foodType) {
this.M_foodName = foodName;
this.M_foodType = foodType;
}
String M_foodName;
String M_foodType;
}
public class FoodAdapter extends ArrayAdapter<Food> {
private Context M_context = null;
public FoodAdapter(Context context) {
super(context, R.layout.foodlist_view_item, M_foods);
this.M_context = context;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) M_context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(
R.layout.foodlist_view_item, parent, false);
}
TextView textView = (TextView) convertView
.findViewById(R.id.foodlist_view_item_textview);
textView.setText(M_foods.get(position).M_foodName);
return convertView;
}
}
}
And the foodlist_view_item.xml is :
<?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"
android:background="#drawable/border"
android:orientation="vertical" >
<TextView
android:id="#+id/foodlist_view_item_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="right|center_vertical"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black"
android:textStyle="bold" />
</RelativeLayout>
and the foodlist.xml is as follows :
<?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:background="#drawable/background"
android:orientation="vertical" >
<TextView
android:id="#+id/foodlist_title_bar"
android:layout_width="match_parent"
android:layout_height="40dip"
android:background="#drawable/textlines"
android:gravity="right|center_vertical"
android:text="#string/foodlist_titlebar_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent"
android:dividerHeight="1dip" >
</ListView>
</LinearLayout>
What thing is wrong ? Why restarting occurs ?
Thanks in advance :)

Categories

Resources