how to connect to different apis on different button click - android

I have placed buttons on these 6 items now all I need is when a user clicks on a button it has to connect to a api fetch and display content ,similarly clicking on all other buttons should connect to respective api s.Now creating a new activity and new adapter for each is causing redundant code how to implement this properly please help me
home fragment
class Homefragment : Fragment() {
lateinit var buttondept:Button
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view= inflater.inflate(R.layout.fragment_homefragment, container, false)
buttondept=view.findViewById(R.id.btnDept)
buttondept.setOnClickListener {
val intent=Intent(context,descactivity::class.java)
intent.putExtra("option","department")
startActivity(intent)
}
return view
}
}
desc activity
class descactivity : AppCompatActivity() {
lateinit var recyclerDashBoard: RecyclerView
lateinit var layoutmanager: RecyclerView.LayoutManager
lateinit var recyclerAdapter:Horizontal_RecyclerView
lateinit var progressLayout: RelativeLayout
lateinit var progressBar: ProgressBar
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_descactivity)
val bookInfoList = arrayListOf<Book>()
recyclerDashBoard = findViewById(R.id.recyclerDashboard)
progressBar = findViewById(R.id.progressbar)
progressLayout = findViewById(R.id.progresslayout)
progressLayout.visibility = View.VISIBLE
val intent=getIntent()
val selectionOption= intent.getStringExtra("option")
val queue = Volley.newRequestQueue(this as Context)
val url = "http://13.235.250.119/v1/book/fetch_books/"
if (ConnectionManager().checkConnectivity(this as Context)) {
val jsonObjectRequest =
object : JsonObjectRequest(Method.GET, url, null, Response.Listener {
try {
progressLayout.visibility = View.GONE
val success = it.getBoolean("success")
if (success) {
val data = it.getJSONArray("data")
for (i in 0 until data.length()) {
val bookJSONObject = data.getJSONObject(i)
val bookobject = Book(
bookJSONObject.getString("book_id"),
bookJSONObject.getString("name"),
bookJSONObject.getString("author"),
bookJSONObject.getString("rating"),
bookJSONObject.getString("price"),
bookJSONObject.getString("image")
)
bookInfoList.add(bookobject)
layoutmanager = LinearLayoutManager(this)
recyclerAdapter =
Horizontal_RecyclerView(this as Context, bookInfoList)
recyclerDashBoard.adapter = recyclerAdapter
recyclerDashBoard.layoutManager = layoutmanager
}
} else {
Toast.makeText(
this as Context,
"some error occurred!!",
Toast.LENGTH_SHORT
).show()
}
} catch (e: JSONException) {
Toast.makeText(
this as Context,
"some unknown error occured!!",
Toast.LENGTH_SHORT
).show()
}
}, Response.ErrorListener {
Toast.makeText(
this as Context,
"volley error occured!!",
Toast.LENGTH_SHORT
).show()
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["content-type"] = "application/json"
headers["token"] = "a07daa7f3efb3b"
return headers
}
}
queue.add(jsonObjectRequest)
}
}
}

Related

firebase realtime database: messenger

I am building a chatting app using firebase realtime database.
I am storing the messages in both accounts simultaneously.
This is my fragment to send message:
class DmFragment : Fragment() {
lateinit var binding: FragmentDMBinding
lateinit var user: User
val list = ArrayList<Message>()
lateinit var auth: FirebaseAuth
lateinit var firebaseDatabase: FirebaseDatabase
lateinit var reference: DatabaseReference
lateinit var usersDMAdapter: UsersDMAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
user = it.getSerializable("user") as User
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDMBinding.inflate(LayoutInflater.from(requireContext()), container, false)
auth = FirebaseAuth.getInstance()
val currentUser = auth.currentUser!!
firebaseDatabase = FirebaseDatabase.getInstance()
reference = firebaseDatabase.getReference("users")
binding.apply {
sendBtn.setOnClickListener {
val smsText = message.text.toString()
val simpleDateFormat = SimpleDateFormat("dd.MM.yyyy HH.ss")
val date = simpleDateFormat.format(Date())
val message1 = Message(smsText, date, currentUser.uid, user.uid)
val key = reference.push().key
reference.child("${currentUser.uid}/messages/${user.uid!!}/$key")
.setValue(message1)
reference.child("${user.uid}/messages/${currentUser.uid}/$key")
.setValue(message1)
message.text.clear()
}
reference.child("${currentUser.uid}/messages/${user.uid}")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val children = snapshot.children
for (child in children) {
val value = child.getValue(Message::class.java)
if (value != null) {
list.add(value)
}
}
usersDMAdapter = UsersDMAdapter(list, currentUser.uid)
messageRv.adapter = usersDMAdapter
}
override fun onCancelled(error: DatabaseError) {
}
})
back.setOnClickListener {
findNavController().popBackStack()
}
userName.text = user.displayName
Picasso.get().load(user.photoUrl).into(userImage)
}
return binding.root
}
}
This is the adapter file that i used in the DMFragment:
class UsersDMAdapter(var list: List<Message>, var uid: String) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
inner class FromVh(val fromBinding: ItemFromBinding) :
RecyclerView.ViewHolder(fromBinding.root) {
fun onBind(message: Message) {
fromBinding.apply {
messageTv.text = message.message
messageDateTv.text = message.date
}
}
}
inner class ToVh(val toBinding: ItemToBinding) :
RecyclerView.ViewHolder(toBinding.root) {
fun onBind(message: Message) {
toBinding.apply {
messageTv.text = message.message
messageDateTv.text = message.date
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == 1) {
return FromVh(
ItemFromBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
} else {
return ToVh(
ItemToBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (getItemViewType(position)==1){
val fromVh = holder as FromVh
fromVh.onBind(list[position])
}else{
val toVh = holder as ToVh
toVh.onBind(list[position])
}
}
override fun getItemViewType(position: Int): Int {
return if (list[position].fromUid == uid) {
1
} else{
2
}
}
override fun getItemCount(): Int = list.size
}
This is my fragment that shows all users excluding myself:
class UserRecyclerFragment : Fragment() {
lateinit var binding: FragmentUserRecyclerBinding
lateinit var userRvAdapter: UserRvAdapter
var list = ArrayList<User>()
lateinit var auth: FirebaseAuth
lateinit var firebaseDatabase: FirebaseDatabase
lateinit var reference: DatabaseReference
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentUserRecyclerBinding.inflate(
LayoutInflater.from(requireContext()),
container,
false
)
auth = FirebaseAuth.getInstance()
val currentUser = auth.currentUser!!
firebaseDatabase = FirebaseDatabase.getInstance()
reference = firebaseDatabase.getReference("users")
val email = currentUser.email
val displayName = currentUser.displayName
val photo = currentUser.photoUrl
val phoneNumber = currentUser.phoneNumber
val uid = currentUser.uid
val user = User(
email,
displayName,
photo.toString(),
phoneNumber,
uid
)
reference.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
list.clear()
val filterList = arrayListOf<User>()
val children = snapshot.children
for (child in children) {
val value = child.getValue(User::class.java)
if (value != null && uid != value.uid) {
list.add(value)
}
if (value != null && value.uid == uid) {
filterList.add(value)
}
}
if (filterList.isEmpty()) {
reference.child(uid).setValue(user)
}
userRvAdapter = UserRvAdapter(list, object : UserRvAdapter.OnItemClickListener {
override fun onItemCick(user: User) {
val bundle = Bundle()
bundle.putSerializable("user", user)
findNavController().navigate(R.id.dmFragment, bundle)
}
})
binding.rv.adapter = userRvAdapter
}
override fun onCancelled(error: DatabaseError) {
}
})
return binding.root
}
}
Whenever i chat (send/receive) in DM, it is showing messages. But when I go back, messages that added in my user account is being deleted automatically. If i come back again, it is not showing the messages that have been saved in other person's account either. And i do not know what to do. Can anyone help?

Blank fragment is displayed

I am creating a food ordering app . I am fetching the list of restaurants using volley .
Error:
The restaurant list does not displayed and in the logcat window the following displayed:
E/RecyclerView: No adapter attached; skipping layout
What I have tried to resolve:
used postman to verify volley response,the response is as expected
made sure if the variables were received in the right order
made sure that the array was received in the right format.
I attach the code of the HomeFragment and the adapter file
HomeFragment.class
class HomeFragment : Fragment() {
lateinit var recyclerRestaurant: RecyclerView
lateinit var progressLayout: RelativeLayout
lateinit var progressBar: ProgressBar
lateinit var layoutManager: RecyclerView.LayoutManager
lateinit var recyclerAdapter: RestaurantRecyclerAdapter
var restaurantList = arrayListOf<Restaurant>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
setHasOptionsMenu(true)
recyclerRestaurant = view.findViewById(R.id.recyclerRestaurant)
progressLayout = view.findViewById(R.id.progressLayout)
progressBar = view.findViewById(R.id.progressBar)
layoutManager = LinearLayoutManager(activity)
progressLayout.visibility= View.VISIBLE
val queue = Volley.newRequestQueue(activity as Context)
val url = "http://13.235.250.119/v2/restaurants/fetch_result/"
if (ConnectionManager().checkConnectivity(activity as Context)) {
val jsonObjectRequest = object : JsonObjectRequest(
Request.Method.GET,url , null,
Response.Listener<JSONObject>{
progressLayout.visibility = View.GONE
try {
val data = it.getJSONObject("data")
val success = data.getBoolean("success")
if (success) {
val data = it.getJSONObject("data").getJSONArray("data")
for(i in 0 until data.length()) {
val resObject = data.getJSONObject(i)
val restaurants = Restaurant(
resObject.getString("id").toInt(),
resObject.getString("name"),
resObject.getString("rating"),
resObject.getString("cost_per_person"),
resObject.getString("image_url")
)
restaurantList.add(restaurants)
if(activity != null) {
recyclerAdapter = RestaurantRecyclerAdapter(activity as Context, restaurantList)
val mLayoutManager=LinearLayoutManager(activity)
recyclerRestaurant.layoutManager =mLayoutManager
recyclerRestaurant.adapter = recyclerAdapter
recyclerRestaurant.setHasFixedSize(true)
}
}
}
else {
Toast.makeText(
activity as Context,
"some error has occurred",
Toast.LENGTH_SHORT
).show()
}
}catch (e: JSONException){
e.printStackTrace()
}
},
Response.ErrorListener {
if(activity != null){
Toast.makeText(activity as Context,"Volley error has occurred", Toast.LENGTH_LONG).show() }
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["Content-type"] = "application/json"
headers["token"] = "06f579db533924"
return headers
}
}
queue.add(jsonObjectRequest)
}else{
val dialog = AlertDialog.Builder(activity as Context)
dialog.setTitle("error")
dialog.setMessage("Internet connection not found")
dialog.setPositiveButton("open settings"){ text, listener->
val settingsIntent = Intent(Settings.ACTION_WIRELESS_SETTINGS)
startActivity(settingsIntent)
activity?.finish()
}
dialog.setNegativeButton("exit"){text,listener->
ActivityCompat.finishAffinity(activity as Activity)
}
dialog.create()
dialog.show()
}
return view
}
}
RestaurantRecyclerAdapter.class
class RestaurantRecyclerAdapter(val context:Context, val itemList: ArrayList<Restaurant> ):RecyclerView.Adapter<RestaurantRecyclerAdapter.RestaurantViewHolder>() {
class RestaurantViewHolder(view: View): RecyclerView.ViewHolder(view){
val txtRestaurantName :TextView= view.findViewById(R.id.txtRestaurantName)
val imgRestaurantImage :ImageView = view.findViewById(R.id.imgRestaurantImage)
val txtRating : TextView = view.findViewById(R.id.txtRating)
val txtPerPerson : TextView = view.findViewById(R.id.txtPerPerson)
val llContent : LinearLayout = view.findViewById(R.id.llContent)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RestaurantViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_single_row,parent,false)
return RestaurantViewHolder(view)
}
override fun getItemCount(): Int {
return itemList.size
}
override fun onBindViewHolder(holder: RestaurantViewHolder, position: Int) {
val restaurant = itemList[position]
holder.txtRestaurantName.text = restaurant.name
holder.txtRating.text = restaurant.rating
holder.txtPerPerson.text = restaurant.cost_per_person
Picasso.get().load(restaurant.image).error(R.drawable.ic_food).into(holder.imgRestaurantImage)

Can we retrieve firebase data into spinner?

I have added firebase database and the data also gets saved into the firebase realtime database, but it doesnot gets shown into the spinner, my spinner is showing no value.If theres some other way?
This is the code of my fragment:
class IncomeFragment: Fragment(){
//FAB
lateinit var addBankFab: FloatingActionButton
lateinit var addBankText: TextView
//Spinner
lateinit var spinner: Spinner
lateinit var dropDown: TextView
//Firebase Database
lateinit var mAuth: FirebaseAuth
lateinit var mIncomeDatabase: DatabaseReference
lateinit var mBankDatabase: DatabaseReference
lateinit var helper: FirebaseHelper
//Recycler View
lateinit var recyclerView: RecyclerView
//TextView
lateinit var incomeTotal : TextView
//Update Edit Text
lateinit var editAmount: EditText
lateinit var editType: EditText
lateinit var editNote: EditText
lateinit var editBankName:EditText
//Button for update and delete
lateinit var btnUpdate: Button
lateinit var btnDelete: Button
lateinit var btnSave : Button
lateinit var btnCancel:Button
//Data item Value
lateinit var type: String
lateinit var note: String
var amount: Int = 0
lateinit var post_key:String
lateinit var name:String
lateinit var ac:String
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val myview= inflater.inflate(R.layout.fragment_income, container, false)
mAuth= FirebaseAuth.getInstance()
val mUser = mAuth.currentUser
val uid = mUser?.uid
addBankFab=myview.findViewById(R.id.add_bank_fab)
addBankText=myview.findViewById(R.id.add_bank_text)
spinner=myview.findViewById(R.id.incomeSpinner)
mIncomeDatabase =
FirebaseDatabase.getInstance().reference.child("IncomeData").child(uid.toString())
incomeTotal=myview.findViewById(R.id.income_txt_result)
mBankDatabase= FirebaseDatabase.getInstance().reference.child("BankData").child(uid.toString())
helper = FirebaseHelper(mBankDatabase)
spinner.setAdapter(
activity?.let {
ArrayAdapter<String>(
it,
android.R.layout.simple_list_item_1,
helper.retrieve()
)
}
)
recyclerView=myview.findViewById(R.id.incomeRecyclerView)
val layoutManager = LinearLayoutManager(activity)
layoutManager.reverseLayout = true
layoutManager.stackFromEnd = true
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = layoutManager
mIncomeDatabase.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var totalvalue :Int = 0
for (ds in dataSnapshot.children) {
val data: Data = ds.getValue<Data>(Data::class.java)!!
totalvalue+=data.amount
val stTotalValue:String = valueOf(totalvalue)
incomeTotal.text = stTotalValue+".00"
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
return myview
}
private fun insertBank() {
val bankdialog = AlertDialog.Builder(activity)
val inflater = LayoutInflater.from(activity)
val view: View = inflater.inflate(R.layout.add_bank_layout, null)
bankdialog.setView(view)
val dialog = bankdialog.create()
dialog.setCancelable(false)
val BankName = view.findViewById<EditText>(R.id.account_bank)
val BankAc = view.findViewById<EditText>(R.id.account_number)
val btnSaveBank = view.findViewById<Button>(R.id.btn_save_bank)
val btnCancelBank = view.findViewById<Button>(R.id.btn_cancel_bank)
btnSaveBank.setOnClickListener {
val name = BankName.text.toString().trim()
val ac = BankAc.text.toString().trim()
if (TextUtils.isEmpty(name)) {
BankName.error = "Required Field..."
return#setOnClickListener
}
if (TextUtils.isEmpty(ac)) {
BankAc.error = "Required Field..."
return#setOnClickListener
}
val bankacno = ac.toInt()
val id: String? = mBankDatabase.push().key
val mDate: String = DateFormat.getDateInstance().format(Date())
val bankdata = EmiData(bankacno, name, id, mDate)
mBankDatabase.child(id.toString()).setValue(bankdata)
Toast.makeText(activity, "DATA ADDED", Toast.LENGTH_SHORT).show()
dialog.dismiss()
}
btnCancelBank.setOnClickListener {
dialog.dismiss()
}
dialog.show()
}
override
fun onStart() {
super.onStart()
val options = FirebaseRecyclerOptions.Builder<Data>()
.setQuery(mIncomeDatabase, Data::class.java)
.setLifecycleOwner(this)
.build()
val firebaseRecyclerAdapter: FirebaseRecyclerAdapter<Data, MyViewHolder> =
object : FirebaseRecyclerAdapter<Data, MyViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.income_recycler_data, parent, false)
)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int, model: Data) {
holder.setType(model.type)
holder.setAmount(model.amount)
holder.setDate(model.date)
holder.setNote(model.note)
holder.mView.setOnClickListener {
post_key= getRef(position).key.toString()
type=model.type
note=model.note
amount=model.amount
updateDataItem()
}
}
}
recyclerView.adapter = firebaseRecyclerAdapter
}
class MyViewHolder(itemView: View) : ViewHolder(itemView) {
val mView = itemView
fun setType(type: String) {
val mType = mView.findViewById<TextView>(R.id.type_txt_income)
mType.text = type
}
fun setNote(note: String) {
val mNote = mView.findViewById<TextView>(R.id.note_txt_income)
mNote.text = note
}
fun setDate(date: String) {
val mDate = mView.findViewById<TextView>(R.id.date_txt_income)
mDate.text = date
}
fun setAmount(amount: Int) {
val mAmount = mView.findViewById<TextView>(R.id.amount_txt_income)
val stAmount = valueOf(amount)
mAmount.text = stAmount
}
}
private fun updateDataItem() {
val mydialog = AlertDialog.Builder(activity)
val inflater = LayoutInflater.from(activity)
val myView: View = inflater.inflate(R.layout.update_data_item, null)
mydialog.setView(myView)
val dialog = mydialog.create()
val editAmount = myView.findViewById<EditText>(R.id.amount_edit)
val editType = myView.findViewById<EditText>(R.id.type_edit)
val editNote = myView.findViewById<EditText>(R.id.note_edit)
//Set data to edit text..
editType.setText(type)
editType.setSelection(type.length)
editNote.setText(note)
editNote.setSelection(note.length)
editAmount.setText(valueOf(amount))
editAmount.setSelection(valueOf(amount).length)
val btnUpdate = myView.findViewById<Button>(R.id.btn_update)
val btnDelete = myView.findViewById<Button>(R.id.btn_delete)
btnUpdate.setOnClickListener {
type = editType.text.toString().trim()
note = editNote.text.toString().trim()
var mdAmount = amount.toString()
mdAmount = editAmount.text.toString().trim { it <= ' ' }
val myAmount = mdAmount.toInt()
val mDate: String = DateFormat.getDateInstance().format(Date())
val data = Data(myAmount, type, note, post_key, mDate)
mIncomeDatabase.child(post_key).setValue(data)
dialog.dismiss()
}
btnDelete.setOnClickListener {
mIncomeDatabase.child(post_key).removeValue()
dialog.dismiss()
}
dialog.show()
}
}
This is my firebase helper:
class FirebaseHelper(val db: DatabaseReference) {
private var saved: Boolean? = null
//SAVE
fun save(bankData: BankData?): Boolean? {
saved = if (bankData == null) {
false
} else {
try {
db.child("name").push().setValue(bankData)
true
} catch (e: DatabaseException) {
e.printStackTrace()
false
}
}
return saved
}
//READ
fun retrieve(): ArrayList<String> {
val bankNames = ArrayList<String>()
db.addChildEventListener(object : ChildEventListener {
override fun onChildAdded(
dataSnapshot: DataSnapshot,
s: String?
) {
fetchData(dataSnapshot, bankNames)
}
override fun onChildChanged(
dataSnapshot: DataSnapshot,
s: String?
) {
fetchData(dataSnapshot, bankNames)
}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {}
override fun onChildMoved(
dataSnapshot: DataSnapshot,
s: String?
) {
}
override fun onCancelled(databaseError: DatabaseError) {}
})
return bankNames
}
private fun fetchData(
snapshot: DataSnapshot,
bankData: ArrayList<String>
) {
bankData.clear()
val name: BankData? = snapshot.getValue(BankData::class.java)
bankData.add(bankData.toString())
}
}
Your spinner shows no value because the data is not retrieved yet from the DB.
So what you should do is create a callback from FirebaseHelper to IncomeFragment
First, create a callback
interface FirebaseHelperCallback {
fun dataRetrievedFromDB(data: List<String>)
}
Second, create a variable, setter function and call dataRetrievedFromDB function in FirebaseHelper class
class FirebaseHelper(val db: DatabaseReference) {
private lateinit var firebaseHelperCallback: FirebaseHelperCallback
fun setFirebaseHelperCallback(firebaseHelperCallback: FirebaseHelperCallback) {
this.firebaseHelperCallback = firebaseHelperCallback
}
...
private fun fetchData(snapshot: DataSnapshot, bankData: ArrayList<String>) {
bankData.clear()
val name: BankData? = snapshot.getValue(BankData::class.java)
bankData.add(bankData.toString())
firebaseHelperCallback.dataRetrievedFromDB(bankData)
}
}
Lastly, implement the callback in IncomeFragment
class IncomeFragment: Fragment(), FirebaseHelperCallback {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
...
helper.setFirebaseHelperCallback(this)
}
...
override fun dataRetrievedFromDB(data: List<String>) {
spinner.setAdapter(
activity?.let {
ArrayAdapter<String>(
it,
android.R.layout.simple_list_item_1,
data
)
}
)
}
}

Deep link intent return unresolved reference

I am trying to get list of posts in categories with deep linking but it returns Unresolved reference
Screenshots
Documents
my code
Errors
Code
class CategoryLinkDetails : Fragment() {
private lateinit var mInterstitialAd: InterstitialAd
private lateinit var homeViewModel: HomeViewModel
private var recyclerView: RecyclerView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreate(savedInstanceState)
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.categorylink_details, container, false)
recyclerView = root.findViewById(R.id.categorylinkRecycle)
handleIntent(intent)
return root
}
// api code
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent) {
val appLinkAction = intent.action
val appLinkData: Uri? = intent.data
if (Intent.ACTION_VIEW == appLinkAction) {
appLinkData?.lastPathSegment?.also { recipeId ->
Uri.parse("content://com.my.app/categories/")
.buildUpon()
.appendPath(recipeId)
.build().also { appData ->
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(activity)
val url = "https://example.com/v1/categories/$recipeId"
// Request a string response from the provided URL.
val stringRequest = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
val jsonArray = JSONArray(response)
val list: ArrayList<MyCategoryLink> = ArrayList()
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
list.add(parseData(jsonObject))
}
// here you will have the complete list of data in your "list" variable
categoriesRecycle.layoutManager = LinearLayoutManager(activity)
Log.d("my list", list.toString())
categoriesRecycle.adapter = MyCategoryListAdapter(list)
},
Response.ErrorListener { error ->
//displaying the error in toast if occurrs
Toast.makeText(activity, error.message, Toast.LENGTH_SHORT)
.show()
})
// Add the request to the RequestQueue.
queue.add(stringRequest)
}
}
}
}
private fun parseData(jsonObject: JSONObject): MyCategoryLink {
var listingObject = MyCategoryLink(
jsonObject.getString("name"),
jsonObject.getString("slug"),
HtmlCompat.fromHtml(jsonObject.getString("body"), HtmlCompat.FROM_HTML_MODE_COMPACT),
jsonObject.getString("image")
)
return listingObject
}
}
NOTE:
The only difference between my code and documentation is that I use Fragment because I need to show a list of posts but in docs they used Activity
Any idea?
You need to handle intent data in activity class then you need to pass intent to fragment constructor
refer below code.
class TestActivity :AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handleIntent(intent)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent?) {
// now from here you can add your fragment here
var categoryDetails = CategoryDetailsFragment(intent)
var ft = supportFragmentManager.beginTransaction()
ft.add(R.id.container,categoryDetails)
}}
I hope this will help.

No Error in the Log but RecyclerView is not displaying any JSON value-No error in the code too---Volley

I am trying to display name and age from a JSON Array in a HomeFragment. I have model, data and UI package. I am not seeing any error in the code or log but I am not getting the output in my activity. I am getting the JSON output in my response log and Commented for loop is working in recyclerview but If I use the real JSON value then fragment is not displaying any values. Your help is appreciated.
Home Fragment.kt
class HomeFragment : Fragment() {
private var adapter:PersonListAdapter?=null
private var personList:ArrayList<Person>?=null
private var layoutManager: RecyclerView.LayoutManager?=null
var volleyRequest: RequestQueue?=null
val SchoolLink="https://www.abc.app/"
//JSON Output
//[{"name":"AAA","age":"20"},{"name":"BBBB","age":"30"}]
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
volleyRequest= Volley.newRequestQueue(this.context)
val view = inflater.inflate(R.layout.fragment_home, container, false)
val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
personList=ArrayList<Person>()
layoutManager= LinearLayoutManager(this.context)
adapter= PersonListAdapter(personList,this.context!!)
recyclerView.layoutManager=layoutManager
recyclerView.adapter=adapter
/*
for (i in 0..16) {
val person = Person()
person.name="Hello" + i
person.age = 20 + i
personList!!.add(person)
}*/
val jsonArray=JsonArrayRequest(Request.Method.GET,SchoolLink,
Response.Listener {
response: JSONArray ->
try {
Log.d("Response from JSON",response.toString())
for(i in 0..response.length()-1)
{
val person = Person()
val SchoolObj=response.getJSONObject(i)
var name=SchoolObj.getString("name")
person.name=name
Log.d("name from JSON",name)
var age:String=SchoolObj.getString("age")
person.age=age.toDouble()
Log.d("age from JSON",age)
personList!!.add(person)
}
adapter!!.notifyDataSetChanged()
} catch (e:JSONException){e.printStackTrace()}
},
Response.ErrorListener {
error ->
try {
Log.d("Error",error.toString())
}
catch (e: JSONException){e.printStackTrace()}
})
volleyRequest!!.add(jsonArray)
return view
}
fun getJsonArray(Url:String)
{
}
}
PersonListAdapter.kt
class PersonListAdapter(private val list: ArrayList<Person>,
private val context: Context)
: RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {
override fun getItemCount(): Int {
return list.size
}
override fun onCreateViewHolder(parent: ViewGroup?, position: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.list_row, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
holder?.bindItem(list[position])
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItem(person: Person) {
var name: TextView = itemView.findViewById(R.id.name) as TextView
var age: TextView = itemView.findViewById(R.id.age) as TextView
name.text = person.name
age.text = person.age.toString()
itemView.setOnClickListener {
Toast.makeText(context, name.text, Toast.LENGTH_LONG ).show()
}
}
}
}
In this part:
for(i in 0..response.length()-1)
{
val SchoolObj=response.getJSONObject(i)
var name=SchoolObj.getString("name")
person.name=name
Log.d("name from JSON",name)
var age:String=SchoolObj.getString("age")
person.age=age.toDouble()
Log.d("age from JSON",age)
}
You does not add the person object in the person list.
for(i in 0..response.length()-1)
{
val person = Person()
val SchoolObj=response.getJSONObject(i)
var name=SchoolObj.getString("name")
person.name=name
Log.d("name from JSON",name)
var age:String=SchoolObj.getString("age")
person.age=age.toDouble()
Log.d("age from JSON",age)
personList!!.add(person)
}
adapter!!.notifyDataSetChanged()
Hope this will help for you.

Categories

Resources