I am new to programming and want to ask for help because I am stuck on this task.
Clicking on the RecyclerView gets this error.
Below I will attach my code and hope for your help and solutions to the problem. Thank you
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.skreep.worko, PID: 24044
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skreep.worko/com.skreep.worko.DetailActivity}: java.lang.NullPointerException: workout_title must not be null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7560)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: workout_title must not be null
at com.skreep.worko.DetailActivity.onCreate(DetailActivity.kt:32)
at android.app.Activity.performCreate(Activity.java:7894)
at android.app.Activity.performCreate(Activity.java:7881)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7560)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Workout Adapter
package com.skreep.worko.adapter
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.skreep.worko.DetailActivity
import com.skreep.worko.R
import com.skreep.worko.databinding.ItemWorkoutBinding
import com.skreep.worko.model.WorkoutData
class WorkoutAdapter(var c:Context,var workoutList:ArrayList<WorkoutData>
):RecyclerView.Adapter<WorkoutAdapter.WorkoutViewHolder>()
{
inner class WorkoutViewHolder(var v:ItemWorkoutBinding): RecyclerView.ViewHolder(v.root){}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WorkoutViewHolder {
val inflter = LayoutInflater.from(parent.context)
val v = DataBindingUtil.inflate<ItemWorkoutBinding>(
inflter, R.layout.item_workout,parent,
false)
return WorkoutViewHolder(v)
}
override fun onBindViewHolder(holder: WorkoutViewHolder, position: Int) {
val newList = workoutList[position]
holder.v.isWorkouts = workoutList[position]
holder.v.root.setOnClickListener {
val name = newList.name
val description = newList.description
val fullTime = newList.fullTime
val workoutDesc = newList.workoutDesc
val workoutName = newList.workoutName
val workoutTime = newList.workoutTime
val mIntent = Intent(c,DetailActivity::class.java)
mIntent.putExtra("description",description)
mIntent.putExtra("name",name)
mIntent.putExtra("fullTime",fullTime)
mIntent.putExtra("workoutDesc",workoutDesc)
mIntent.putExtra("workoutName",workoutName)
mIntent.putExtra("workoutTime",workoutTime)
c.startActivity(mIntent)
}
}
override fun getItemCount(): Int {
return workoutList.size
}
}
Detail Activity
package com.skreep.worko
import android.os.Bundle
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.database.DatabaseReference
import com.skreep.worko.adapter.WorkoutAdapter
import com.skreep.worko.model.WorkoutData
import kotlinx.android.synthetic.main.activity_detail.*
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.item_workout.*
import kotlinx.android.synthetic.main.item_workout_detail.*
class DetailActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
val workoutIntent = intent
val name = workoutIntent.getStringExtra("name")
val description = workoutIntent.getStringExtra("description")
val workoutName = workoutIntent.getStringExtra("workoutName")
detail_name.text = name
detail_desc.text = description
workout_title.text = workoutName
}
}
Home Activity
package com.skreep.worko
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.database.*
import com.skreep.worko.adapter.WorkoutAdapter
import com.skreep.worko.model.WorkoutData
import kotlinx.android.synthetic.main.activity_detail.*
import kotlinx.android.synthetic.main.activity_home.*
class HomeActivity : BaseActivity() {
lateinit var mDataBase:DatabaseReference
private lateinit var workoutList:ArrayList<WorkoutData>
private lateinit var mAdapter:WorkoutAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
workoutList = ArrayList()
mAdapter = WorkoutAdapter(this, workoutList)
recyclerworkoutList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
recyclerworkoutList.setHasFixedSize(true)
recyclerworkoutList.adapter = mAdapter
getWorkoutData()
}
private fun getWorkoutData() {
mDataBase = FirebaseDatabase.getInstance().getReference("Workout")
mDataBase.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (userSnapshot in snapshot.children) {
val workout = userSnapshot.getValue(WorkoutData::class.java)
workoutList.add(workout!!)
}
recyclerworkoutList.adapter = mAdapter
}
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(this#HomeActivity,
error.message, Toast.LENGTH_SHORT).show()
}
})
}
}
XML Activity Detail
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="isData"
type="com.skreep.worko.model.WorkoutData" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/gray"
tools:context=".DetailActivity">
<ImageView
android:id="#+id/back_ic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_margin="20dp"
android:padding="20dp"
android:src="#drawable/ic_back">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:fontFamily="#font/poppins"
android:padding="20dp"
android:text="#string/app_name"
android:textSize="20sp"></TextView>
<TextView
android:id="#+id/detail_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="120dp"
android:fontFamily="#font/poppins_bold"
android:text="#{isData.name}"
android:textColor="#color/darkblue"
android:textSize="26sp"></TextView>
<TextView
android:id="#+id/detail_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/detail_name"
android:layout_alignLeft="#+id/detail_name"
android:fontFamily="#font/poppins"
android:text="#{isData.workoutDesc}"
android:textColor="#color/lightgray">
</TextView>
<TextView
android:id="#+id/tv_workout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="310dp"
android:fontFamily="#font/poppins_bold"
android:gravity="center"
android:text="Упражнения"
android:textColor="#color/darkblue"
android:textSize="20sp"></TextView>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/workoutListDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_workout"
android:orientation="vertical"
android:padding="10dp"
tools:itemCount="1"
/>
</RelativeLayout>
</layout>
Xml activity Home
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="isWorkouts"
type="com.skreep.worko.model.WorkoutData" />
</data>
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/darkblue"
android:orientation="vertical"
tools:context=".HomeActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:fontFamily="#font/poppins"
android:gravity="center"
android:padding="20dp"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:id="#+id/welcome"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/poppins"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:text="#string/welcome"
android:textColor="#color/white"
android:textSize="30sp"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/welcome_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/poppins"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:text="#string/welcome_description"
android:textColor="#color/desc_color"
android:textSize="14sp"
app:layout_constraintTop_toBottomOf="#id/welcome" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerworkoutList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal"
android:paddingTop="40dp"
tools:itemCount="1"
tools:listitem="#layout/item_workout" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
</layout>
item_workout xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="isWorkouts"
type="com.skreep.worko.model.WorkoutData" />
</data>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".SplashActivity">
<androidx.cardview.widget.CardView
android:layout_width="250dp"
android:layout_height="350dp"
android:layout_margin="10dp"
android:backgroundTint="#color/gray"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/watch_ic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:src="#drawable/ic_watch"
app:tint="#color/darkblue"></ImageView>
<TextView
android:id="#+id/tvfulltime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="50dp"
android:layout_marginTop="26dp"
android:fontFamily="#font/poppins"
android:text="#{isWorkouts.fullTime}"
android:textSize="10sp"></TextView>
<TextView
android:id="#+id/tvtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="27dp"
android:layout_marginTop="80dp"
android:fontFamily="#font/poppins_bold"
android:text="#{isWorkouts.name}"
android:textColor="#color/darkblue"
android:textSize="24sp">
</TextView>
<TextView
android:id="#+id/tvdesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvtitle"
android:layout_marginStart="10dp"
android:padding="20dp"
android:text="#{isWorkouts.description}"
android:textColor="#color/lightgray"
android:textSize="12sp"></TextView>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:src="#drawable/ic_next"
>
</ImageView>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</layout>
item workout detail xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="isWorkout"
type="com.skreep.worko.model.WorkoutData" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".SplashActivity">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="150dp"
android:backgroundTint="#color/gray">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/workout_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:fontFamily="#font/poppins_bold"
android:text="#{isWorkout.workoutName}"
android:textColor="#color/darkblue"
android:textSize="24sp"></TextView>
<TextView
android:id="#+id/workout_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/workout_title"
android:layout_alignLeft="#+id/workout_title"
android:fontFamily="#font/poppins"
android:text="#{isWorkout.workoutName}"
android:textColor="#color/lightgray"
android:textSize="12sp"></TextView>
<TextView
android:id="#+id/workout_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/workout_title"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:text="#{isWorkout.workoutTime}"
android:textColor="#color/darkblue"
android:textSize="12sp">
</TextView>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
</layout>
Check your activity_detail XML file is missing a Textview called workout_title
You have it in a different XML layout file workout_detail xml
Related
I have a Navigation drawer that has four different fragments. On the Home Fragment Dashboard, I have eight different image buttons that I want to open a new activity I.E. when you click the Image Button TM's I want it to open the TM's activity. I'm using kotlin as well.
I've watched numerous videos and forums on YouTube and google and none have seemed to work for what I'm doing.
// Dashboard.kt is where I have my ImageButtons, where I want each button to open a new activity.
package com.example.militarymainenance
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class Dashboard : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_dashboard, container, false)
}
}
// fragment_dashboard.xml is where I have my ImageButtons, where I want each button to open a new 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"
tools:context=".Dashboard">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="32dp"
android:layout_marginRight="20dp">
<ImageView
android:id="#+id/txtdashboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/dashboard3"
android:textAlignment="center"
android:textColor="#FFF" />
</RelativeLayout>
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="3"
android:columnCount="2"
android:alignmentMode="alignMargins">
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardBackgroundColor="#color/material_on_surface_stroke"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
app:cardElevation="6dp"
app:cardCornerRadius="12dp"
android:layout_margin="12dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">
<ImageButton
android:id="#+id/card1"
android:src="#drawable/folder3"
android:scaleType="centerCrop"
android:layout_width="130dp"
android:layout_height="130dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:textColor="#color/white"
android:text="#string/tm_s"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
app:cardBackgroundColor="#color/material_on_surface_stroke"
app:cardElevation="6dp"
app:cardCornerRadius="12dp"
android:layout_margin="12dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">
<ImageButton
android:id="#+id/card2"
android:src="#drawable/circuit3"
android:scaleType="centerCrop"
android:layout_width="130dp"
android:layout_height="130dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:textColor="#color/white"
android:text="#string/schematics"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
app:cardBackgroundColor="#color/material_on_surface_stroke"
app:cardElevation="6dp"
app:cardCornerRadius="12dp"
android:layout_margin="12dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">
<ImageButton
android:id="#+id/card3"
android:src="#drawable/parts3"
android:scaleType="centerCrop"
android:layout_width="130dp"
android:layout_height="130dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:textColor="#color/white"
android:text="#string/parts_cheat_sheet"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
app:cardBackgroundColor="#color/material_on_surface_stroke"
app:cardElevation="6dp"
app:cardCornerRadius="12dp"
android:layout_margin="12dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">
<ImageButton
android:id="#+id/card4"
android:src="#drawable/load3"
android:scaleType="centerCrop"
android:layout_width="130dp"
android:layout_height="130dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:textColor="#color/white"
android:text="#string/generator_load_wiring"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</GridLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
// MainActivity.kt which controls my navigation drawer.
package com.example.militarymainenance
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import com.google.android.material.navigation.NavigationView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close)
toggle.isDrawerIndicatorEnabled = true
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
nav_menu.setNavigationItemSelectedListener(this)
setToolbarTitle("Dashboard")
changeFragment(Dashboard())
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
drawerLayout.closeDrawer(GravityCompat.START)
when(item.itemId){
R.id.dashboard -> {
setToolbarTitle("Dashboard")
changeFragment(Dashboard())
}
R.id.equipment_tracker -> {
setToolbarTitle("Equipment Tracker")
changeFragment(Equipment_tracker())
}
R.id.service_tracker -> {
setToolbarTitle("Service Tracker")
changeFragment(Service_tracker())
}
R.id.faults_tracker -> {
setToolbarTitle("Faults Tracker")
changeFragment(Faults_tracker())
}
R.id.share -> {
setToolbarTitle("Service Tracker")
changeFragment(Service_tracker())
}
R.id.rate_us -> {
setToolbarTitle("Faults Tracker")
changeFragment(Faults_tracker())
}
}
return true
}
fun setToolbarTitle(title:String){
supportActionBar?.title = title
}
fun changeFragment(frag:Fragment){
val fragment = supportFragmentManager.beginTransaction()
fragment.replace(R.id.fragment_container,frag).commit()
}
}
// activity_main.xml which controls my navigation bar
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#515050"
tools:context=".MainActivity">
<include layout="#layout/content_main" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
You should create ImageButton view in your xml file, then bind onClickListener to it and call startActivity when onClick triggers.
just an example to understand:
public class TabFragment1 extends Fragment {
ImageButton imageButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_fragment1, container, false);
imageButton = (ImageButton)view.findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(getActivity(),NewActivity.class);
}
});
return view;}
I am trying to implement view binding to one of my activity. The issue is I am not able to access the views and it shows unresolved reference.
Now when I am using tools:viewBindingIgnore="true"
then there are no issues with the views and I am able to access them but then I am getting unresolved symbol for the activity class.
activity_single_movie.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:visibility="gone"/>
<TextView
android:id="#+id/text_error"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Connection gone!!"
android:textColor="#color/white"
android:visibility="gone" />
<ScrollView
app:layout_constraintTop_toTopOf= "parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/movie_poster"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitCenter"
android:src="#drawable/placeholder_image"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp" >
<TextView
android:id="#+id/movie_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="movie"
android:textStyle="bold"
android:textSize="18sp" />
<TextView
android:id="#+id/movie_tagline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sub title"
android:textStyle="bold"
android:textSize="14sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="movie info"
android:textStyle="bold"
android:textSize="14sp" />
//Layout for Release Date
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Release Date: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_release_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="2019"
android:textSize="12sp"
style="bold" />
</LinearLayout>
//Layout for Rating
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Rating: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="5/10"
android:textSize="12sp"
style="bold" />
</LinearLayout>
//Layout for Runtime
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Runtime: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_runtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="2hrs 13mins"
android:textSize="12sp"
style="bold" />
</LinearLayout>
//Layout for Budget
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Budget: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_budget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="$550Million"
android:textSize="12sp"
style="bold" />
</LinearLayout>
//Layout for revenue
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="Budget: "
android:textSize="12sp"
style="bold" />
<TextView
android:id="#+id/movie_revenue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="$550Million"
android:textSize="12sp"
style="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
In SingleMovie.kt
package com.example.movieapp.ui.single_movie_details
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.bumptech.glide.Glide
import com.example.movieapp.R
import com.example.movieapp.data.api.POSTER_BASE_URL
import com.example.movieapp.data.api.TheMovieDBClient
import com.example.movieapp.data.api.TheMovieDBInterface
import com.example.movieapp.data.repository.NetworkState
import com.example.movieapp.data.vo.MovieDetails
import com.example.movieapp.databinding.ActivitySingleMovieBinding
import java.text.NumberFormat
import java.util.*
class SingleMovie : AppCompatActivity() {
private lateinit var viewModel: SingleMovieViewModel
private lateinit var movieRepository: MovieDetailsRepository
private lateinit var binding: ActivitySingleMovieBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySingleMovieBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
val movieId: Int = intent.getIntExtra("id", 1)
val apiService: TheMovieDBInterface = TheMovieDBClient.getClient()
movieRepository = MovieDetailsRepository(apiService)
viewModel = getViewModel(movieId)
viewModel.movieDetails.observe(this, Observer {
bindUi(it)
})
viewModel.movieDetailsNetworkState.observe(this, Observer {
binding.progress_bar.setVisibility(if (it == NetworkState.LOADING) View.VISIBLE else View.GONE)
binding.text_error.setVisibility( if(it == NetworkState.ERROR) View.VISIBLE else View.GONE)
})
}
fun bindUi(it: MovieDetails){
binding.movie_title.setText(it.title)
binding.movie_tagline.setText(it.tagline)
binding.movie_release_date.setText(it.releaseDate)
binding.movie_rating.setText(it.voteAverage.toString())
binding.movie_runtime.setText(it.runtime.toString() + "minutes")
val formatCurrency: NumberFormat = NumberFormat.getCurrencyInstance(Locale.US)
binding.movie_budget.setText(formatCurrency.format(it.budget))
binding.movie_revenue.setText(formatCurrency.format(it.revenue))
//for poster of movie
val moviePosterURL: String = POSTER_BASE_URL + it.posterPath
Glide.with(this)
.load(moviePosterURL)
.into(binding.movie_poster)
}
private fun getViewModel(movieId: Int): SingleMovieViewModel {
return ViewModelProviders.of(this, object: ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return SingleMovieViewModel(movieRepository, movieId) as T
}
}) [SingleMovieViewModel::class.java]
}
}
Errors while using tools:viewBindingIgnore="true"
Unresolved reference: ActivitySingleMovieBinding
Errors without using tools:viewBindingIgnore="true"
Unresolved reference: progress_bar
and similar for all the views
View Binding converts underscores to camelCase, the correct syntax is binding.progressBar
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:visibility="gone"/>
binding.progressBar.setVisibility(if (it == NetworkState.LOADING) View.VISIBLE else View.GONE)
I modified my code by referring to the "https://www.tutorialspoint.com/add-and-remove-views-in-android-dynamically-in-kotlin". There was no error in my code, but the view added when running in the app was not visible. I have no idea what the problem is. Please help me!!
Activity to which the view is added
package com.akj.callback
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import com.akj.callback.databinding.ActivitySearchSubject2Binding
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_search_subject_2.*
import kotlinx.android.synthetic.main.activity_search_subject_2.to_go_check
import kotlinx.android.synthetic.main.choiced_subject_list.*
import java.util.*
class search_subject_2 : AppCompatActivity() {
lateinit var binding3:ActivitySearchSubject2Binding
private var parentLinearLayout: LinearLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search_subject_2)
parentLinearLayout = findViewById(R.id.parent_linear_layout)
binding3= ActivitySearchSubject2Binding.inflate(layoutInflater)
setContentView(binding3.root)
userList3.onItemClickListener= AdapterView.OnItemClickListener{
parent, view, position, id ->
//parent?.getItemAtPosition(position).toString()
onAddField()
}
val user = arrayOf("abc", "bcd", "cde", "def", "efg")
val userAdapter: ArrayAdapter<String> = ArrayAdapter(
this,android.R.layout.simple_list_item_1,user)
to_go_check.setOnClickListener {
val intent6=Intent(this#search_subject_2,checkthesetting::class.java)
startActivity(intent6)
}
binding3.searchView3.setOnQueryTextListener(object :androidx.appcompat.widget.SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
binding3.searchView3.clearFocus()
if(user.contains(query)){
userAdapter.filter.filter(query)
}
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
if(newText==""){
}
else{
binding3.userList3.adapter=userAdapter
userAdapter.filter.filter(newText)
}
return false
}
})
}
fun onDelete(view: View) {
parentLinearLayout!!.removeView(view.parent as View)
}
fun onAddField() {
val inflater =
getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val rowView: View = inflater.inflate(R.layout.choiced_subject_list, null)
parentLinearLayout!!.addView(rowView, parentLinearLayout!!.childCount - 1)
Toast.makeText(applicationContext,"fdsvkgjh", Toast.LENGTH_SHORT).show()
}
}
choiced_subject_list.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="50dp"
android:orientation="horizontal">
<TextView
android:id="#+id/number_edit_text"
android:text="title_fdskhdsffsd"
android:textColor="#color/black"
android:textSize="30dp"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone"
/>
<Button
android:id="#+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="#android:drawable/ic_delete"
android:onClick="onDelete" />
</LinearLayout>
activity_search_subject_2.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".search_subject_2">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.04" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.94" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.03" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.97" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.06" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.11" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.87" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<androidx.appcompat.widget.SearchView
android:id="#+id/searchView3"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#drawable/coner_search_bar"
android:theme="#style/AppSearchView"
app:layout_constraintBottom_toTopOf="#id/guideline6"
app:layout_constraintEnd_toEndOf="#id/guideline4"
app:layout_constraintStart_toStartOf="#id/guideline3"
app:layout_constraintTop_toBottomOf="#id/guideline5"
app:queryHint="강좌 검색"
app:iconifiedByDefault="false"
/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/to_go_check"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintStart_toEndOf="#id/guideline3"
app:layout_constraintEnd_toStartOf="#id/guideline4"
app:layout_constraintTop_toBottomOf="#id/guideline1"
app:layout_constraintBottom_toTopOf="#id/guideline2"
app:layout_constraintVertical_bias="0.98"
android:text="확인"
android:textColor="#FFF"
android:textSize="20dp"
android:background="#drawable/coner_search_bar"
android:stateListAnimator="#null"
/>
<HorizontalScrollView
android:id="#+id/scrollView"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:scrollbars="none"
app:layout_constraintBottom_toTopOf="#+id/to_go_check"
app:layout_constraintEnd_toStartOf="#id/guideline4"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#id/guideline3"
>
<LinearLayout
android:id="#+id/linear_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/njklsfd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="전공검색" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="교양검색" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="교수검색" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="정렬" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="학점:3" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:stateListAnimator="#null"
android:text="학점:2" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/search_subject_bar"
android:text="학점:1"
/>
</LinearLayout>
</HorizontalScrollView>
<ListView
android:id="#+id/userList3"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/guideline8"
app:layout_constraintEnd_toStartOf="#+id/guideline4"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#id/guideline3"
app:layout_constraintTop_toTopOf="#+id/guideline6"
app:layout_constraintVertical_bias="0.0" />
<LinearLayout
android:orientation="vertical"
android:id="#+id/parent_linear_layout"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="7dp"
android:layout_marginBottom="7dp"
app:layout_constraintBottom_toTopOf="#id/scrollView"
app:layout_constraintEnd_toStartOf="#+id/guideline4"
app:layout_constraintStart_toEndOf="#id/guideline3"
app:layout_constraintTop_toBottomOf="#id/guideline8" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try this:
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val rowView: View = inflater.inflate(R.layout.row_child_view, null, false)
Mainview.removeView(rowView)
I have a progressbar in my layout in Android and i want to change its visibility inside the viewmodel. But application only gets the first state of progressbar. Whenever i try to change it nothing happen. Here is my layout file ;
<?xml version="1.0" encoding="utf-8"?>
<layout
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"
>
<data>
<import type="android.view.View"></import>
<variable
name="viewmodel"
type="com.tolgahantutar.bexworkfloww.ui.auth.AuthViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:clipChildren="false"
android:clipToPadding="false"
android:orientation="vertical"
android:padding="24dp"
android:paddingTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:layout_width="154dp"
android:layout_height="154dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="48dp"
android:src="#drawable/bexfalogo"
android:contentDescription="#string/bexlogo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="132dp"
android:textAllCaps="true"
android:textSize="16dp" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:hint="#string/hint_username">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/edit_text_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#={viewmodel.userName}"
>
</com.google.android.material.textfield.TextInputEditText>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/password_text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:hint="#string/hint_password"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/edit_text_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:text="#={viewmodel.password}"
/>
</com.google.android.material.textfield.TextInputLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:id="#+id/button_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="#string/button_login"
android:onClick="#{viewmodel::onClickUserLogin}"
/>
<com.google.android.material.button.MaterialButton
android:id="#+id/button_cancel"
style="#style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
android:layout_toStartOf="#id/button_login"
android:layout_toLeftOf="#id/button_login"
android:text="#string/button_cancel" />
</RelativeLayout>
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="#{viewmodel.isLoading ? View.VISIBLE : View.GONE}" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
and my viewmodel looks like this
package com.tolgahantutar.bexworkfloww.ui.auth
import android.content.Intent
import android.view.View
import android.widget.Toast
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.ObservableBoolean
import androidx.databinding.library.baseAdapters.BR
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tolgahantutar.bexworkfloww.data.network.repositories.AuthorizeSessionRepository
import com.tolgahantutar.bexworkfloww.ui.home.HomeActivity
import com.tolgahantutar.bexworkfloww.util.ApiException
import com.tolgahantutar.bexworkfloww.util.NoInternetException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.internal.notify
class AuthViewModel (
private val repository: AuthorizeSessionRepository
):ViewModel() {
var userName: String?=null
var password: String?=null
val isLoading = MutableLiveData<Boolean>(true)
fun onClickUserLogin(view: View){
isLoading.value = false
val sessionID = 0
val authorityID = 0
val loginType = "System"
viewModelScope.launch {
if(!(userName==null||password==null)){
try{
val authResponse = userLogin(sessionID,authorityID,userName!!,password!!,loginType)
if(authResponse.Result){
isLoading.value=false
Toast.makeText(view.context, "Login Successfull", Toast.LENGTH_LONG).show()
val intent = Intent(view.context,HomeActivity::class.java)
view.context.startActivity(intent)
}else{
//isLoading.value=false
Toast.makeText(view.context, "Login Failed!!", Toast.LENGTH_LONG).show()
}
}catch (e: ApiException){
e.printStackTrace()
}catch (e: NoInternetException){
e.printStackTrace()
}}
else{
Toast.makeText(view.context, "Kullanıcı adı ve şifre boş bırakılamaz!!", Toast.LENGTH_SHORT).show()
}
}
}
suspend fun userLogin(
SessionID : Int,
AuthorityID: Int,
UserName: String,
Password : String,
LoginType: String
)= withContext(Dispatchers.IO){repository.userLogin(SessionID, AuthorityID, UserName, Password, LoginType)}
}
As i mentioned it is just get the first state but when i click the button nothing changes..
I am using ConstraintLayout as a parent and put recyclerview in it to populate the list. Suppose I have to give item count 5 to populate the list and run the code then the list is showing perfectly but the last item of the recyclerview is showing half and not fully visible, and scroll stops at there. I found a solution for this is if am giving height match_parent to the recyclerview then it works fine but then all other view is hidden behind the recyclerview.
If I use another parent view like LinearLayout or RelativeLayout, then recyclerview with height wrap_content works fine and all the list item are fully visible.
I have tried by 2 ways that work for me but I found that wrong programming practice
I give height match_parent to recyclerview and give top_margin to the recylerview so all the other UI item show.
I give padding_bottom to the recyclerview until all the list item position visible
My XML file "activity_per_day_sale.xml" is below.
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/btn_back"
android:padding="5dp"
android:onClick="OnClickPerDaySale"
android:background="?attr/selectableItemBackground"
android:src="#drawable/icon_back_white"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Signup"
android:layout_centerInParent="true"
android:id="#+id/home_title_text"
android:textColor="#color/black"
android:visibility="gone"
android:fontFamily="#font/seguisb"
android:textSize="18sp"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SKIP"
android:padding="10dp"
android:layout_centerVertical="true"
android:visibility="gone"
android:id="#+id/skip"
android:textColor="#color/black"
android:fontFamily="#font/seguisb"
android:textSize="18sp"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:layout_marginTop="10dp"
android:text="Per Day Sale Details"
android:textColor="#color/yellow_app_logo_color"
android:fontFamily="#font/segoeuib"
app:layout_constraintTop_toBottomOf="#+id/toolbar"
app:layout_constraintStart_toStartOf="parent"
android:id="#+id/TV_signupScreenText"
android:layout_marginLeft="45dp"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rv_perday_sale"
android:layout_marginTop="10dp"
android:layout_marginHorizontal="10dp"
app:layout_constraintTop_toBottomOf="#+id/TV_signupScreenText"/>
</android.support.constraint.ConstraintLayout>
Activity class is "PerDaySaleActivity.kt"
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.View
import com.nq.NQManager.R
import com.nq.NQManager.utils.BaseActivity
import kotlinx.android.synthetic.main.activity_per_day_sale.*
class PerDaySaleActivity:BaseActivity(){
var adapterPerdaySale : AdapterPerdaySale? = null
companion object {
fun start(context: Context) {
val starter = Intent(context, PerDaySaleActivity::class.java)
context.startActivity(starter)
}
}
override fun getID(): Int {
return R.layout.activity_per_day_sale
}
override fun iniView(savedInstanceState: Bundle?) {
initViews()
}
fun OnClickPerDaySale(v: View){
when(v){
btn_back->{
finish()
}
}
}
fun initViews() {
adapterPerdaySale = AdapterPerdaySale( this)
rv_perday_sale.layoutManager = StaggeredGridLayoutManager(1, 1)
rv_perday_sale.adapter = adapterPerdaySale
}
private fun setUpRecyclerView() {
runOnUiThread { adapterPerdaySale!!.notifyDataSetChanged() }
}
My Adapter class "AdapterPerdaySale.kt"
mport android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.nq.NQManager.R
import kotlinx.android.synthetic.main.adapter_perday_sale.view.*
class AdapterPerdaySale(context: Context):
RecyclerView.Adapter<AdapterPerdaySale.MyViewHOlder>() {
private var ctx:Context?=context
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): MyViewHOlder {
return MyViewHOlder(LayoutInflater.from(ctx).inflate(R.layout.adapter_perday_sale, p0, false))
}
override fun getItemCount(): Int {
return 5
}
override fun onBindViewHolder(holder: MyViewHOlder, position: Int) {
if (position==1){
holder.tv_date.text="26 June, 2019"
}else if(position==2){
holder.tv_date.text="27 June, 2019"
}
}
inner class MyViewHOlder(view: View) : RecyclerView.ViewHolder(view) {
val tv_date=view.tv_date
}
}
My Adapter xml file "adapter_perday_sale.xml"
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingVertical="5dp"
android:background="#color/black">
<TextView
android:id="#+id/tv_date"
android:layout_below="#+id/txt_today"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:fontFamily="#font/segoeuib"
android:text="25 June, 2019"
android:textSize="23sp"
android:layout_marginEnd="8dp" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginRight="8dp" android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp" android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearLayout1"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#+id/tv_date">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:layout_marginTop="5dp"
android:text="Orders"
android:layout_centerHorizontal="true"
android:textColor="#color/white"
android:fontFamily="#font/segoeuib"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50sp"
android:layout_marginTop="0dp"
android:text="50"
android:layout_centerHorizontal="true"
android:textColor="#color/order_history_txt_color"
android:fontFamily="#font/segoeui"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:layout_marginTop="5dp"
android:text="Revenue"
android:layout_centerHorizontal="true"
android:textColor="#color/white"
android:fontFamily="#font/segoeuib"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50sp"
android:layout_marginTop="0dp"
android:text="£550"
android:layout_centerHorizontal="true"
android:textColor="#color/order_history_txt_color"
android:fontFamily="#font/segoeui"/>
</LinearLayout>
</LinearLayout>
<View android:layout_width="match_parent"
android:layout_height="1.5dp"
android:background="#color/gray"
android:id="#+id/view_1"
app:layout_constraintTop_toBottomOf="#+id/linearLayout1"
android:layout_marginLeft="8dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp"/>
</android.support.constraint.ConstraintLayout>
Add this app:layout_constraintBottom_toBottomOf="parent" property to your recyclerview
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<ImageView
android:id="#+id/btn_back"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="?attr/selectableItemBackground"
android:onClick="OnClickPerDaySale"
android:padding="5dp"
android:src="#drawable/ic_background" />
<TextView
android:id="#+id/home_title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Signup"
android:textColor="#000"
android:textSize="18sp"
android:visibility="gone" />
<TextView
android:id="#+id/skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:padding="10dp"
android:text="SKIP"
android:textColor="#000"
android:textSize="18sp"
android:visibility="gone" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
<TextView
android:id="#+id/TV_signupScreenText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="45dp"
android:layout_marginTop="10dp"
android:text="Per Day Sale Details"
android:textColor="#AD4E4E"
android:textSize="25sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv_perday_sale"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/TV_signupScreenText" />
</androidx.constraintlayout.widget.ConstraintLayout>