How to access an element in a fragment from another activity - android-fragments

I have a fragment, and this fragment has a button (in fragment_call.xml) and is called by Simple Call Activity.
class SimpleCallActivity : CallFragment.OnCallEvents {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DataBindingUtil.setContentView<ActivitySimpleCallBinding>(this, R.layout.activity_simple_call).also {
binding = it
}
Activity_simple_call
<FrameLayout
android:id="#+id/call_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment_call
<android.support.design.widget.FloatingActionButton
android:id="#+id/button_call_disconnect"/>
CallFragment class
class CallFragment : Fragment() {
interface OnCallEvents {
fun onCallHangUp()
fun onToggleMic(): Boolean
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
DataBindingUtil.inflate<FragmentCallBinding>(inflater, R.layout.fragment_call, container, false).also {
...
binding.buttonCallDisconnect.setOnClickListener({
callEvents.onCallHangUp()
})
}
How can I access this button element from another class? It says null when I access it directly with
import kotlinx.android.synthetic.main.fragment_call.*
button_call_disconnect.callOnClick();

Related

Recycler View items Not showing from firebase realtime database in kotlin

I am trying to show this datas to my recycler view but they are not showed in the recycler view.
My Codes are below
fragment_group_notice.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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/GroupNoticeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".groupTab.groupNotices.GroupNoticesFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/groupNoticeListRecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">
</androidx.recyclerview.widget.RecyclerView>
</FrameLayout>
card_group_notice.xml
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#color/primary_green"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/NoticeNameCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notice Name"
android:textColor="#color/pure_white"
android:textSize="25sp" />
</LinearLayout>
</layout>
GroupNoticesFragment
class GroupNoticesFragment : Fragment() {
private var _binding: FragmentGroupNoticesBinding? = null
private val binding get() = _binding!!
private lateinit var recycler: RecyclerView
private var adapter: NoticeAdapter?= null
private lateinit var viewModel: NoticeViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
container?.removeAllViews()
_binding = FragmentGroupNoticesBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler = binding.groupNoticeListRecycler
recycler.layoutManager = LinearLayoutManager(context)
recycler.setHasFixedSize(true)
adapter = NoticeAdapter()
recycler.adapter = adapter
viewModel = ViewModelProvider(this)[NoticeViewModel::class.java]
viewModel.allNotices.observe(viewLifecycleOwner) {
adapter!!.updateNoticeList(it)
}
}
}
NoticeAdapter.kt
class NoticeAdapter : RecyclerView.Adapter<NoticeAdapter.NoticeViewHolder>() {
private val notices = ArrayList<GroupNoticeData>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoticeViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(
R.layout.card_group_notices,
parent, false
)
return NoticeViewHolder(itemView)
}
override fun onBindViewHolder(holder: NoticeViewHolder, position: Int) {
val currentNotice = notices[position]
holder.noticeName.text = currentNotice.taskName
}
override fun getItemCount(): Int {
return notices.size
}
fun updateNoticeList(notice: List<GroupNoticeData>) {
this.notices.clear()
this.notices.addAll(notice)
notifyDataSetChanged()
}
class NoticeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val noticeName: TextView = itemView.findViewById(R.id.NoticeNameCard)
}
}
GroupNoticeData
data class GroupNoticeData(
val userId: String,
val taskName: String,
val taskDescription: String,
val taskDate: String,
val path: String?,
val groupId: String
) {
fun toMap(): Map<String, Any?> {
return mapOf(
"userId" to userId,
"taskName" to taskName,
"taskDescription" to taskDescription,
"taskDate" to taskDate,
"path" to path,
"groupId" to groupId
)
}
}
NoticeViewModel
class NoticeViewModel : ViewModel() {
private val repository : NoticeRepo = NoticeRepo().getInstance()
private val _allNotices = MutableLiveData<List<GroupNoticeData>>()
val allNotices : LiveData<List<GroupNoticeData>> = _allNotices
init {
repository.loadNotices(_allNotices)
}
}
NoticeRepo
class NoticeRepo{
val auth = Firebase.auth
val user = auth.currentUser!!.uid
private val noticeReference : DatabaseReference = FirebaseDatabase.getInstance().getReference("groupNotice").child(user)
#Volatile private var INSTANCE : NoticeRepo?= null
fun getInstance(): NoticeRepo {
return INSTANCE ?: synchronized(this) {
val instance = NoticeRepo()
INSTANCE = instance
instance
}
}
fun loadNotices(allNoticeList: MutableLiveData<List<GroupNoticeData>>) {
noticeReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
try {
val noticeList : List<GroupNoticeData> = snapshot.children.map { dataSnapshot ->
dataSnapshot.getValue(GroupNoticeData::class.java)!!
}
allNoticeList.postValue(noticeList)
}catch (_: Exception){
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
I tried to change the reference in repo class aslo checked the items height width issue but couldn't come to any solution
There isn't any error but the code is supposed to load data from the rtdb reference but it isn't showing anything. The recycler view was supposed to fill up using the card_group_notice.xml where the information were supposed to come from the database child as you can see groupNotice/(userId)

How to retrieve image from fire base

I have a question that how to get the image from a real-time database. In my code, I want to get the data from the database ( one is text form, one is image form ) and insert them in the recycler view. I get the reference from the internet and find these codes to realise my function. However, after inserting it, it still cannot be shown because my image is in string form but I cannot find any solution to solve it. Can somebody help me? Maybe the main problem is I do not know how to insert the URL of the real-time database.
Problem faced :
java.lang.ClassCastException: com.google.android.material.imageview.ShapeableImageView cannot be cast to android.widget.TextView
at com.example.assignment_mad.NotificationAdapter$MyViewHolder.<init>(Notificatiion_Adapter.kt:118)
at com.example.assignment_mad.NotificationAdapter.onCreateViewHolder(Notificatiion_Adapter.kt:85)
at com.example.assignment_mad.NotificationAdapter.onCreateViewHolder(Notificatiion_Adapter.kt:63)
Main code :
package com.example.assignment_mad
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.assignment_mad.databinding.ActivityMainBinding
import com.example.assignment_mad.databinding.FragmentNotificationBinding
import com.example.assignment_mad.databinding.FragmentSearchPageBinding
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.tabs.TabLayout
import com.google.firebase.database.*
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_notification_.*
class Notification_Fragment : Fragment( ) {
val database=Firebase.database
val myRef=database.getReference("message")
private var _binding:FragmentNotificationBinding?=null
private val binding get()=_binding!!
private lateinit var dbref: DatabaseReference
private lateinit var newRecyclerView: RecyclerView
private lateinit var newArrayList: ArrayList<Company>
private lateinit var tempArrayList: ArrayList<Company>
lateinit var imageId:Array<Int>
lateinit var heading:Array<String>
lateinit var news:Array<String>
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<NotificationAdapter.MyViewHolder>? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
var views =inflater.inflate(R.layout.fragment_notification_, container, false)
newRecyclerView=views.findViewById(R.id.recyclerView)
newArrayList= arrayListOf<Company>()
// Inflate the layout for this fragment
return views
}
override fun onViewCreated(itemView: View, savedInstanceState: Bundle?) {
super.onViewCreated(itemView, savedInstanceState)
adapter=NotificationAdapter(newArrayList)
getUserdata()
}
private fun getUserdata() {
dbref=FirebaseDatabase.getInstance("https://recyclerview-e3e96-default-rtdb.asia-southeast1.firebasedatabase.app/").getReference("Notification")
dbref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (companySnapshot in snapshot.children){
val company=companySnapshot.getValue(Company::class.java)
newArrayList.add(company!!)
}
adapter?.notifyDataSetChanged()
}
}
override fun onCancelled(error: DatabaseError) {
Log.w(TAG, "Failed to read value.", error.toException())
}
})
newRecyclerView.layoutManager=LinearLayoutManager(activity)
newRecyclerView.setHasFixedSize(true)
newRecyclerView.adapter=adapter
}
}
The recyclerview adapter :
package com.example.assignment_mad
import android.provider.Settings.System.getString
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.imageview.ShapeableImageView
import kotlinx.android.synthetic.main.dropdown_item.view.*
class NotificationAdapter(private val companysList:ArrayList<Company>):RecyclerView.Adapter<NotificationAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView=LayoutInflater.from(parent.context).inflate(R.layout.list_item,parent,false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem=companysList[position]
holder.titleImage.text=currentItem.titleImage
//holder.titleImage.setImageResource(currentItem.titleImage)
holder.tvHeading.text=currentItem.heading
}
override fun getItemCount(): Int {
return companysList.size
}
class MyViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
//original
//val titleImage:ShapeableImageView=itemView.findViewById(R.id.title_image)
val titleImage: TextView =itemView.findViewById(R.id.title_image)
val tvHeading: TextView =itemView.findViewById(R.id.tvHeading)
}
}
the xml file and list_item xml :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context=".Notification_Fragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerView"
tools:listitem="#layout/list_item"/>
<!-- TODO: Update blank fragment layout -->
</FrameLayout>
------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="8dp">
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/title_image"
android:scaleType="centerCrop"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:shapeAppearanceOverlay="#style/RoundCorner"
android:src="#drawable/company_logo_1"/>
<TextView
android:id="#+id/tvHeading"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Candidate Biden Called Saudi Arable a Pareft eaft."
android:textSize="16dp"
android:textStyle="bold"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/title_image"
app:layout_constraintTop_toTopOf="parent"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_margin="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title_image"
android:background="#color/underline"/>
</androidx.constraintlayout.widget.ConstraintLayout>
The realtime firebase resource :
enter image description here
The specific error you are seeing is because you define a ShapeableImageView in xml with id title_image, but you are casting it to a TextView in this line:
val titleImage: TextView =itemView.findViewById(R.id.title_image)
Once you resolve this, consider using an image loading library like Glide to load the image URL you get from the Realtime Database into your ImageView.

MVVM Cross Exception: Cannot Create Fragment. Use the MvxAppCompatViewPresenter when using Android Support Fragments

Im having trouble getting my fragments to run, and im getting the following exception. MVVM Cross Exception: Cannot Create Fragment. Use the MvxAppCompatViewPresenter when using Android Support Fragments.
Here is the MainViewModel, where it should navigate to the first fragment/ViewModel (ActionViewModel).
public class MainViewModel : BaseViewModel
{
public IMvxCommand<string> BottomNavigationItemSelectedCommand { get; private set; }
List<TabViewModel> _tabs;
public List<TabViewModel> Tabs
{
get => _tabs;
set => SetProperty(ref _tabs, value);
}
private readonly IMvxNavigationService _navigationService;
public MainViewModel(IMvxNavigationService navigationService)
{
_navigationService = navigationService;
BottomNavigationItemSelectedCommand = new MvxCommand<string>(BottomNavigationItemSelected);
var tabs = new List<TabViewModel>
{
Mvx.IoCProvider.IoCConstruct<ActionViewModel>(),
Mvx.IoCProvider.IoCConstruct<TaskViewModel>(),
Mvx.IoCProvider.IoCConstruct<KpiViewModel>(),
Mvx.IoCProvider.IoCConstruct<EisViewModel>(),
Mvx.IoCProvider.IoCConstruct<MenuViewModel>()
};
Tabs = tabs;
}
public override Task Initialize()
{
return base.Initialize();
}
// Android-only, not used on iOS
private void BottomNavigationItemSelected(string tabId)
{
if (tabId == null)
{
return;
}
foreach (var item in Tabs)
{
if (tabId == item.TabId)
{
_navigationService.Navigate(item);
break;
}
}
}
}
}
And this is the ActionFragment:
[MvxFragmentPresentation(typeof(MainViewModel), Resource.Id.fragment_content, true)]
[Register(nameof(ActionFragment))]
public class ActionFragment : BaseFragment<ActionViewModel>
{
//public static ActionFragment NewInstance() => new ActionFragment();
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.activity_actions, container, false);
return view;
}
}
This is the main activity layout:
<androidx.coordinatorlayout.widget.CoordinatorLayout
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"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/parentView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/colorBackground">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.ContentFrameLayout
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_nav_menu"
local:MvxBind="BottomNavigationSelectedBindingKey BottomNavigationItemSelectedCommand"/>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Could someone please let me know what I should do to solve this problem? I am new to this!
I found out that my problem was that I had to change the MainApplication.cs and Setup.cs classes.
from :
public class Setup : MvxAndroidSetup
to
public class Setup : MvxAppCompatSetup<App>
and from :
public class MainApplication : MvxAndroidApplication<MvxAndroidSetup<App>, App>
to
public class MainApplication : MvxAppCompatApplication<Setup, App>

Android how to call Navigation Drawer from fragment

In my fragment I have material search bar with navigation button(humbugger).
How can I call Navigation Drawer which is in main activity with that humbugger button in my fragment
Do not get how to handle it inside DictionaryFragment
MainActivity:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
drawer,
R.string.nav_open_drawer,
R.string.nav_close_drawer){
};
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
DictionaryFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
materialSearchBar = (MaterialSearchBar) RootView.findViewById(R.id.search_bar);
...
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onButtonClicked(int buttonCode) {
//***HOW TO HANDLE IT HERE?***
//switch (buttonCode) {
// case MaterialSearchBar.BUTTON_NAVIGATION:
// drawer.openDrawer(Gravity.START);
// break;}
}
});
//return RootView;
}
layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/searchBarDividerColor"
tools:context="com.hfad.catchat.DictionaryFragment">
<com.mancj.materialsearchbar.MaterialSearchBar
android:id="#+id/search_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:mt_hint="Search"
app:mt_navIconEnabled="true"
app:mt_speechMode="false" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
</android.support.v7.widget.RecyclerView>
</LinearLayout>
This is what you can try where you want to toggle navigation drawer in your fragment, this way you will have to write a method in activity to do whatever you want to do from your fragment, be sure it is a public method:
((MainActivity)getContext()).toggleDrawer();
in your MainActivity:
public void toggleDrawer(){
//do your stuff
}
Other way is callback aka interface (the preferred one), pass that as a parameter in fragment's constructor and consume that where you want to change drawer's state. Like inside your activity:
Callback callback = new Callback(){
#Override
public void onDrawerStateChanged(){
//do your stuff
}};
new DictionaryFragment(callback);
And inside your fragment you will have to write a constructor to accept that callback and save in a local variable :
public DictionaryFragment() {
}
#SuppressLint("ValidFragment")
public DictionaryFragment(Callback callback) {
this.callback = callback;
}
And use it like :
callback.onDrawerStateChanged();
You can also pass parameters to MainActivity both ways.

Activity loads independently but not in Fragment

I am new to Mobile development. I have started my Mobile app with Kotlin. I have an Activity (ProductsActivity.kt) which loads RecyclerView with ImageView and TextView getting data from MySQL, which is working independently. Now, I want this Activity to load in Fragment, I tried to load using Inflater, but it doesn't show any data. Following is my code, please help how can I achieve the same. Thanks in advance.
MainActivity.kt
package com.example.administrator.zmaart
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
class MainActivity : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
drawer.addDrawerListener(toggle)
toggle.syncState()
val navigationView = findViewById<View>(R.id.nav_view) as
NavigationView
navigationView.setNavigationItemSelectedListener(this)
displaySelectedScreen(R.id.nav_home)
}
private var backButtonCount: Int = 0
override fun onBackPressed() {
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
if (backButtonCount >= 1) {
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_HOME)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
} else {
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show()
backButtonCount++
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
return if (id == R.id.action_settings) {
true
} else super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
displaySelectedScreen(item.itemId)
return true
}
private fun displaySelectedScreen(itemId: Int) {
//creating fragment object
var fragment: Fragment? = null
//initializing the fragment object which is selected
when (itemId) {
R.id.nav_home -> fragment = home()
R.id.nav_orders -> fragment = orders()
R.id.nav_wishlist -> {
val intent = Intent(this#MainActivity,
ProductsActivity::class.java)
this#MainActivity.startActivity(intent)
}
R.id.nav_logout -> {
val sharedPreferences = getSharedPreferences("SharedPref", 0)
val editor = sharedPreferences.edit()
editor.clear()
editor.apply()
val intent = Intent(this#MainActivity, Login_Page::class.java)
this#MainActivity.startActivity(intent)
}
}
//replacing the fragment
if (fragment != null) {
val ft = supportFragmentManager.beginTransaction()
ft.replace(R.id.content_frame, fragment)
ft.commit()
}
val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
}
}
activity_products.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"
tools:context=".ProductsActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="-51dp" />
</RelativeLayout>
ProductsActivity.kt
package com.example.administrator.zmaart
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
import org.json.JSONException
import java.util.*
class ProductsActivity : AppCompatActivity() {
private lateinit var productList: MutableList<Product>
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_products)
recyclerView = findViewById(R.id.recylcerView1)
recyclerView.setHasFixedSize(false)
recyclerView.layoutManager = LinearLayoutManager(this)
productList = ArrayList()
loadProducts()
}
private fun loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
val stringRequest = StringRequest(Request.Method.GET, URL_PRODUCTS,
Response.Listener { response ->
try {
//converting the string to json array object
val array = JSONArray(response)
//traversing through all the object
for (i in 0 until array.length()) {
//getting product object from json array
val product = array.getJSONObject(i)
//adding the product to product list
productList.add(Product(
product.getString("prod_id_sha"),
product.getString("prod_title"),
product.getDouble("prod_price"),
product.getDouble("prod_price2"),
product.getString("img_thumbnail")
))
}
//creating adapter object and setting it to recyclerview
val adapter = ProductsAdapter(this#ProductsActivity, productList)
recyclerView.adapter = adapter
} catch (e: JSONException) {
e.printStackTrace()
}
},
Response.ErrorListener { })
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest)
}
companion object {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
private const val URL_PRODUCTS = "localhost/app/load_prod.php"
}
}
home.kt (where I want to load activity_products.xml)
package com.example.administrator.zmaart
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class home : Fragment() {
private lateinit var productList: MutableList<Product>
private lateinit var recyclerView: RecyclerView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.activity_products, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity!!.title = "Home"
}
}
Please let me know if any other code(s) to be included to help you to help me.

Resources