LISTVIEW - onItemClick not working - android

I'm at my first steps into Android... I already read some of the answered question, and I tool a lot of tips, but I don't find how to solve my problem.
In the activity Categories.java I have a listview built starting from a database. The listview displys correctly, then I would like to start another activity from the OnItemClick, but I realized that I can't display even a toast.
I really hope some of you can help me I really don't find where is my error!! Thank you in advance!
Here is my code:
package com.example.myshopping;
import java.util.ArrayList;
import android.os.Bundle;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.app.Activity;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
public class Categories extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
final ListView lista= (ListView) findViewById(R.id.id_categorie);
MioDatabaseHelper myHelper;
myHelper= new MioDatabaseHelper(this);
final SQLiteDatabase db= myHelper.getReadableDatabase();
String [] columns_cat ={"nome_categoria"};
Cursor cursor= db.query("categorie", columns_cat, null, null, null, null, null);
int len= cursor.getCount();
cursor.moveToFirst();
final ArrayList <String> array_cat= new ArrayList<String>();
for (int i=0; i<(len); ++i){
array_cat.add(cursor.getString(0));
cursor.moveToNext();
}
ArrayAdapter<String> myadapter= new ArrayAdapter<String>(this, R.layout.listitem, R.id.listitemTextView, array_cat);
lista.setAdapter(myadapter);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Toast.makeText(getApplicationContext(), "hello toast!!!!", Toast.LENGTH_LONG).show();
}
});
}
and here the xml file of the list items:
<?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"
android:descendantFocusability="blocksDescendants">
<TextView
android:id="#+id/listitemTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:includeFontPadding="false"
android:padding="5pt"
android:scrollHorizontally="false"
android:textSize="10pt" />
</LinearLayout>
and here the xml file of the categories.java file:
<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="wrap_content"
android:gravity="center_horizontal"
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=".Categories" >
<ListView
android:id="#+id/id_categorie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textIsSelectable="true">
</ListView>
</RelativeLayout>

I see basic inconsistency in your code:
R.layout.categories//in set content view
and in array adapter:
ArrayAdapter<String> myadapter= new ArrayAdapter<String>(this, R.layout.listitem, R.id.listitemTextView, array_cat);
Change R.layout.listitem to R.layout.categories
or use a different constructor.

Is android:textIsSelectable="true" and android:descendantFocusability="blocksDescendants" attributes needed in your case? Using them wrong can cause focusing problems and the click listener doesn't work. Try removing both.
Also the list item contains only one child for the LinearLayout so it could just be TextView having width set to match_parent and height wrap_contentcombined with padding.

Also if you want to specyfy textView appearance Create XML Just with that textView without parent Noode, coz lists can be ricky sometimes :P try create another XML just to test that one thingChange this:<relativeLayout>
attributes..
<textView>
attributes..
</textView>
</relativeLayout> To<TextView>
attributes
</TextView>Basicaly you want stand alone TextView

Related

How to know which button user clicked and its text and id in Android Studio?

Through out the whole android application I want to capture button click, radio button clicks, link click etc... basically a user interaction in whole android application. Is there any common method to detect which element user click and its values.?
Try using onCickListener() on the buttons.
In Kotlin:
Add id to button in .xml files with android:id="#+id/nameOfButton". Every button needs an unique name.
In .kt file, use setOnClickListener with the id to set up the action when user click the button.
If there are several buttons, just follow step 1 and 2.
Example:
step 1
<Button
android:id="#+id/buttonSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
step 2
buttonSave.setOnclickListenter {
//TODO: your code goes here
}
Its very simple you just need to get the text and id of button from the onclick method. Here is java and xml code for it:
XML:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onclick="getid"
android:text="Save" />
JAVA:
public void getid(View v){
int id = v.getId();
String text = v.getText();
}
As #Muthukumar Lenin asked here is listview in xml and java
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity">
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="italic"
android:textColor="#5f65ff"
android:padding="5dp"
android:text="Choose is the best football player?"/>
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textview" />
</RelativeLayout>
JAVA:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
final TextView textView = (TextView) findViewById(R.id.textview);
String[] players = new String[] {"CR7", "Messi", "Hazard", "Neymar"};
List<String> Players_list = new ArrayList<String>(Arrays.asList(players));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Players_list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = (String) parent.getItemAtPosition(position);
textView.setText("The best football player is : " + selectedItem);
}
});
}
}
Some of these code are from tutorialspoint and some are edited by me.

Showing error in ArrayAdapter ListView

I have written this code but it shows me error and i cannot identify where the problem is.My code is as follows-
package com.example.adapterexample;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Build;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listAdapter();
}
public void listAdapter() {
String[] myItems = { "Apple", "Orange", "Grape", "Watermilon" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.da_items, myItems);
ListView list = (ListView) findViewById(R.id.listView);
list.setAdapter(adapter);
}
}
xml for da_items
<?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:orientation="vertical" >
</LinearLayout>
xml for activity_main
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
//tools:context="com.example.adapterexample.MainActivity"
//tools:ignore="MergeRootFrame" >
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</FrameLayout>
It shows me error: E/ArrayAdapter(30552): You must supply a resource ID for a TextView
I do not add any text view then why this error is coming?
JavaExperts need your valuable suggestion to solve this issue.
Check official docs of ArrayAdapter.
public ArrayAdapter (Context context, int resource, T[] objects)
Added in API level 1
Constructor
Parameters
context - The current context.
resource - The resource ID for a layout file containing a TextView to use when instantiating views.
objects - The objects to represent in the ListView.
You will notice that the array adapter is expecting that the second parameter is a resource id of a text view not a layout.
So, when you use this constructor:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.da_items, myItems);
R.Layout.da_items must be an xml layout where the first element must be a TextView, something like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
//other attributes
/>
To be more sort of a custom textview, you can also use -
new ArrayAdapter<String>(this, R.layout.da_items,
R.id.the_id_of_a_textview_from_the_layout, myItems)
where you supply the id of a layout that can contain various views, but also must contain a TextView with and id(third parameter) that you pass to your ArrayAdapter so it can know where to put the Strings.
The layout that you provide in the adapter - R.layout.da_items - should only contain a TextView because that's what android supports by default. So either use android.R.layout.simple_list_item_1 (this layout is provided by android) in place of your custom layout or make sure that your R.layout.da_items looks something like :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:minHeight="?android:attr/listPreferredItemHeight"
/>
Try this.
Add this in da_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" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16sp" />
</LinearLayout>
And in MainActivity.java
listView = (ListView) findViewById(R.id.list1);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.da_item, myItems);
listView.setAdapter(adapter);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.simple_list_item_1, myItems);
it will help you.
As you have used below code is creating problem
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.da_items, myItems);
So there is no need to make another layout and use it as R.layout.da_items
instead use
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.simple_list_item_1, myItems);

How the display bug of TextView drawableStart can be explained?

Update: Simpler code created and presented here, full layout XML definitions.
When trying to replace the row layout with the icon on the left by the new drawableStart attribute of the TextView element in XML layout, I can observe the following wrongly displayed last item (captured on Nexus 7):
The related code is -- MainActivity:
package cz.skil.android.tut.testtextviewdrawablestart;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ListView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_list);
ListView listView = (ListView) findViewById(R.id.mylist);
String[] values = new String[] {"item 1", "item 2", "item 3"};
MyAdapter adapter = new MyAdapter(this, values);
listView.setAdapter(adapter);
}
}
MyAdapter
package cz.skil.android.tut.testtextviewdrawablestart;
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 class MyAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MyAdapter(Context context, String[] values) {
super(context, R.layout.row, 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.row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.mylabel);
textView.setText(values[position]);
return rowView;
}
}
The main_list.xml layout:
<?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:orientation="vertical" >
<ListView
android:id="#+id/mylist"
android:layout_width="match_parent"
android:layout_height="wrap_content" > <!-- Update: here is the bug -->
</ListView>
</LinearLayout>
and finally the row.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mylabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="4dp"
android:drawablePadding="8dp"
android:drawableStart="#drawable/reminder"
android:lines="1"
android:textSize="24sp" >
</TextView>
I guess the reason is that the height of the area for displaying the items is calculated from dimensions declared for the text; however, the icon possibly forces a bigger height for the list item.
Can you confirm the behaviour? If yes, why it behaves so? I am new to Android. It is likely I am doing it wrongly.
(The question is loosely related to this one: Android layout: on TextView and android:drawableStart -- setting size of the icon?).
It's always wrong to set android:layout_height="wrap_content" for a ListView. It works as expected with android:layout_height="fill_parent". More detailed explanation could be found here The World of ListView
Though I don't know if this is intended behaviour or bug, this happens when you use drawableStart. Change it to drawableLeft and it will draw the layout properly.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mylabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="4dp"
android:drawablePadding="8dp"
android:drawableLeft="#drawable/reminder"
android:lines="1"
android:textSize="24sp" >
</TextView>

Android - Retrieving a string from a specific element of a gridview

I'm pretty new to Android and I have been playing about with GridView. I've got stuck trying to retrieve Strings from individual elements of the GridView so that I can save state based on the changes a user has made.
I've mocked up a stripped down version of what I'm trying to do for this question:
The view of each element in the grid is made up of a TextView and an EditText defined by the following xml file; grid_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id = "#+id/single_item_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id = "#+id/label"
android:layout_width = "fill_parent"
android:layout_height="wrap_content"
android:inputType="text">
</TextView>
<EditText
android:id = "#+id/item_value"
android:layout_width = "fill_parent"
android:layout_height="wrap_content"
android:inputType="text">
</EditText>
</LinearLayout>
My main.xml, consisting of a button and a gridview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/editbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRetrieveButtonClick"
android:text="#string/get" android:clickable="true"/>
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="250dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:paddingTop="50dp">
</GridView>
</LinearLayout>
My Activity Class:
package com.jdev.simplegrid;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;
public class SimpleGridActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
//Some hard-coded sample data -each person has a birth-name and a nickname
ArrayList<Person> people = new ArrayList<Person>();
people.add(new Person("David","Dave"));
people.add(new Person("Bruce","Batman"));
people.add(new Person("John","J"));
gridview.setAdapter(new SimpleAdapter(this, people));
}
public void onRetrieveButtonClick(View view)
{
Toast.makeText(getBaseContext(), "Get the String value of EditText at position 1 of the gridview e.g Batman", Toast.LENGTH_LONG).show();
//Get the String value of EditText at position 1 of the gridview. e.g Batman
}
}
And finally my Adapter for the view:
package com.jdev.simplegrid;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
public class SimpleAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Person> personList;
public SimpleAdapter(Context c, ArrayList<Person> people) {
mContext = c;
personList = people;
}
public int getCount() {
return personList.size();
}
public Person getItem(int position) {
return personList.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.grid_item, parent, false);
TextView birthnameLabel=(TextView)view.findViewById(R.id.birthname);
birthnameLabel.setText(personList.get(position).getBirthname());
EditText nicknameText=(EditText)view.findViewById(R.id.nickname);
nicknameText.setText(personList.get(position).getNickname());
return view;
}
}
So my question is, how do I retrieve the a value from the gridview on the click of a button. Say the value "Batman" in EditText at position 1 of the gridview.
I feel like I'm really missing something here!
gridview.getAdapter().getItem(1).getNickname();
Is that what you're looking for? assuming your Person object has a getter method for the nickname of course. - Sorry, obviously I could've seen that in your custom adapter.
If your the idea is the user can change the nickname in the EditText, you'll probably want to add a TextChangedListener (TextWatcher) to each of them and after editting update the nickname on the Person object associated with that position in the grid; e.g. with the help of a setNickname(String) method.
The easiest way to think about this is probably in terms of 'models' and 'views'. The TextViews and EditTexts are the views, whereas the Person objects in the adapter are the models. If you want to make any changes to the data, modify the underlying models with some logic and simply have the views update/refresh after that.

Empty ListView with simple_list_item_multiple_choice layout

How to handle an empty ListView if I use simple_list_item_multiple_choice layout?
'Android Developers' say that I should use the android prefix
android:id="#android:id/empty
But cannot take in mind how to use it with simple_list_item_multiple_choice
protected ListView mFavList;
ArrayList<String> fakeFavs;
mFavList.setAdapter(new ArrayAdapter<String>(this.android.R.layout.simple_list_item_multiple_choice,fakeFavs);
if fakeFavs is null?
I solved my problem.
All I need - "empty" tag in main.xml layout and string of code:
mFavList.setEmptyView(findViewById(android.R.id.empty));
In my program fakeFavs is populating from text file.
In case of empty file, the empty list is properly handled.
Maybe it will be useful for somebody. Working example:
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HelloAndroid3 extends Activity {
/** Called when the activity is first created. */
static final String split_symbol = "\n";
protected ListView mFavList;
protected ArrayList<String> fakeFavs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fakeFavs = new ArrayList<String>();
this.mFavList = (ListView) this.findViewById(R.id.list_favorites);
refreshFavListItems();
}
private void refreshFavListItems() {
//put some code here that populates fakeFavs
//.......
mFavList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, fakeFavs));
mFavList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mFavList.setEmptyView(findViewById(android.R.id.empty));
//if fakeFavs will be empty, list shows "No Data"
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<ListView android:id="#+id/list_favorites"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
/>
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF0000"
android:text="No Data"/>

Categories

Resources