Android dynamic viewpager and tablayout from JSON data - android

I am following this tutorial https://www.codexpedia.com/android/android-tablayout-with-many-tabs-kotlin/
i am modify method to add fragment, but i need jump to specific tab in tablayout. this tutorial not return the tab position (page) correctly and every jump (lets say tab 5), always load every tab (0,1,2,3,4,5) not straight to tab 5, every tab need to take data from server so its take to much time for fetching data in all tab.
Listing Class
class Listing : AppCompatActivity() {
// From server
var latitude = ""
var longitude = ""
var category:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_listing)
getCategory()
}
fun getCategory(){
val builder = AlertDialog.Builder(this)
val dialogView=layoutInflater.inflate(R.layout.progress_dialog,null)
builder.setView(dialogView)
builder.setCancelable(false)
val dialog = builder.create()
dialog.show()
var rq: RequestQueue = Volley.newRequestQueue(this)
var sr = object : StringRequest(Request.Method.POST, user_info.get_category, Response.Listener { response ->
//========================================================================================= data from server
Handler().postDelayed({dialog.dismiss()},0)
Log.i("AIM", response.toString())
val pageAdapter = MyPagerAdapter(supportFragmentManager)
var jsonObject = JSONObject(response)
var data:JSONObject = jsonObject["data"] as JSONObject
var jsonArray = data.getJSONArray("vendor_type")
for (i in 0 until jsonArray.length()) {
var jo = jsonArray.getJSONObject(i)
var id = jo["id"].toString()
var nama = jo["nama"].toString()
pageAdapter.add(FirstFragment.newInstance(i), nama)
user_info.nama_category.add(i,nama)
Log.d("aim","Fragment created")
}
viewpager_main.adapter = pageAdapter
tabs_main.setupWithViewPager(viewpager_main)
if (category != 0){
var fix = category - 1
viewpager_main.setCurrentItem(fix, false)
}
}, Response.ErrorListener { response ->
//========================================================================================= error handling
Handler().postDelayed({dialog.dismiss()},0)
var networkResponse = response.networkResponse
if (networkResponse == null){
Toast.makeText(this, "Tidak terhubung dengan server", Toast.LENGTH_LONG).show()
}
}) { }
sr.retryPolicy = DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
rq.add(sr)
}
}
Fragment
class FirstFragment : Fragment() {
private val vendorData = mutableListOf<vendor_model>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_first, container, false)
val page = getArguments()!!.getInt(PAGE_NUM)
Log.d("aim", "page : $page")
getVendor(page)
return view
}
companion object {
val PAGE_NUM = "PAGE_NUM"
fun newInstance(page: Int): FirstFragment {
val fragment = FirstFragment()
val args = Bundle()
args.putInt(PAGE_NUM, page)
fragment.setArguments(args)
return fragment
}
}
fun getVendor(page: Int) {
val builder = activity?.let { AlertDialog.Builder(it) }
val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)
builder?.setView(dialogView)
builder?.setCancelable(false)
val dialog = builder?.create()
dialog?.show()
var category = page + 1
Log.d("aim", "category : $category")
var rq: RequestQueue = Volley.newRequestQueue(activity)
var sr = object : StringRequest(Request.Method.POST, url, Response.Listener { response ->
Handler().postDelayed({dialog?.dismiss()},0)
Log.i("AIM", response.toString())
var jsonObject = JSONObject(response)
var jsonArray = jsonObject.getJSONArray("list")
for (i in 0 until jsonArray.length()) {
var jo = jsonArray.getJSONObject(i)
var jarak: String
if (jo.isNull("distance")) {
jarak = "Unknown"
}else jarak = jo["distance"].toString() + " Km"
var id = jo["id_vendor"].toString()
var nama = jo["nama"].toString()
//var jarak = jo["distance"].toString()
var rating = jo["rating"].toString()
var status = jo["is_open"].toString()
var img = jo["file_logo"].toString()
var category = jo["vendor_type"].toString()
val mItem = vendor_model(id, nama, "$jarak", rating, status, img, category)
vendorData.add(mItem)
}
// ============ recycler_nearme ============
recyclerView.layoutManager = LinearLayoutManager(activity, OrientationHelper.VERTICAL,false)
val vendorAdapter = vendor_adapter()
recyclerView.adapter = vendorAdapter
vendorAdapter.setList(vendorData)
vendorData.clear()
}, Response.ErrorListener { response ->
Handler().postDelayed({dialog?.dismiss()},0)
//========================================================================================= error handling
Toast.makeText(activity, response.toString(), Toast.LENGTH_LONG).show()
var networkResponse = response.networkResponse
if (networkResponse == null){
Toast.makeText(activity, "Tidak terhubung dengan server", Toast.LENGTH_LONG).show()
}
else {
var code = networkResponse.statusCode
var err = networkResponse.data
Toast.makeText(activity, "Error : $code", Toast.LENGTH_LONG).show()
Log.i("AIM", err.toString())
}
}) {
override fun getParams(): MutableMap<String,String> {
var map = HashMap<String, String>()
map.put("text" , "")
map.put("tags" , "")
map.put("take" , "10")
map.put("skip" , "0")
map.put("sort_by" , "asc")
map.put("language" , "[]")
map.put("type" , "")
map.put("category" , "[$category]")
map.put("grade" , "[]")
map.put("nearme" , "0")
map.put("distance" , "")
map.put("location" , "")
map.put("latitude" , "")
map.put("longitude" , "")
map.put("open_now" , "")
map.put("price_min" , "")
map.put("price_max" , "")
map.put("rating" , "")
map.put("rating_max" , "")
map.put("rating_min" , "")
map.put("ratings" , "[]")
map.put("subject" , "")
return map
}
}
sr.retryPolicy = DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
rq.add(sr)
Log.i("aim", sr.body.toString(Charset.defaultCharset()))
}
}
Adapter
class MyPagerAdapter(fm: FragmentManager): FragmentPagerAdapter(fm){
private val tabNames: ArrayList<String>
private val fragments: ArrayList<Fragment>
init {
tabNames = ArrayList()
fragments = ArrayList()
}
fun add(fragment: Fragment, title: String) {
tabNames.add(title)
fragments.add(fragment)
}
override fun getCount(): Int {
return fragments.size
}
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getPageTitle(position: Int): CharSequence {
return tabNames[position]
}
}
thank you for your answer, really apreciated

You can pass additional parameter (second one as false):
viewpager_main.setCurrentItem(4, false)
Set true to smoothly scroll to the new item,
Set false to do transition immediately

Related

java.lang.NumberFormatException: For input string: "null" at jdk.internal.math.FloatingDecimal.readJavaFormatString

I tried to pass data from DetailActivity to PaymentActivity, but I got this error
Here is the error and here is PaymentFragment after I comment textview that contain number format on it here it is. The user data pass successfully, but the product data unsuccess to pass I think. So how to pass the product data from DetailActivity to PaymentActivity
here is my code:
Helpers File
object Helpers {
fun getDefaultGson(): Gson {
return GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setDateFormat(Cons.DATE_FORMAT_SERVER)
.registerTypeAdapter(Date::class.java, JsonDeserializer { json, _, _ ->
val formatServer = SimpleDateFormat(Cons.DATE_FORMAT_SERVER, Locale.ENGLISH)
formatServer.timeZone = TimeZone.getTimeZone("UTC")
formatServer.parse(json.asString)
})
.registerTypeAdapter(Date::class.java, JsonSerializer<Date> { src, _, _ ->
val format = SimpleDateFormat(Cons.DATE_FORMAT_SERVER, Locale.ENGLISH)
format.timeZone = TimeZone.getTimeZone("UTC")
if (src != null) {
JsonPrimitive(format.format(src))
} else {
null
}
})
.create()
}
fun Throwable.getErrorBodyMessage(): String {
return if (this is HttpException) {
val errorCode = this.code()
if (errorCode == 405) {
"Method yang digunakan salah"
} else if (errorCode == 503) {
"Error Server"
} else {
val parseErrorBody = this.response()?.errorBody()!!.parseErrorBody()
if (parseErrorBody?.meta?.message == null) {
"Permintaan anda belum berhasil di proses. Silakan coba kembali"
} else {
parseErrorBody?.meta?.message.toString()
}
}
} else if (this is ConnectException || this is UnknownHostException) {
"Maaf Anda sedang Offline. Silakan coba kembali"
} else {
return if (this.message == null)
"Permintaan anda belum berhasil di proses. Silakan coba kembali"
else if (this.message.equals(""))
""
else
this.message!!
}
}
fun ResponseBody.parseErrorBody(): Wrapper<*>? {
val gson = Gson()
val adapter = gson.getAdapter(Wrapper::class.java)
try {
return adapter.fromJson(string())
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
fun TextView.formatPrice(value: String) {
this.text = getCurrencyIdr(java.lang.Double.parseDouble(value))
}
fun getCurrencyIdr(price: Double): String {
val format = DecimalFormat("#,###,###")
return "Rp. " + format.format(price).replace(",".toRegex(), ".")
}
fun Long.convertLongToTime(formatTanggal: String): String {
val date = Date(this)
val format = SimpleDateFormat(formatTanggal)
return format.format(date)
}
}
PaymentFragment:
class PaymentFragment : Fragment(), PaymentContract.View {
var progressDialog: Dialog? = null
var total : Int = 0
lateinit var presenter: PaymentPresenter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_payment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(activity as DetailActivity?)!!.toolbarPayment()
var data = arguments?.getParcelable<Data>("data")
initView(data)
initView()
presenter = PaymentPresenter(this)
}
private fun initView(data: Data?) {
tvTitle.text = data?.name
tvPrice.formatPrice(data?.price.toString())
Glide.with(requireContext())
.load(data?.picturePath)
.into(tvPoster)
tvNameItem.text = data?.name
tvHarga.formatPrice(data?.price.toString())
if (!data?.price.toString().isNullOrEmpty()) {
var totalTax = data?.price?.div(10)
tvTax.formatPrice(totalTax.toString())
total = data?.price!! + totalTax!! + 50000
tvTotalPrice.formatPrice(total.toString())
} else {
tvPrice.text = "IDR. 0"
tvTax.text = "IDR. 0"
tvTotalPrice.text = "IDR. 0"
total = 0
}
var user = IcaCraft.getApp().getUser()
var userResponse = Gson().fromJson(user, User::class.java)
tvNameDeliver.text = userResponse?.name
tvPhoneDeliver.text = userResponse?.phoneNumber
tvAddressDeliver.text = userResponse?.address
tvHouseNo.text = userResponse?.houseNumber
tvCityDeliver.text = userResponse?.postalCode
btn_CheckoutNow.setOnClickListener {
presenter.getCheckout(
data?.id.toString(),
userResponse?.id.toString(),
"1",
total.toString(), it
)
}
}
private fun initView() {
progressDialog = Dialog(requireContext())
val dialogLayout = layoutInflater.inflate(R.layout.dialog_loader, null)
progressDialog?.let {
it.setContentView(dialogLayout)
it.setCancelable(false)
it.window?.setBackgroundDrawableResource(android.R.color.transparent)
}
}
override fun onCheckoutSuccess(checkoutResponse: CheckoutResponse, view: View) {
val i = Intent(Intent.ACTION_VIEW)
i.data = Uri.parse(checkoutResponse.paymentUrl)
startActivity(i)
Navigation.findNavController(view).navigate(R.id.action_fragmentPayment_to_fragmentPaymentSuccess)
}
override fun onCheckoutFailed(message: String) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
}
override fun showLoading() {
progressDialog?.show()
}
override fun dismissLoading() {
progressDialog?.dismiss()
}
}
DetailActivity:
class DetailFragment : Fragment() {
var data:Data?= null
var bundle:Bundle?= null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_detail, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(activity as DetailActivity?)!!.toolbarDetail()
arguments?.let {
DetailFragmentArgs.fromBundle(it).data?.let {
initView(it)
}
}
btnOrderNow.setOnClickListener { view ->
Navigation.findNavController(view).navigate(R.id.action_fragmentDetail_to_fragmentPayment, bundle)
}
}
private fun initView(data: Data?) {
data?.let {
// bundle = bundleOf("data" to data)
Glide.with(requireContext())
.load(it.picturePath)
.into(ivPoster)
tvTitle.text = it.name
tvDescription.text = it.description
tvMaterials.text = it.materials
tvTotal.formatPrice(it.price.toString())
}
}
}
I am not sure about the bug in the code but there are many other ways you can share data in between activities. Try using viewModel to share data between your activities. SharedPreferences are another way too. There are plenty of other ways but I think viewModel is the best way. I personally find it difficult to transfer data between fragments using arguments. So Good Luck!
Your code is a bit complicated but the error is understandable. It says "You can not parse null to double". You define "price" as "Int?", so it can be "null" and when it is null, app crashes. This can be solved by doing the followings:
1- You can define your price "not null" and set a default value as 0.
#Expose
#SerializedName("price")
val price: Int = 0
2- If you do not want to change your data class, you need to control what to pass to "parseDouble()" method.
fun TextView.formatPrice(value: String) {
if (value != null) {
this.text = getCurrencyIdr(java.lang.Double.parseDouble(value))
} else {
this.text = getCurrencyIdr(0.0) // we didn't parse the null
}
}
If one of these individually will not solve your error try both, it has to solve it.

Jitsi Meet mute audio and video issue

i'm trying to mute everyone in the conference call to prevent trolling/spamming, but the problem is allowed to umute audio and video at anytime even tho i'm setting the options to be muted by default. P.S : if you have any idea that may help me to prevent this issue from going on into the conference call please just write it down.
MeetingUtils.kt
object MeetingUtils {
private var isMuted: Boolean = true
fun startMeeting(context: Context, meetingCode: String) {
val serverUrl = URL(context.getString(R.string.app_server_url))
val defaultOptions = JitsiMeetConferenceOptions.Builder()
.setServerURL(serverUrl)
.setWelcomePageEnabled(false)
.setAudioMuted(isMuted)
.setVideoMuted(true)
.setFeatureFlag("invite.enabled", false)
.setFeatureFlag("live-streaming.enabled", false)
.setFeatureFlag("meeting-name.enabled", false)
.setFeatureFlag("call-integration.enabled", false)
.setFeatureFlag("recording.enabled", false)
.build()
JitsiMeet.setDefaultConferenceOptions(defaultOptions)
val options = JitsiMeetConferenceOptions.Builder()
.setRoom(meetingCode)
.setUserInfo(null)
val sharedPrefData= SharedPrefData(context)
val currentUser = FirebaseAuth.getInstance().currentUser
if (sharedPrefData.getSkip().equals("Skip"))
{
val userInfoBundle = bundleOf(
"displayName" to "User Not Sign in",
"email" to "Please Sign In",
"avatarURL" to R.drawable.ic_account
)
options.setUserInfo(JitsiMeetUserInfo(userInfoBundle))
}
else
{
if (currentUser != null) {
val userInfoBundle = bundleOf(
"displayName" to sharedPrefData.getName(),
"email" to sharedPrefData.getEmail(),
"avatarURL" to sharedPrefData.getImage()
)
options.setUserInfo(JitsiMeetUserInfo(userInfoBundle))
}
val userInfoBundle = bundleOf(
"displayName" to sharedPrefData.getName() ,
"email" to sharedPrefData.getEmail(),
"avatarURL" to "http://graph.facebook.com/${sharedPrefData.getAuthId()}/picture?type=square"
)
options.setUserInfo(JitsiMeetUserInfo(userInfoBundle))
}
JitsiMeetActivity.launch(context, options.build())
}
}
HomeFragment.kt
class HomeFragment : Fragment() {
private var binding: FragmentHomeBinding? = null
private val minMeetingCodeLength = 10
private var currentUser: FirebaseUser? = null
var email:String?=null
var firstName:String?=null
var lastName:String?=null
var profileImage:String?=null
private val viewModel by viewModel<MainViewModel>()
lateinit var auth: FirebaseAuth
private var sharedPrefData: SharedPrefData?=null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
binding=FragmentHomeBinding.inflate(inflater,container,false)
val view = binding!!.root
onCreateMeetingCodeChange()
onCopyMeetingCodeFromClipboardClick()
onShareMeetingCodeClick()
onJoinMeetingClick()
onCreateMeetingClick()
onMeetingToggleChange()
val mAdView: AdView = view.findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
return view
}
companion object{
fun newInstance(text: String?): HomeFragment? {
val f = HomeFragment()
val b = Bundle()
b.putString("msg", text)
f.arguments = b
return f
}
}
private fun onMeetingToggleChange() {
binding?.tgMeeting?.addOnButtonCheckedListener { toggleGroup, checkedId, isChecked ->
if (isChecked) {
when (checkedId) {
R.id.btnToggleJoinMeeting -> {
binding?.groupCreateMeeting?.makeGone()
binding?.groupJoinMeeting?.makeVisible()
}
R.id.btnToggleCreateMeeting -> {
binding?.groupJoinMeeting?.makeGone()
binding?.groupCreateMeeting?.makeVisible()
val meetingCode = generateMeetingCode()
binding?.etCodeCreateMeeting?.setText(meetingCode)
}
}
}
}
}
private fun onCreateMeetingCodeChange() {
binding?.tilCodeCreateMeeting?.etCodeCreateMeeting?.doOnTextChanged { text, start, before, count ->
if (count >= minMeetingCodeLength) binding?.tilCodeCreateMeeting!!.error = null
}
}
private fun generateMeetingCode(): String {
val allowedChars = ('A'..'Z') + ('a'..'z')
return (1..10)
.map { allowedChars.random() }
.joinToString("")
}
private fun onCopyMeetingCodeFromClipboardClick() {
binding?.tilCodeJoinMeeting?.setEndIconOnClickListener {
val clipboardText = activity?.getTextFromClipboard()
if (clipboardText != null) {
binding?.etCodeJoinMeeting?.setText(clipboardText)
activity?.toast(getString(R.string.main_meeting_code_copied))
} else {
activity?.toast(getString(R.string.main_empty_clipboard))
}
}
}
private fun onShareMeetingCodeClick() {
binding?.tilCodeCreateMeeting?.setEndIconOnClickListener {
if (binding?.etCodeCreateMeeting?.text.toString().length >= minMeetingCodeLength) {
binding!!.tilCodeCreateMeeting.error = null
activity?.startShareTextIntent(
getString(R.string.main_share_meeting_code_title),
"Meeting Code: "+binding!!.etCodeCreateMeeting.text.toString()+"\n "+
getString(R.string.profile_share_app_text, activity!!. applicationContext.packageName)
)
} else {
binding!!.tilCodeCreateMeeting.error =
getString(R.string.main_error_meeting_code_length, minMeetingCodeLength)
}
}
}
private fun onJoinMeetingClick() {
binding?.btnJoinMeeting?.setOnClickListener {
if (binding!!.etCodeJoinMeeting.text.toString().length >= minMeetingCodeLength) {
joinMeeting()
} else {
activity?.toast(getString(R.string.main_error_meeting_code_length, minMeetingCodeLength))
}
}
}
private fun joinMeeting() {
activity?.let {
MeetingUtils.startMeeting(
it,
binding?.etCodeJoinMeeting?.text.toString())
} // Start Meeting
viewModel.addMeetingToDb(
Meeting(
binding?.etCodeJoinMeeting?.text.toString(),
System.currentTimeMillis()
)
) // Add meeting to db
}
private fun onCreateMeetingClick() {
binding?.btnCreateMeeting?.setOnClickListener {
if (binding!!.etCodeCreateMeeting.text.toString().length >= minMeetingCodeLength) {
createMeeting()
} else {
activity?.toast(getString(R.string.main_error_meeting_code_length, minMeetingCodeLength))
}
}
}
private fun createMeeting() {
activity?.let {
MeetingUtils.startMeeting(
it,
binding?.etCodeCreateMeeting?.text.toString()
)
} // Start Meeting
viewModel.addMeetingToDb(
Meeting(
binding?.etCodeCreateMeeting?.text.toString(),
System.currentTimeMillis()
)
) // Add meeting to db
}
}

How can I call a variab that I wrote in a non-Class place to another class?

1.The "address" variable here gives me a city name with coordinates.I would like to write this address instead of Istanbul in the retrofit so that it can automatically show the weather of the selected location on the map.(Googlemap)
private const val TAG = "MapViewFragment"
class MapViewFragment: Fragment(), OnMapReadyCallback {
companion object{
private lateinit var nMap: GoogleMap
var address:String = ""
var test:String = ""
var test2:String = ""
var cacik:String = "adana"
private var markers:MutableList<Marker> = mutableListOf<Marker>()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
map_view.onCreate(savedInstanceState)
map_view.onResume()
map_view.getMapAsync(this)
setToolbar()
}
override fun onMapReady(map: GoogleMap?) {
if (map != null) {
nMap = map
}
map?.let {
nMap = it
nMap.setOnInfoWindowClickListener { markerToDelete ->
Log.i(TAG, "onWindowsClickListener - Delete Thismarker")
markers.remove(markerToDelete)
markerToDelete.remove()
}
nMap.setOnMapLongClickListener { latlng ->
Log.i(TAG, "onMapLongClickListener" + latlng)
Toast.makeText(
requireContext(),
"this is toast message" + latlng,
Toast.LENGTH_SHORT
).show()
showAlertDialog(latlng)
address= getAddress(latlng.latitude, latlng.longitude)
test = getAddress(37.000000,35.321335)
test2 = "istanbul"
Log.d(TAG,"test5 $address ${latlng.latitude} ${latlng.longitude}")
Toast.makeText(requireContext(),"test"+address,Toast.LENGTH_LONG).show()
}
}
}
private fun getAddress(lat: Double, lng: Double): String {
val geocoder = Geocoder(requireContext())
val list = geocoder.getFromLocation(lat, lng, 1)
return list[0].getAddressLine(0)
//val stateName: String = addresses[0].getAddressLine(1)
}
private fun showAlertDialog(latlng: LatLng) {
val dialog =
AlertDialog.Builder(requireContext())
.setTitle("Create a marker").setMessage("add marker...")
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok", null)
.show()
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener {
val marker = nMap.addMarker(
MarkerOptions().position(latlng).title("my new marker").snippet(
"a cool snippet"
)
)
markers.add(marker)
dialog.dismiss()
}
dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener {
dialog.dismiss()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.mapviewfragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
private fun setToolbar(){
val actionBar : ActionBar? =(requireActivity() as MainActivity).supportActionBar
actionBar?.apply {
title = getString(R.string.Kartenansicht)
setDisplayShowTitleEnabled(true)
setHomeButtonEnabled(true)
}
}
}
3.i just want to call "address" in my retrofit response .I want to call the address on the other class and write the location of Istanbul.The getter and setter methods don't work because I haven't written them inside the class.How can I use the address in another class.
private const val TAG = "Retrofit Connection"
fun main(){
retrofitResponse()
}
object RetrofitSetup {
//var test = MapViewFragment.address
var urlAll = "api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}"
var url = "https://api.openweathermap.org/data/2.5/"
val apiKey = "d459f98ffa705ad3f6c5e02f86d9fab9"
}
fun retrofitResponse(){
val retrofit = Retrofit.Builder()
.baseUrl(RetrofitSetup.url)
.addConverterFactory(GsonConverterFactory.create())
.build()
val weatherApi = retrofit.create(CallWeatherApi::class.java)
val weatherResponseCall = weatherApi.getWeather(MapViewFragment.test,RetrofitSetup.apiKey)
weatherResponseCall!!.enqueue(object : Callback<CurrentWeatherResponse?> {
override fun onResponse(call: Call<CurrentWeatherResponse?>, response: Response<CurrentWeatherResponse?>
) {
if (response.code() == 404) {
Log.d(TAG,"Successfuly")
} else if (!response.isSuccessful) {
Log.d(TAG,"Error")
}
val mydata = response.body()
val main = mydata!!.main
val temp = main!!.temp
val pres =main!!.pressure
val temperature = (temp!! - 273.15).toInt()
Log.d("TAG","City pressure :" + pres)
Log.d("TAG","City Temp : " + temperature)
}
override fun onFailure(call: Call<CurrentWeatherResponse?>, t: Throwable) {}
})
}
if i write default istanbul.its working
if i create another varible in other class dosent work
exception
put "retrofitResponse" inside "RetrofitSetup" and add a parameter for the addresss
object RetrofitSetup {
private const val urlAll = "api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}"
private const val url = "https://api.openweathermap.org/data/2.5/"
private const val apiKey = "keep this private"
fun retrofitResponse(address: String) {
...
val weatherResponseCall = weatherApi.getWeather(address, apiKey)
...
}
}
then pass the address as argument
nMap.setOnMapLongClickListener { latlng ->
val address = getAddress(latlng.latitude, latlng.longitude)
RetrofitSetup.retrofitResponse(address)
}

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)

Recycler View not showing JSON data in kotlin

Here is my main class where I'm adding JASON data in ArrayList using volley.
Toast show the JASON data but array does not show any data. I'm trying to solve my error from last 3 days.
I also read many questions on stack but i have no solution for this please help me
var item = ArrayList<dumy_item_list>()
var url = "https://apps.faizeqamar.website/charity/api/organizations"
var rq: RequestQueue = Volley.newRequestQueue(this)
var sr = StringRequest(Request.Method.GET, url, Response.Listener { response ->
var jsonResponse = JSONObject(response)
var jsonArray: JSONArray = jsonResponse.getJSONArray("data")
for (i in 0..jsonArray.length() - 1) {
var jsonObject: JSONObject = jsonArray.getJSONObject(i)
var name = jsonObject.getString("name")
val data = dumy_item_list()
data.setName(jsonObject.getString(name))
item.add(data)
Toast.makeText(applicationContext, "NGO Name is : $name", Toast.LENGTH_LONG).show()
}
},
Response.ErrorListener { error ->
Toast.makeText(applicationContext, error.message, Toast.LENGTH_LONG).show()
})
rq.add(sr)
var away_recycler = findViewById<RecyclerView>(R.id.away_recycler)
var adaptor = custom_adopter(item, applicationContext)
away_recycler.layoutManager = GridLayoutManager(applicationContext, 1)
away_recycler.adapter = adaptor
}
Here is my adapter class where I'm using getName() function
class custom_adopter(data: ArrayList<dumy_item_list>, var context: Context) :
RecyclerView.Adapter<custom_adopter.viewHolder>() {
var data: List<dumy_item_list>
init {
this.data = data
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): custom_adopter.viewHolder {
var layout = LayoutInflater.from(context).inflate(R.layout.dumy_item, parent, false)
return viewHolder(layout)
}
override fun onBindViewHolder(holder: custom_adopter.viewHolder, position: Int) {
holder.tv_dummy_name_donnor.text = data[position].getName()
holder.card.setOnClickListener {
var intent = Intent(context, ngosProfile::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(context, intent, null)
}
}
override fun getItemCount(): Int {
return data.size
}
class viewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal var tv_dummy_name_donnor: TextView
internal var card: CardView
init {
tv_dummy_name_donnor = itemView.findViewById(R.id.tv_dummy_name_donnor)
card = itemView.findViewById(R.id.card)
}
}
}
follow this code this work for me. (var adaptor = custom_adopter(item, applicationContext) away_recycler.adapter = adaptor progressBar2?.visibility = View.INVISIBLE ) singe the value to adaptor after the loop.
class MainActivity : AppCompatActivity() {
var progressBar2:ProgressBar?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var item = ArrayList<dumy_item_list>()
var progressBar2 = findViewById<ProgressBar>(R.id.progressBar2)
var away_recycler = findViewById<RecyclerView>(R.id.away_recycler)
away_recycler.layoutManager = GridLayoutManager(applicationContext, 1)
var url = "https://apps.faizeqamar.website/charity/api/organizations"
var rq: RequestQueue = Volley.newRequestQueue(this)
var sr = StringRequest(Request.Method.GET, url, Response.Listener { response ->
var jsonResponse = JSONObject(response)
var jsonArray: JSONArray = jsonResponse.getJSONArray("data")
for (i in 0..jsonArray.length() - 1) {
var jsonObject: JSONObject = jsonArray.getJSONObject(i)
var name = jsonObject.getString("ngo_name")
var about = jsonObject.getString("ngo_desc")
item.add(dumy_item_list(name,about))
}
var adaptor = custom_adopter(item, applicationContext)
away_recycler.adapter = adaptor
progressBar2?.visibility = View.INVISIBLE
},
Response.ErrorListener { error ->
})
rq.add(sr)
}
I guess you have the RecyclerView with all items, but they are empty
so the issue should be where you fill the list of you adapter..in this below line exactly :
data.setName(jsonObject.getString(name))
it must be something like
data.setName(name)
OR
data.setName(jsonObject.getString("name"))
You should call method notifyDataSetChanged of the adapter after the data is loaded in your list in order to inform that there is new data.

Categories

Resources