androidx.spinner onItemSelectedListener not working - androidx

Am trying to use a spinner in a layout. I can add and select items to the spinner but I cannot retrieve the selected item. This is the main activity:
class pageNewPurchaseOrder : AppCompatActivity() {
lateinit var spinnerVendorX: androidx.appcompat.widget.AppCompatSpinner
var spinnerArray: java.util.ArrayList<CharSequence> = ArrayList<CharSequence>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_page_new_purchase_order)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
spinnerVendorX = findViewById(R.id.spinnerVendorX)
spinnerVendorX.adapter = ArrayAdapter(this#pageNewPurchaseOrder, android.R.layout.simple_spinner_item, spinnerArray)
spinnerVendorX.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Log.d("aaa", "This code is not running!")
}
}
}
}
This is the layout activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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="?attr/colorPrimary"
android:fillViewport="true"
android:focusable="true"
android:focusableInTouchMode="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".pageNewPurchaseOrder"
tools:showIn="#layout/activity_page_new_purchase_order">
<androidx.appcompat.widget.AppCompatSpinner
android:padding="10dp"
android:background="#drawable/bgselect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/lbl2"
android:id="#+id/spinnerVendorX" />
</androidx.core.widget.NestedScrollView>
Am getting result this on the logcat when I select an item: E/ViewRootImpl(31835): sendUserActionEvent() mView == null.I get tj=he same results even when I use <Spinner instead of <androidx.appcompat.widget.AppCompatSpinner

User must have to add data in the ArrayList. Here, you are initialising arrayList and set it but not adding data in ArrayList. Please add data in ArrayList then try it. Thank you.

Related

How to retrieve data from firebase into a recycler view using Kotlin (including images)?

I'm retrieving data from firebase into a recycler view using Kotlin. I'm able to load the text easily but unable to load the images. I have used Picasso library for the same. There is no error in the code, can anyone suggest something?
Following is my code:
1) This is the main activity class
class MainActivity : AppCompatActivity()
{
lateinit var recyclerView: RecyclerView
lateinit var ref:DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView=findViewById(R.id.rvFirebase)
ref= FirebaseDatabase.getInstance().reference.child("Restaurants")
recyclerView.layoutManager=LinearLayoutManager(this)
val option=FirebaseRecyclerOptions.Builder<ResModel>().setQuery(ref,ResModel::class.java).build()
val firebaseRecyclerAdapter= object :FirebaseRecyclerAdapter<ResModel,RViewHolder>(option){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RViewHolder {
val itemView= LayoutInflater.from(this#MainActivity).inflate(R.layout.single_row,parent,false)
return RViewHolder(itemView)
}
override fun onBindViewHolder(holder: RViewHolder, position: Int, model: ResModel) {
val refId = getRef(position).key.toString()
ref.child(refId).addValueEventListener(object:ValueEventListener{
override fun onCancelled(error: DatabaseError) {
}
override fun onDataChange(snapshot: DataSnapshot) {
holder.rCost.text = model.resCost
holder.rName.text = model.resName
Picasso.get().load(model.resImage).into(holder.rImage)
holder.rRating.text=model.resRating
}
})
}
}
recyclerView.adapter=firebaseRecyclerAdapter
firebaseRecyclerAdapter.startListening()
}
class RViewHolder(itemView:View):RecyclerView.ViewHolder(itemView) {
var rImage:ImageView=itemView.findViewById(R.id.imgRestaurant)
var rName:TextView=itemView.findViewById(R.id.txtRestaurantName)
var rCost:TextView=itemView.findViewById(R.id.txtCost)
var rRating:TextView=itemView.findViewById(R.id.txtResRating)
}
}
2) This is the model class
class ResModel
{
var resCost: String =" "
var resImage: String=" "
var resName: String=" "
var resRating: String=" "
constructor():this("","","",""){
}
constructor(resCost:String,resImage: String,resName:String,resRating:String){
this.resCost=resCost
this.resImage=resImage
this.resName=resName
this.resRating=resRating
}
}
3)This is the main activity xml file
<?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="wrap_content"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:id="#+id/rvFirebase"/>
</RelativeLayout>
4) This is the card view xml file which is being used in recycler view
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_margin="5dp"
app:cardCornerRadius="4dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/carViewXml">
<LinearLayout
android:id="#+id/llContent"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:background="#ffffff"
android:weightSum="6">
<ImageView
android:layout_marginTop="6dp"
android:layout_weight="1.7"
android:id="#+id/imgRestaurant"
android:layout_width="0dp"
android:layout_height="90dp"
android:src="#drawable/ic_food"
android:padding="5dp"
android:layout_marginStart="10dp"
android:scaleType="centerCrop"
android:fadingEdge="vertical"
android:background="#drawable/rounded_image"/>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:layout_weight="3.3"
android:layout_marginStart="5dp">
<TextView
android:id="#+id/txtRestaurantName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
android:text="name_of_the_restaurant"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/txtCost"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_below="#id/txtRestaurantName"
android:layout_alignParentBottom="true"
android:layout_marginTop="20dp"
android:layout_marginBottom="0dp"
android:padding="8dp"
android:text="Rs. 299"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="9dp"
android:layout_weight="1"
android:layout_marginStart="3dp">
<ImageView
android:id="#+id/imgFavResIcon"
android:layout_width="match_parent"
android:layout_height="23dp"
android:layout_alignParentTop="true"
android:layout_marginTop="11dp"
android:src="#drawable/ic_favorite_res" />
<TextView
android:id="#+id/txtResRating"
android:layout_width="match_parent"
android:layout_height="53dp"
android:layout_below="#id/imgFavResIcon"
android:layout_marginTop="22dp"
android:padding="4dp"
android:text="4.5"
android:textAlignment="center"
android:textColor="#FB8C00"
android:textSize="14sp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
4) This is the image of how I stored data on firebase database and storage
Firebase Databse
Firebase storage
Not sure how Picasso can handle Firebase ui storage but with glide you do something like this:
implementation 'com.firebaseui:firebase-ui-storage:6.3.0' add firebase UI Storage
Then:
val storageReference: StorageReference = model.resImage //not sure about the reference here - eg FirebaseStorage.getInstance().getReference().child("yourImageReferencePath")
Glide.with(this /* context */)
.using(FirebaseImageLoader())
.load(storageReference)
.into(holder.rImage)
Also please take a look at other resources

ListView ID called on null? (Kotlin)

I'm new to Kotlin and im trying to build a HomePage where there is a BottomNavigation with 3 Fragment pages but in 1 of the pages I set a ListView and whenever I call the ID it gives the following errer(Caused by: java.lang.IllegalStateException: categoryListView must not be null)
Here is how Im calling it in my HomePage which is where the content appears:
class HomePage : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
lateinit var adapter : CategoryAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_page)
adapter = CategoryAdapter(this, DataService.categories)
categoryListView.adapter = adapter
navView.setNavigationItemSelectedListener(this)
bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
replaceFragment(HomeFragment())
}
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when(item.itemId) {
R.id.Bottom_Nav_Home -> {
println("Home pressed")
replaceFragment(HomeFragment())
return#OnNavigationItemSelectedListener true
}
R.id.Bottom_Nav_Notifs -> {
println("Notification pressed")
replaceFragment(NotifsFragment())
return#OnNavigationItemSelectedListener true
}
R.id.Bottom_Nav_List -> {
println("List pressed")
replaceFragment(ListFragment())
return#OnNavigationItemSelectedListener true
}
}
false
}
private fun replaceFragment(fragment: Fragment) {
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.NavPageFragment, fragment)
fragmentTransaction.commit()
}
}
am I doing it correct? or am I supposed to call the categoryListView elsewhere? because I tried in my ListFragment which is where my activity code is and it gave a context error
here is how the Fragment activity looks:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/Bottom_List"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.ListFragment">
<ListView
android:id="#+id/categoryListView"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
You are trying to get the categoryListView resolved inside the activity but it is (as far as I understand) part of the fragment. This simply does not work.
The CategoryAdapter and the ListView should be used inside your HomeFragment class and this will work then.
So move this code into your fragment:
adapter = CategoryAdapter(this, DataService.categories)
categoryListView.adapter = adapter
Update
I would move it into the onViewCreated() method. There you can simply rely on the fact that there is a view available with a context.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
adapter = CategoryAdapter(view.context, DataService.categories)
categoryListView.adapter = adapter // categoryListView will be not null here
}

How to make custom buttons in corona, Lua

I'm trying to make a mobile application with a screen that looks like this:
I'm making this using Corona, it's written in the Lua language
It's a scrollable list of buttons, I somewhat understand the scroll aspect. What I'm having problems now is making a button that can have more than one line of text and also an image. I've literally been searching for hour but haven't found anything (I'm probably bad at finding things). I think I'd have to create a custom button but I have no idea how to do this. I would appreciate some help with this be it a link or just some lines of text explaining it, thank you so much!
use custom view
custom_button_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iconImgV"
android:layout_alignParentRight="true"
android:layout_width="100dp"
android:layout_alignParentTop="true"
android:background="#ff0000"
android:layout_height="100dp" />
<TextView
android:id="#+id/titleTv"
android:textSize="18sp"
android:text="Title"
android:layout_toLeftOf="#+id/iconImgV"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/descriptionTv"
android:layout_width="wrap_content"
android:text="description"
android:textSize="14sp"
android:layout_below="#+id/titleTv"
android:layout_toLeftOf="#+id/iconImgV"
android:layout_height="wrap_content" />
</RelativeLayout>
and CustomButtonView.java
public class CustomButtonView extends RelativeLayout {
Context context;
//view
ImageView iconImgV;
TextView titleTv, descriptionTv;
//value
int drawableIcon;
String title,description;
public CustomButtonView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
public CustomButtonView(Context context) {
super(context);
init();
}
public CustomButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customButtonViewAttrs);
drawableIcon = typedArray.getInt(R.styleable.customButtonViewAttrs_drawableIcon,0);
title = typedArray.getString(R.styleable.customButtonViewAttrs_title);
description = typedArray.getString(R.styleable.customButtonViewAttrs_description);
typedArray.recycle();
init();
}
public void init() {
if (isInEditMode())
return;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.custom_button_view, null);
iconImgV = (ImageView) myView.findViewById(R.id.iconImgV);
titleTv = (TextView) myView.findViewById(R.id.titleTv);
descriptionTv = (TextView) myView.findViewById(R.id.descriptionTv);
titleTv.setText(title);
addView(myView);
}
}
and value/attrs.xml
<declare-styleable name="customButtonViewAttrs">
<attr name="title" format="string" />
<attr name="description" format="string" />
<attr name="drawableIcon" format="integer" />
</declare-styleable>
you can use this way
<com.example.rasoul.testprojectstacj.CustomButtonView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:title = "Car"/>
Found a solution, widget.newTable does this perfectly

fragment - navigation drawer - app stopped error

Greeting
When I click on the camera text, the app shows an error said "The application has stopped". How it can be fixed?
MaingActivity.java
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
CameraFragment cameraFragment = new CameraFragment();
FragmentManager manager= getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.relativelayout_for_fragment,
cameraFragment,
cameraFragment.getTag()
).commit();
} else if (id == R.id.nav_gallery) {
Toast.makeText(this,"Gallary",Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I have found it
Select contant_main.xml => click on icon refer Constrains
The code will be as the following
<?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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.shakeralmoosa.nav1.MainActivity"
tools:showIn="#layout/app_bar_main"
android:id="#+id/mainLayout">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="0dp"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
android:layout_marginStart="5dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="5dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="4dp"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="4dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
</RelativeLayout>
</android.support.constraint.ConstraintLayout>

Navigation Drawer opens to different fragments

I am a beginner when it comes to Android. I have spent hours reading tutorials, watching videos, and combing through stackoverflow trying to figure this out. Even with all the online resources available , I still can't figure this out.
I want my list view always on the main screen, but when I swipe I want the navigation drawer to slide in and display a different fragment depending on which item in the list view has been selected. For example if the user selected 'account', when they slide from the right the account fragment would display.
I've left in 'navList' and 'nav2List' for testing, but I would like these to be fragments.
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bankMenu"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</ListView>
</RelativeLayout>
<!-- Side navigation drawer UI -->
<ListView
android:id="#+id/navList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#ffeeeeee"/>
<ListView
android:id="#+id/nav2List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#ffeeeeee"/>
</android.support.v4.widget.DrawerLayout>
JAVA
public class MainActivity extends AppCompatActivity {
private ListView menu;
private ListView mDrawerList;
private ListView secondDrawerList;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = (ListView) findViewById(R.id.bankMenu);
mDrawerList = (ListView)findViewById(R.id.navList);
secondDrawerList = (ListView)findViewById(R.id.nav2List);
addBankingListItems(); // populate the banking items list
menu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) menu.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG)
.show();
if (itemPosition < 4) { // TESTING FUNCTIONALITY
addDrawerItems();
} else {
addSecondDrawerItems();
}
}
});
}
---EDIT---
This issue has been resolved.
In the xml file, i changed the two ListViews to a RelativeView.
<RelativeLayout
android:id="#+id/frame_to_be_replaced"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_below="#+id/topRL"
android:background="#ffeeeeee">
</RelativeLayout>
In the MainActivity, I created a fragment manager, then after my switch statement, i replaced the frame with the required one. Hope this can help someone, send me a pm for more info.
FragmentManager fragmentManager = getFragmentManager();
switch (itemPosition) {
case 0:
fragment = MyFrag1.newInstance("", ""); // fragment declared above
break;
case 1:
fragment = MyFrag2.newInstance("", "");
break;
case 2: etc....
fragmentManager.beginTransaction()
.replace(R.id.frame_to_be_replaced, fragment)
.commit();

Resources