Android: ListView "setOnItemSelectedListener" not working - java

I have a ListView (of a predefined set of quotes in a string array) in my android program that does not seem to work when an item is selected. The ListView is populated, but the toast message in my onClickListener is never called. I am not sure what the issue is here. I have never run into this problem before.
Here is my onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
List<String> quotesList = new ArrayList<String>(Arrays.asList(quotes));
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, quotesList);
listView.setAdapter(arrayAdapter);
listView.setOnItemSelectedListener(new ListView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Toast.makeText(getApplicationContext(), "Toast", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
}
Here is my activity_main.xml
<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"
android:background="#b2cfff"
tools:context="com.examples.myteststuff.listviews.MainActivity">
<LinearLayout
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:src="#drawable/icon"
android:layout_height="wrap_content" />
<ListView
android:layout_width="match_parent"
android:id="#+id/listView"
android:background="#drawable/border"
android:layout_marginHorizontal="8dp"
android:layout_marginVertical="8dp"
android:layout_height="match_parent"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

Try setOnItemClickListener instead :
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Toast", Toast.LENGTH_SHORT).show();
}
});
Hope this helps

Related

How to set the margin if using viewbinding

I want to set the margin on the LinearLayout in activity_main.xml, but because I'm using viewbinding, the margin doesn't show any result. Is there a way to have the margins on the LinearLayout set even when using viewbinding?
build.gradle
android {
viewBinding {
enabled = true
}
}
acivity_main.xml
<LinearLayout 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"
android:layout_margin="20dp"
android:id="#+id/idLayout"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/idText1"
android:textSize="20sp"
android:text="HELLO WORLD"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click"
android:layout_margin="100dp"
android:id="#+id/idButton1"/>
</LinearLayout>
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.idText1.setText("This is view binding");
binding.idButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
}
});
}

Why does listview is not showing on my emulator?

I'm making simple listview of therapies and the list is not showing on the emulator. I've upgraded and downgraded my api from 22 to 30 and change relative layout to linear layout but still the list is not showing.
activty_stress.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
android:orientation="vertical"
android:weightSum="9"
android:background="#83BCD4"
tools:context=".stress">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Find your relaxation"
android:textColor="#color/white"
android:textSize="18pt" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"/>
</RelativeLayout>
stress.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stress);
ListView listView = findViewById(R.id.listview);
List<String> list = new ArrayList<>();
list.add("Therapy1");
list.add("Therapy2");
list.add("Therapy3");
list.add("Therapy4");
list.add("Therapy5");
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==0){
//clicked therapy1
startActivity(new Intent(stress.this,Therapy1.class));
} else if (position==1){
//clicked therapy2
}else{
}
}
});
}
Heyy try replacing your RelativeLayout with LinearLayout, or remove weightSum because weightSum cannot be used with RelativeLayout
Replace with this code.
Note: Whenever you give textSize, give it in sp not in Pixel.
activty_stress.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#83BCD4"
android:orientation="vertical">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Find your relaxation"
android:textColor="#color/white"
android:textSize="30sp" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp" />
</RelativeLayout>
stress.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listview);
List<String> list = new ArrayList<>();
list.add("Therapy1");
list.add("Therapy2");
list.add("Therapy3");
list.add("Therapy4");
list.add("Therapy5");
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
//clicked therapy1
// startActivity(new Intent(stress.this,Therapy1.class));
} else if (position == 1) {
//clicked therapy2
} else {
}
}
});
}
Output:

cant set onclick on recylerview(cardview)

MainActivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference reference;
FirebaseRecyclerAdapter<Bookdeets,Bkhomeholder>adapter;
FirebaseRecyclerOptions<Bookdeets> options;
ProgressBar loading;
FloatingActionButton searchbtn;
TextView logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reference = FirebaseDatabase.getInstance().getReference().child("books");
reference.keepSynced(true);
recyclerView = (RecyclerView) findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
loading=(ProgressBar)findViewById(R.id.loading);
searchbtn=(FloatingActionButton)findViewById(R.id.searchbtn);
logout = (TextView) findViewById(R.id.Logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Logout();
}
});
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Opensearchpage();
}
});
options = new FirebaseRecyclerOptions.Builder<Bookdeets>()
.setQuery(reference, Bookdeets.class).build();
adapter = new FirebaseRecyclerAdapter<Bookdeets, Bkhomeholder>(options) {
#Override
protected void onBindViewHolder(#NonNull Bkhomeholder holder, int position, #NonNull Bookdeets model) {
Picasso.get().load(model.getImage()).into(holder.bookimg, new Callback() {
#Override
public void onSuccess() {
loading.setVisibility(View.GONE);
}
#Override
public void onError(Exception e) {
Toast.makeText(getApplicationContext(), "could not get the image", Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
}
});
holder.title.setText(model.getBookname());
}
#NonNull
#Override
public Bkhomeholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewlay, parent, false);
return new Bkhomeholder(view);
}
};
GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),3);
recyclerView.setLayoutManager(gridLayoutManager);
adapter.startListening();
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
if(adapter!=null)
adapter.startListening();
loading.setVisibility(View.VISIBLE);
}
#Override
protected void onStop() {
super.onStop();
if(adapter!=null)
adapter.stopListening();
}
#Override
protected void onResume() {
super.onResume();
if(adapter!=null)
adapter.startListening();
}
public void Opensearchpage(){
Intent intent=new Intent(this, SearchPage.class);
startActivity(intent);
}
public void Logout() {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
Bkhomeholder.java
public class Bkhomeholder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView bookimg;
public Bkhomeholder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.bkdettitle);
bookimg = itemView.findViewById(R.id.bkdetimg);
}
activity_main.xml
<RelativeLayout 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=".homepage.MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="4dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="Library App"
android:textAlignment="center"
android:textColor="#E21B1B"
android:textSize="32dp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:clipChildren="true"
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="525dp"
android:layout_marginStart="8dp"
android:layout_marginTop="75dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/searchbtn"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginStart="345dp"
android:layout_marginTop="480dp"
android:layout_marginEnd="12dp"
android:background="#B3E5FC"
android:clickable="true"
app:srcCompat="#drawable/customicon" />
<ProgressBar
android:id="#+id/loading"
style="?android:attr/progressBarStyle"
android:layout_width="76dp"
android:layout_height="76dp"
android:layout_marginStart="163dp"
android:layout_marginTop="253dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="253dp"
android:visibility="invisible"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="25dp"
android:id="#+id/Logout"
android:layout_centerHorizontal="true"
android:text="Logout"
android:textAlignment="center"
android:textSize="14sp"
android:layout_marginBottom="8dp"
android:layout_marginTop="565dp"
cardview xml
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:id="#+id/bookcardview"
android:layout_width="120dp"
android:layout_height="190dp"
android:layout_margin="5dp"
cardview:cardCornerRadius="4dp">
<LinearLayout
android:id="#+id/bkdetlinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="ExtraText"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:layout_marginEnd="4dp"
>
<ImageView
android:id="#+id/bkdetimg"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#2d2d2d"
android:clickable="true"
android:scaleType="fitXY" />
<TextView
android:id="#+id/bkdettitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Book title"
android:textColor="#2d2d2d"
android:textSize="12sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
i tried setting on click on the cardviewholder that is separate xml file which is inflated in my mainactivity oncreate and set the onclick listener under
onBindViewHolder but i got a error regarding null object refference as if the activity could not detect the cardview
You can set OnClickListener on RecyclerView item inside onBindViewHolder like below:
#Override
protected void onBindViewHolder(#NonNull Bkhomeholder holder, int position, #NonNull Bookdeets model) {
....
holder.title.setText(model.getBookname());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do your operation here
}
});
}
Update: Remove android:clickable="true" from cardview layout like below:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:foreground="?android:attr/selectableItemBackground"
android:id="#+id/bookcardview"
android:layout_width="120dp"
android:layout_height="190dp"
android:layout_margin="5dp"
cardview:cardCornerRadius="4dp">
<LinearLayout
android:id="#+id/bkdetlinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="ExtraText"
android:foreground="?android:attr/selectableItemBackground"
android:layout_marginEnd="4dp"
>
<ImageView
android:id="#+id/bkdetimg"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#2d2d2d"
android:scaleType="fitXY" />
<TextView
android:id="#+id/bkdettitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Book title"
android:textColor="#2d2d2d"
android:textSize="12sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>

ListView onItemClick "unfortunately myapp has stopped" error android

I used ListView on my layout but on ItemClick event it shows this error : "unfortunately myappname has stopped"
this is my java code booking.java the OnCreate method :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.booking);
lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + i, Toast.LENGTH_SHORT).show();
}
});
}
And my layout
<?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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/booking"
>
<TextView
android:id="#+id/textView"
android:layout_width="302dp"
android:layout_height="25dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="32dp"
android:layout_marginRight="8dp"
android:layout_marginTop="60dp"
android:text="TextView"
android:textAlignment="textStart"
android:textColor="#f0f0f0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.011" />
<ListView
android:id="#+id/list"
android:layout_width="302dp"
android:layout_height="398dp"
android:layout_marginLeft="32dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="11dp"
app:layout_constraintTop_toBottomOf="#+id/textView"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
app:layout_constraintVertical_bias="0.0"
tools:layout_editor_absoluteY="97dp" />
</android.support.constraint.ConstraintLayout>
Can anyone please help me to solve this problem ?
Try this
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
Try setOnItemSelectedListener instead of onItemClickedListener.

make popupWindow TextView clickable?

I have a PopupWindow on my activity and PopupWindow contain some TextView i want to make that text clickable.please help i m new in android.
main activity.java:
public class ListViewForDeleteContact extends AppCompatActivity {
ListView myListView;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LayoutInflater layoutInflater=(LayoutInflater)ListViewForDeleteContact.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dfg= layoutInflater.inflate(R.layout.popupWindow,(ViewGroup)findViewById(R.id.popupId));
PopupWindow popupWindow=new PopupWindow(dfg,420,300,true);
popupWindow.showAtLocation(dfg, Gravity.CENTER, 0, 0);
popupWindow.setOutsideTouchable(true);
}
});
}
}
main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/trans">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
popupWindow.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popupId"
android:background="#546e7a"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="are you sure"
android:layout_margin="20dp"
android:id="#+id/textView7"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="no"
android:id="#+id/textView8"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yes"
android:textColor="#color/colorAccent"
android:id="#+id/textView9"
android:layout_below="#+id/textView7"
android:layout_alignBottom="#+id/textView8"
android:layout_alignEnd="#+id/textView7"/>
</RelativeLayout>
main.xml activity use popupWindow.xml for displaying popup i want to make clickable TextView which are present in popupWindow.xml.
You can access TextView using findViewById method in your dfg View variable.
Example
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LayoutInflater layoutInflater=(LayoutInflater)ListViewForDeleteContact.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dfg= layoutInflater.inflate(R.layout.popupWindow,(ViewGroup)findViewById(R.id.popupId));
TextView textView7 = (TextView) dfg.findViewById(R.id.textView7);
textView7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something when the textview is clicked
}
});
... // for other textviews
PopupWindow popupWindow=new PopupWindow(dfg,420,300,true);
popupWindow.showAtLocation(dfg, Gravity.CENTER, 0, 0);
popupWindow.setOutsideTouchable(true);
}

Categories