How can I call the access_role in OrganizationAccess ?
This is the classes
User
class User : Serializable {
var id = ""
var user_organization_accesses: ArrayList<OrganizationAccess>? = null
}
OrganizationAccess
class OrganizationAccess:Serializable {
var access_role = ""
}
What I have tried
mUser = intent.getSerializableExtra(ARG_PARAM) as User // receive from previous activity
longToast("Role is " + mUser.user_organization_accesses!!.xxx)
What should I write for the xxx ?
I have solved it
longToast("Role is " + mUser.user_organization_accesses!!.component1().access_role)
Related
//MovieList function Defination
private fun getMovieList(): GraphQLRequest<MovieDBFinal2> {
val document = ("query getMovieList { "
+ "listMovieDBFinal2s(limit: 1000, filter: {Genre1: {eq: \"Animation\"}}) { "
+ "nextToken "
+ "items { "
+ "IMDB_title "
+ "} "
+ "} "
+ "} ")
return SimpleGraphQLRequest(
document,
Collections.emptyMap(),
TypeMaker.getParameterizedType(QueryResponse::class.java, MovieDBFinal2::class.java),
GsonVariablesSerializer())
}
internal class QueryResponse<T> {
private val listMovieDBFinal2s: QueryList<T>? = null
val moviesList: QueryList<T>?
get() = listMovieDBFinal2s
}
internal class QueryList<T> {
val items: Iterable<T>? = null
val nextToken: String? = null
}
//MovieList function call
Amplify.API.query(
getMovieList(),
{ response ->
if (response.hasData()) {
Log.e("MovieList", "$response")
}
},
{ failure ->
Log.e("MovieList", "Query failed.", failure)
}
)
I tried this type in my schema not working.Github issue
PaginationResult not working.Iterable also not giving any token. Only solution is String.class but that is difficult to serialize. The workaround is make the same request two times once with PaginationResult passing the nextToken as input and second make the same request with string.Class type.
This is my first post on StackOverflow, so please don't kill me for my poor formatting.
I'm trying to make a Work Tracker App, which logs your time of arrival and time of leave in a MySQL database when you press the button in the app.
I want the app to open the correct (is working / is not working) screen when you launch the app, and I kinda managed to make it work with shared preferences, but I figured it would be more reliable if it would request the status from the database.
The table holding the logs looks like this:
user_id | time_of_arrival | time_of_leave
if the user is still in work, there will be a row where he has time_of_arrival, but the time_of_leave field is NULL.
That's what I want to request here:
private fun checkWorking(
sharedPreferences: SharedPreferences,
localContext: Context
) : Boolean {
val userId = sharedPreferences.getString("userId", "").toString()
var isWorking = false
if (userId != "") {
val handler = Handler(Looper.getMainLooper())
handler.post {
val field = arrayOfNulls<String>(1)
field[0] = "user_id"
val data = arrayOfNulls<String>(1)
data[0] = userId
val putData = PutData(
Database().host + Database().databaseName + "checkWorking.php",
"POST",
field,
data
)
if (putData.startPut()) {
if (putData.onComplete()) {
val result = putData.result
if(result == "You are working") {
isWorking = true
}
}
}
}
}
return isWorking
}
here is the php part:
<?php
require "DataBase.php";
$db = new DataBase();
if ($db->dbConnect()) {
if($db->checkWorking("logs", $_POST['user_id'])) {
echo "Success";
} else echo "Failure";
}
?>
and
function checkWorking($table, $userId) {
$userId = $this->prepareData($userId);
$this->sql = "SELECT * FROM " . $table . " WHERE user_id = '" . $userId . "' AND time_of_leave IS NULL";
$result = mysqli_query($this->connect, $this->sql);
if(mysqli_num_rows($result) != 0) {
return true;
}
return false;
}
(The PHP part works correctly, I just wanted to give full insight about my problem)
My problem is that it always returns false, because I read somewhere that the return finishes faster than the handler.post changing the isWorking variable to true.
How can I fix this issue, I legitimately can't figure out anything else I could try.
Thanks in advance!
yes, the return statement is being called before the handler is done since it will be working on a different thread while the return is still on the main thread.
So, you can solve that by using an interface to return the callback whenever it has been received, first you create the interface as follows:
public interface CallbackListener<T> {
void onSuccess(T response);
}
then you have to modify you method to take this interface as a parameter
private fun checkWorking(
sharedPreferences: SharedPreferences,
localContext: Context,
callback: CallbackListener<Boolean>) {
val userId = sharedPreferences.getString("userId", "").toString()
var isWorking = false
if (userId != "") {
CoroutineScope(IO).launch { //running code on background thread
val field = arrayOfNulls<String>(1)
field[0] = "user_id"
val data = arrayOfNulls<String>(1)
data[0] = userId
val putData = PutData(
Database().host + Database().databaseName + "checkWorking.php",
"POST",
field,
data
)
if (putData.startPut()) {
if (putData.onComplete()) {
val result = putData.result
withContext(Main) {//returning to main thread
if (result == "You are working") {
callback.onSuccess(true)
} else
callback.onSuccess(false)
}
}
}
}
I used kotlin Coroutines here instead of handler, but it can be applied to both of them.
then you can call your new method as follows:
checkWorking(
sharedPreferences,
context,
object: CallbackListener<Boolean>{
override fun onSuccess(response: Boolean?) {
//insert your logic here
}
}
)
I am trying to convert one Android Firestore project from java to kotlin. But got stuck in pagination part, where startAfter(DocumentSnapshot) with java code is working fine. But the kotlin one is giving only first 3 result. StartAfter(DocumentSnapshot) part is not working.
If you could please point out where am i going wrong in Kotlin,it would be very helpful.
This is the java code which is working perfectly
public void loadNotes(View v) {
Query query;
if (lastResult == null) {
query = notebookRef.orderBy("priority")
.limit(3);
} else {
query = notebookRef.orderBy("priority")
.startAfter(lastResult)
.limit(3);
}
Log.d(TAG, "loadNotes: "+ query);
query.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
String data = "";
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Notee note = documentSnapshot.toObject(Notee.class);
note.setDocumentId(documentSnapshot.getId());
String documentId = note.getDocumentId();
String title = note.getTitle();
String description = note.getDescription();
int priority = note.getPriority();
data += "ID: " + documentId
+ "\nTitle: " + title + "\nDescription: " + description
+ "\nPriority: " + priority + "\n\n";
}
if (queryDocumentSnapshots.size() > 0) {
data += "___________\n\n";
textViewData.append(data);
lastResult = queryDocumentSnapshots.getDocuments()
.get(queryDocumentSnapshots.size() - 1);
}
}
});
}
And this is the Kotlin one,which is not working.
private fun loadNotes() {
val query = if (lastResult == null) {
notebookRef
.orderBy("priority")
.limit(3)
} else {
Log.d(TAG, "loadNotes: ${lastResult!!.id}")
notebookRef
.orderBy("priority")
.startAfter(lastResult)
.limit(3)
}
Log.d(TAG, "loadNotes: $query")
query.get()
.addOnSuccessListener { QuerySnapshot ->
var text = ""
for (queryDocumentSnapshot in QuerySnapshot) {
val note: Note = queryDocumentSnapshot.toObject(Note::class.java)
note.docID = queryDocumentSnapshot.id
val title = note.title
val description = note.description
val priority = note.priority
text += "ID: ${note.docID} \n Title : $title\n Description :$description\n" +
"Priority :$priority \n"
}
if (QuerySnapshot.size() > 0) {
text += "---------------\n\n"
textView_data.append(text)
lastResult = QuerySnapshot.documents[QuerySnapshot.size() - 1]
}
}
}
Hope to get some help
Thanks
Required codes for testing : JavaActivity KotlinActivity Note Model and activity_main.xml
Well, after suffering the same issue. It was solved by using the non-null cast (!!). For example:
val query = transactionsCollection
.orderBy(Field.CREATED, Query.Direction.DESCENDING)
.startAfter(lastDocument!!)
.limit(PAGE_SIZE)
In your case it would be:
query = notebookRef.orderBy("priority")
.startAfter(lastResult!!)
.limit(3);
with that it is working on Kotlin.
You have to implement it diferently in Kotlin. instead of keeping a reference to the last result you have to keep a reference to the query you create with the lastResult.
remove the global lastResult and replace it with:
private var query: Query? = null
then implemente the LoadNotes like this:
private fun loadNotes() {
if(query == null){
query = notebookRef.orderBy("priority").limit(3)
}
query!!.get().addOnSuccessListener { QuerySnapshot ->
var text = ""
for (queryDocumentSnapshot in QuerySnapshot) {
val note: Note = queryDocumentSnapshot.toObject(Note::class.java)
note.docID = queryDocumentSnapshot.id
val title = note.title
val description = note.description
val priority = note.priority
text += "ID: ${note.docID}\nTitle: $title \nDescription: $description"+
"\nPriority: $priority\n"
}
if (QuerySnapshot.size() > 0) {
text += "---------------\n\n"
textView_data.append(text)
val lastResult = QuerySnapshot.documents[QuerySnapshot.size() - 1]
query = notebookRef.orderBy("priority").startAfter(lastResult).limit(3)
}
}
}
the last 2 lines is what makes it work. Honesty, i still dont understand why it does not work like in Java, but at least this implementation works. The firebase documentation also recomends to implement it like this.
Your code works as expected. There's no difference between what you're doing in Kotlin from java. You specified the limit to be 3 in both cases.
If there's anything wrong it will be on your logic.
I have a model named Item. the model has linkingObjects to model ItemModifier. The Question is, why do I have to query for it to return a result ?
open class Item() : RealmObject() {
#PrimaryKey
var id: String = ""
#LinkingObjects("item")
val itemModifiers: RealmResults<ItemModifier>? = null
}
var item = Item()
item.id = UUID.randomUUID().toString()
realm.copyToRealmOrUpdate(itemModifier)
var itemModifier = ItemModifier()
itemModifier.id = UUID.randomUUID().toString()
itemModifier.item = item
realm.copyToRealmOrUpdate(itemModifier)
for (itemModifier in item.itemModifiers) { // this returns nullOrEmpty.
Log.e("test", itemModifier.id)
}
queriedItem = Realm.getDefaultInstance().where(Item::class.java).equalTo("id", item.id).findFirst()!!
for (itemModifier in queriedItem.itemModifiers) { // this return itemModifier.
Log.e("test", itemModifier.id)
}
Firstly, I assume the first realm.copyToRealmOrUpdate(itemModifier) is a typo and should be realm.copyToRealmOrUpdate(item).
Having done this the item you created (an unmanaged object) has now been copied into the realm, but the reference you hold is still to the unmanaged object. This is why a look at its linking objects field gives you an empty list. Whereas, as you have shown, retrieving the managed object via query gives you the result you expect.
Note that according to the docs (here), the copyToRealmOrUpdate method returns a reference to the managed object, so you could use that immediately and you should get the correct result. E.g.:
var item = Item()
item.id = UUID.randomUUID().toString()
val managedItem = realm.copyToRealmOrUpdate(item)
var itemModifier = ItemModifier()
itemModifier.id = UUID.randomUUID().toString()
itemModifier.item = managedItem
realm.copyToRealmOrUpdate(itemModifier)
for (itemModifier in managedItem.itemModifiers) { // this should now work.
Log.e("test", itemModifier.id)
}
I created a quiz like app where 10 questions are fetched once. If user got 8 marks out of 10. then I fetch next 10 questions. But startAfter always give the same response.
val questionCollectionRef = db.collection("questionCollection")
///.whereArrayContains("tags", tagName)
.orderBy("questionID", Query.Direction.DESCENDING);
val id = SharedPrefs(this#McqActivity).read(OLD_DOCUMENT_ID, "")
if(id.isNotEmpty()){
//questionCollectionRef.whereLessThan("questionID",id) //also tried for whereGreaterThan
questionCollectionRef.startAfter(id);
Log.v("startAfter","start After : " + id + "" );
}
questionCollectionRef.limit(10).get()
//fixme also orderBy date So user can see latest question first
.addOnSuccessListener { querySnapshot ->
if (querySnapshot.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY")
} else {
val questionList = querySnapshot.toObjects(QuestionBO::class.java)
questionList.forEach { questionItem ->
resultList.add(ResultBO(questionItem))
}
if (resultList.size > 0) {
refreshQuestionWithData()
}
}
}
.addOnFailureListener { exception ->
exception.printStackTrace()
}
This code is written in Activity.After getting score above than 8 .
I open the same activity again and questionCollectionRef.startAfter called but still same question shown in Activity
When you call startAfter() (or any other query building methods), it returns a new query object. So you need to keep a reference to that object:
var questionCollectionQuery = db.collection("questionCollection")
.orderBy("questionID", Query.Direction.DESCENDING);
val id = SharedPrefs(this#McqActivity).read(OLD_DOCUMENT_ID, "")
if(id.isNotEmpty()){
questionCollectionQuery = questionCollectionQuery.startAfter(id);
Log.v("startAfter","start After : " + id + "" );
}
questionCollectionQuery.limit(10).get()...
I also renamed questionCollectionRef to questionCollectionQuery, since the type after orderBy, startAfter or limit is a query.