I've a php file on a server, and I have to fetch the information but i don't know how to pass a parameter to the query.
For example, if I have this query: SELECT * FROM accounttable WHERE idaccount = 1, i want to pass this 1 as a parameter, how can i do?
val stringRequest = StringRequest(Request.Method.POST, URL, Response.Listener<String>{ s ->
try {
val array = JSONArray(s)
for (i in 0..array.length() - 1) {
val objectAccount = array.getJSONObject(i)
val account = Account(
objectAccount.getString("accountplace"),
objectAccount.getString("useraccount"),
objectAccount.getString("accountpass"))
listAccounts.add(account)
}
}catch (e: JSONException){
e.printStackTrace()
}
}, Response.ErrorListener { error: VolleyError? -> Log.e("error", "error") })
val requesQueue = Volley.newRequestQueue(this)
requesQueue.add<String>(stringRequest)
You need to override the getParams() method on your Request. In order to do that you can either subclass StringRequest, or create an object expression (similar to an anonymous inner class from Java); as shown below.
val stringRequest = object : StringRequest(Request.Method.POST, URL, Response.Listener { s ->
// Your success code here
}, Response.ErrorListener { e ->
// Your error code here
}) {
override fun getParams(): Map<String, String> = mapOf("idaccount" to "1")
}
Related
I am new to kotlin and coroutines.I have been working on a client-server part of an android app.I am using mediasoup-client-android library for this.
I am trying to intialize the sendtransports using createSendTransport() method.This method does have a sendTransportListener which has abstract methods.One of them being is onProduce() which returns a producerId which is a String. awaitEmit() is an asynchronous action and I need this in onProduce().To use awaitEmit() I used coroutines.But I need String as return type instead of Deferred.Is there any other way to implement the mentioned logic? Below is my code
class RoomClient {
suspend fun initTransports(device: Device) {
coroutineScope {
val id: String?
val iceParameters: String?
val iceCandidates: String?
val dtlsParameters: String?
val sctpParameters: String?
try {
val params = JSONObject()
params.put("forceTcp",false)
params.put("rtpCapabilities", this#RoomClient.device?.rtpCapabilities)
val res = socket?.awaitEmit("createWebRtcTransport",params)
val data = res?.get(0) as JSONObject
if (data.has("error")) {
Log.d(TAG, data.getString("error"))
return#coroutineScope
}
id = data.optString("id")
iceParameters = data.optString("iceParameters")
iceCandidates = data.optString("iceCandidates")
dtlsParameters = data.optString("dtlsParameters")
sctpParameters = data.optString("sctpParameters")
} catch (e: Throwable) {
Log.e(TAG, "${e.message}")
return#coroutineScope
}
val sendTransportListener: SendTransport.Listener = object : SendTransport.Listener {
private val listenerTAG = TAG.toString() + "_ProducerTrans"
override fun onProduce(
transport: Transport,
kind: String?,
rtpParameters: String?,
appData: String?
): String? {
this#coroutineScope.async{
var producerId: String? = null
Log.d(listenerTAG, "onProduce() ")
val producerDeferred = launch {
val params = JSONObject("""{"producerTransportId": transport.id, "kind": kind, "rtpParameters": rtpParameters,"appData": appData}""")
val res = socket?.awaitEmit("produce",params)
val data = res?.get(0) as JSONObject
producerId = data.getString("producer_Id")
}
producerDeferred.join()
Log.d(listenerTAG, "producerId inside the coroutine: $producerId"
}
return#async producerId
}
}
this#RoomClient.producerTransport = device.createSendTransport(
sendTransportListener, id,
iceParameters,
iceCandidates,
dtlsParameters
)
}
}
}
And also I am not sure about the way coroutines are used here.Please correct me If I have missed something central.
I want to hide app icon from grid view and save it.
I can save application info to shared preferences as mutable set string and get it but cant convert string to application info and show in my grid view
my app activity
private var applist: List<ApplicationInfo>? = null
private var listadaptor: ApplicationAdapter? = null
private var grid: GridView? = null
private var mSelected: ArrayList<Any> = ArrayList()
var context: Activity = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_apps)
val packageManager = getPackageManager()
LoadApplications().execute()
grid = findViewById<View>(R.id.grid) as GridView
grid!!.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE)
grid!!.adapter = listadaptor
grid!!.onItemClickListener = AdapterView.OnItemClickListener { parent: AdapterView<*>?, view: View?, position: Int, id: Long ->
val app = applist!![position]
try {
val intent = packageManager.getLaunchIntentForPackage(app.packageName)
intent?.let { startActivity(it) }
} catch (e: Exception) {
Toast.makeText(this#appsActivity, e.message, Toast.LENGTH_LONG).show()
}
}
grid!!.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->
val position1: String = (position).toString()
if (mSelected.contains(position1)) {
mSelected.remove(position1)
view.setBackgroundColor(Color.TRANSPARENT) // remove item from list
// update view (v) state here
// eg: remove highlight
} else {
mSelected.add(position1)
view.setBackgroundColor(Color.LTGRAY) // add item to list
// update view (v) state here
// eg: add highlight
}
button3.setOnClickListener(
object : View.OnClickListener {
override fun onClick(view: View?) {
val builder1: AlertDialog.Builder = AlertDialog.Builder(this#appsActivity)
builder1.setMessage("Are you sure you want to delete it ?")
builder1.setCancelable(true)
builder1.setPositiveButton(
"Yes",
DialogInterface.OnClickListener { dialog, id ->
deleteSelectedItems()
mSelected.remove(position)
listadaptor!!.notifyDataSetChanged()
val app = applist!![position]
listadaptor!!.remove(app)
})
builder1.setNegativeButton(
"No",
DialogInterface.OnClickListener { dialog, id -> dialog.cancel() })
val alert11: AlertDialog = builder1.create()
alert11.show()
}
})
true
}
}
private fun deleteSelectedItems() {
val checked: SparseBooleanArray = grid!!.getCheckedItemPositions()
if (checked != null) {
val list: List<Any> = mSelected
for (i in 0 until checked.size()) {
if (checked.valueAt(i)) {
mSelected.remove(checked.keyAt(i))
}
}
}
}
private fun checkForLaunchIntent(list: List<ApplicationInfo>): List<ApplicationInfo> {
val applist = ArrayList<ApplicationInfo>()
for (info in list) {
try {
if (null != packageManager!!.getLaunchIntentForPackage(info.packageName)) {
applist.add(info)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
Collections.sort(applist, ApplicationInfo.DisplayNameComparator(packageManager))
return applist
}
#SuppressLint("StaticFieldLeak")
private inner class LoadApplications : AsyncTask<Void?, Void?, Void?>() {
override fun doInBackground(vararg params: Void?): Void? {
applist = checkForLaunchIntent(packageManager!!.getInstalledApplications(
PackageManager.GET_META_DATA))
listadaptor = ApplicationAdapter(this#appsActivity,
R.layout.grid_item, applist!!)
return null
}
override fun onPostExecute(result: Void?) {
grid!!.adapter = listadaptor
super.onPostExecute(result)
}
}
items are deleted, but after re-running the application, all installed apps will be restored in gridview
You can look into my open source project LibTron which has one module library for SharedPref written in Kotlin.
To use the library follow the instruction in Project ReadMe
Example to use the library:
val applicationInfo: ApplicationInfo = sharedprefrence.Object(name = "sharedprefKey", defaultValue = null)
Or in case you want to use it without the help of the you can use GSON, Moshi, Jackson type libraries to convert to/from string to your ApplicationInfo class while saving or reading from the Sharedprefrence
I have the following code, where I validate the JWT token (with volley):
private fun validateToken(token: String) {
var queue = Volley.newRequestQueue(this)
val yourUrl = "https://mysite/wp-json/jwt-auth/v1/token/validate"
val parameters = JSONObject()
try {
parameters.put("username", "abc#test.com")
parameters.put("password", "12345678")
} catch (e: java.lang.Exception) {
}
val request: JsonObjectRequest =
object : JsonObjectRequest(
Method.POST, yourUrl, parameters,
Response.Listener { response -> Log.i("onResponse", response.toString()) },
Response.ErrorListener { error -> Log.e("onErrorResponse", error.toString()) }) {
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers: MutableMap<String, String> = HashMap()
// Basic Authentication
//String auth = "Basic " + Base64.encodeToString(CONSUMER_KEY_AND_SECRET.getBytes(), Base64.NO_WRAP);
headers["Authorization"] = "Bearer $token"
return headers
}
}
queue.add(request)
}
It works for me and I get the correct response from the server (in Log.i):
{"code":"jwt_auth_valid_token","data":{"status":200}}
My question is how in my code I do to be able to save the status: 200 in a variable so then it applies an ʻif status == 200` and if it is 200 then send it to another activity.
Add implementation 'com.google.code.gson:gson:2.8.6' to build.gradle(app)
Create Model.tk with:
data class dataServer (
#SerializedName("code") val code : String,
#SerializedName("data") val data : Data
)
data class Data (
#SerializedName("status") val status : Int
)
3. Update code:
private fun validateToken(token: String) {
var queue = Volley.newRequestQueue(this)
val yourUrl = "https://myweb/wp-json/jwt-auth/v1/token/validate"
val parameters = JSONObject()
try {
parameters.put("username", "abc#test.com")
parameters.put("password", "12345678")
} catch (e: java.lang.Exception) {
}
val request: JsonObjectRequest =
object : JsonObjectRequest(
Method.POST, yourUrl, parameters,
Response.Listener {
response ->
Log.i("onResponse", response.toString())
val gson = Gson()
val dataToken = gson.fromJson(response.toString(), dataServer::class.java)
val status = dataToken.data.status
println(status)
// use here if then
},
Response.ErrorListener { error -> Log.e("onErrorResponse", error.toString()) }) {
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers: MutableMap<String, String> = HashMap()
// Basic Authentication
//String auth = "Basic " + Base64.encodeToString(CONSUMER_KEY_AND_SECRET.getBytes(), Base64.NO_WRAP);
headers["Authorization"] = "Bearer $token"
return headers
}
}
queue.add(request)
}
I'm trying to add url values (imgURL variable) taken from JSON into an ArrayList with Kotlin, but somehow when in the scope of the for loop it doesn't seem to work regardless of having my newArrayURLs array declared as a function variable. Any ideas why is this?
private fun getJsonObjectImg(Url: String): ArrayList<String>{
var paths: ArrayList<String> =ArrayList()
val params = HashMap<String, String>()
var newArrayURLs = ArrayList<String>()
val stringRequest = object : StringRequest(Request.Method.POST, Url, Response.Listener { s ->
try {
val array = JSONObject(s)
var imagesArray = array.getJSONArray("images")
for(i in 0..imagesArray.length() -1 ){
var imgURL = imagesArray.getJSONObject(i).getString("fileName")
newArrayURLs.add(imgURL)
paths.add(imgURL)
}
Log.d("pathsin TRY", paths.count().toString())
} catch(e:JSONException){
Log.d("ERROR------", e.toString())
null
}
}, Response.ErrorListener {
error: VolleyError? ->
try {
Log.d("ERROR======","V")
} catch (e: JSONException){
e.printStackTrace()
}
}) {
override fun getParams(): Map<String, String> = mapOf("uploadedBy" to id)
}
val requestQueue = Volley.newRequestQueue(this)
requestQueue.add<String>(stringRequest)
return newArrayURLs
}
What i want to achive is
Call IndexList API and display the responded list in a spinner -> Click on Spinner item i want to call 3 api in parallel using .zip operator and display in DetailViewModel
I am using flatmap for calling api in sequence
In first flatmap i am calling IndexList api and i am passing IndexList response to call 3 multiple api in parallel using Observable.zip operator but i am not able
to achive the second part of calling 3 API in parallel and display in view model
Code Snippet:
Spinner Click :
spinner_index_list?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
//Performing action onItemSelected and onNothing selected
override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {
mRecyclerView?.visibility = View.GONE
//Select item from spinner calling API
val symbolDefaultGroup = SymbolForDefaultGroup(indexExchangeSegmentList[pos], parent.getItemAtPosition(pos).toString())
grpIndexViewModel.getSearchSymbol(symbolDefaultGroup)?.observe(this#FragmentWatchlist, Observer { instrumentByIdResponse ->
mDataProvider = ExpandableDataProvider(instrumentByIdResponse)
mRecyclerView?.visibility = View.VISIBLE
if (instrumentByIdResponse != null)
initRecyclerView(savedInstanceState)
})
}
ViewModel :
fun getSearchSymbol(symbolForDefaultGroup: SymbolForDefaultGroup): LiveData<List<InstrumentByIdResponse>>? {
instrumentByIdResponse = null
instrumentByIdResponse = MutableLiveData<List<InstrumentByIdResponse>>()
instrumentByIdResponse = groupRepository.getSearchSymbol(symbolForDefaultGroup)
L.d("get symbol for default group method")
return instrumentByIdResponse
}
Repository:
override fun getSearchSymbol(symbolForDefaultGroup: SymbolForDefaultGroup): LiveData<List<InstrumentByIdResponse>> {
val mutableLiveData = MutableLiveData<List<InstrumentByIdResponse>>()
val instrumentsIdList = ArrayList<Instrument>()
val marketDataQuotesList = ArrayList<QuotesList>()
val subscriptionList = ArrayList<SubscriptionList>()
val symbolFroDefaultGroup: Observable<BaseResponse<SymbolForDefaultGroupResponse>> = remoteServices.requestSymbolForDefaultGroup(symbolForDefaultGroup)
symbolFroDefaultGroup
.flatMap { response ->
for (i in 0 until response.result!!.instruments.size) {
instrumentsIdList.add(Instrument(EnumConfig.getExchangeSegment(response.result.exchangeSegment)!!.toInt(), response.result.instruments[i].toInt()))
marketDataQuotesList.add(QuotesList(EnumConfig.getExchangeSegment(response.result.exchangeSegment)!!.toInt(), response.result.instruments[i].toInt()))
subscriptionList.add(SubscriptionList(EnumConfig.getExchangeSegment(response.result.exchangeSegment)!!.toInt(), response.result.instruments[i].toInt()))
}
val instrumentByIdResult = InstrumentById(instrumentsIdList)
val marketDataQuotes = MarketDataQuotes("ABC", "ABC", marketDataQuotesList, 1111)
val subscriptionList = Subscribe("ABC", "ABC", "Mobile", subscriptionList, 1111)
return#flatMap getDetails(instrumentByIdResult, marketDataQuotes, subscriptionList)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : ErrorCallBack<BaseResponse<List<InstrumentByIdResponse>>>() {
override fun onSuccess(t: BaseResponse<List<InstrumentByIdResponse>>) {
L.d("Success of Search Instrument")
mutableLiveData.value = transform1(t)
}
})
return mutableLiveData
}
private fun transform1(response: BaseResponse<List<InstrumentByIdResponse>>?): List<InstrumentByIdResponse>? {
return response!!.result!!.toList()
}
fun getDetails(instrumentById: InstrumentById, marketDataQuotes: MarketDataQuotes, subscription: Subscribe): Observable<DetailsModel> {
return Observable.zip(
remoteServices.requestInstrumentById(instrumentById),
remoteServices.requestMarketDataQuotes(marketDataQuotes),
remoteServices.requestSubscribe(subscription),
/*Observable.fromArray(remoteServices.requestInstrumentById(instrumentById)),
Observable.fromArray(remoteServices.requestMarketDataQuotes(marketDataQuotes)),
Observable.fromArray(remoteServices.requestSubscribe(subscription)),*/
Function3<List<InstrumentByIdResponse>, MarketDataQuotesResponse, SubscribeResult, DetailsModel>
{ instrumentByIdResponse, marketDataQuotesResponse, subscribeResponse ->
createDetailsModel(instrumentByIdResponse, marketDataQuotesResponse, subscribeResponse)
})
}
private fun createDetailsModel(instrumentByIdResponse: List<InstrumentByIdResponse>, marketDataQuotesResponse: MarketDataQuotesResponse, subscribeResult: SubscribeResult): DetailsModel {
return DetailsModel(instrumentByIdResponse, marketDataQuotesResponse, subscribeResult)
}
data class DetailsModel(
val instrument: List<InstrumentByIdResponse>,
val marketDataQuotes: MarketDataQuotesResponse,
val subscribe: SubscribeResult)
RemoteService :
fun requestInstrumentById(instrumentById: InstrumentById) = ApiService.requestInstrumentById(instrumentById)
APIService :
#Headers("Content-Type: application/json")
#POST("search/instrumentsbyid")
fun requestInstrumentById(#Body instrumentById: InstrumentById): Observable<BaseResponse<List<InstrumentByIdResponse>>>
API Structure
Error that i get on Zip Operator