Parse Server Android SDK query retrieves list of empty values - android

I am using self hosted Parse server (Using Ubuntu Server). For my Android app, have following dependencies,
****compile 'com.parse.bolts:bolts-tasks:1.3.0'
compile 'com.parse:parse-android:1.13.1'****
I am able to save the data in cloud. The problem is when I try to retrieve the data its giving list of data (eg. list of 10 objects). But its fields didn't have the actual value that I have saved. Its shows the default value of the field type (eg. String = null, int = 0, double = 0.0)
Example Saving Data
Rich {
String name = "UserName",
int age = 22,
double weight = 58
}
Example Retrieved Data
[
Rich {
name = null,
age = 0,
weight = 0.0
},
...
...
]
I am querying as follows
ParseQuery<ParseObject> query = ParseQuery.getQuery("Rich");
List list = query.find();
If you guys know about the issue, please tell me what I am doing wrong.
Thanks in advance.

Related

Unable to fetch the list column of AWS DynamoDB in Android Kotlin

I am developing an Android application using Kotlin and AWS DynamoDB. I am new to both technologies. What I am doing now is I am trying to scan data from a table of DynamoDB. I know how to scan it. But the problem is that one of the column has List data type.
I have a table called item with the following columns.
Note in particular the Images field.
In Kotlin Android, I scan the table like this.
val dynamoDBClient = AmazonDynamoDBClient(AWSMobileClient.getInstance().credentialsProvider)
val fetchedItems: ArrayList<Any> = ArrayList();
val scanRequest = ScanRequest().withTableName(MainApplication.DB_TABLE_ITEMS);
scanRequest.exclusiveStartKey = lastEvaluatedKey
val scanResult = dynamoDBClient.scan(scanRequest)
scanResult.items.forEach { item ->
Log.i("ITEM_NAME", item.get("Name")?.s)
val viewItem = ItemDO()
viewItem.id = item.get("Id")?.s
viewItem.description = item.get("Description")?.s
viewItem.name = item.get("Name")?.s
viewItem.userId = item.get("UserId")?.s
viewItem.images = item.get("Images")?.ns
fetchedItems.add(viewItem)
Log.i("IMAGES_COUNT", item.get("Images")?.ns?.size.toString())
}
But this
item.get("Images")?.ns
always return null even if the data exists in the column as in the screenshot below.
Why my code is not fetching the list data type but others?
The code looks good and should be returning data for all the attributes irrespective of their type. I have equivalent piece of code in java that works as expected. Can you try inspecting the value returned by item.get("Images") before making the null-safe call. Type of the value returned by item.get("Images") is AttributeValue and so there is a possibility that the value gets lost in the course of implicit type conversion.

Query Data from Google Spreadsheet in Android

I am trying to query data form Google Spreadsheet available to be read by anyone with the Read Only link.
I implemented this Quickstart solution but here is what I need:
Access data just with URL, no authentication needed
Query item in column A and get value in column B
No need for updating any data
I tried constructing queries like:
http://spreadsheets.google.com/tq?tq=SELECT%20*%20WHERE%20A=C298732300456446&key=2aEqgR1CDJF5Luib-uTL0yKLuDjcTm0pOIZeCf9Sr0wAL0yK
But all I get is:
/*O_o*/
google.visualization.Query.setResponse(
{
"version": "0.6",
"reqId": "0",
"status": "error",
"errors": [
{
"reason": "invalid_query",
"message": "INVALID_QUERY",
"detailed_message": "Invalid query: NO_COLUMN: C298732300456446"
}
]
}
This comes when the data is actually present in the sheet in column A with value C298732300456446.
What can I do for getting the data, without any authentication from my spreadsheet?
I am not sure if this can be done. If fine, I can suggest an alternative solution. You can try writing a Google App script like:
function doGet(e) { return getInfo(e); }
function doPost(e) { return getInfo(e); }
function getInfo(request) {
var someValueFromUrl = request.parameter.value;
var requiredValue = "";
var sheet = SpreadsheetApp.openById("spreadsheet_id");
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
Logger.log("Reading row num: " + i);
if(data[i][0] == someValueFromUrl) {
requiredValue = data[i][1];
break;
}
}
Logger.log(requiredValue);
return ContentService.createTextOutput(JSON.stringify(requiredValue));
}
This way, you can publish this script as web app and call it using an URL which will be obtained when you publish this script.
Call the script like:
https://script.google.com/macros/s/obtained_url/exec?value=1234
If key is found, you will get the String response as:
"value"
I hope this helps.
C298732300456446 needs to be put within single quotes.
So you need to enclose C298732300456446 as %27C298732300456446%27
Your'e modified query would be
http://spreadsheets.google.com/tq?tq=SELECT%20*%20WHERE%20A=%27C298732300456446%27&key=2aEqgR1CDJF5Luib-uTL0yKLuDjcTm0pOIZeCf9Sr0wAL0yK
I'm unable to test this though - looks like you've removed/removed access from this spreadsheet.

Looping out JSON Array using ArrayList

I am trying to learn retrofit and I have made successful attempts at posting data and now I am trying to retrieve JSON array which looks as follows:
{
"result": "success",
"message": "All Questions Have Been Selected",
"question": {
"all_question_ids": ["1","2","3"]
}
}
I am using the following getter
public ArrayList getAll_question_ids(){
return all_question_ids;
}
I am retrieving using Retrofit as follows
if (resp.getResult().equals(Constants.SUCCESS)) {
SharedPreferences.Editor editor = pref.edit();
Log.d("Question_IDs", "getAllQuestionID() = " + response.body().getQuestion().getAll_question_ids() );
editor.putString(Constants.All_QUESTION_IDS,((resp.getQuestion().getAll_question_ids().toString())));
editor.apply();
}
progress.setVisibility(View.INVISIBLE);
It is here that I am stuck, as I am retrieving the array ok but I am unsure how to loop out the Array which is now stored in Shared Preferences.
When I place a toast to show me how the IDs are coming across, my toast confirms the data as [1,2,3]
The goal is to add a dynamic button and the individual ID, i.e button 1, button 2 etc every-time the loop is iterated.
I have tried the following:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
for (int i =0; i < questionNumber.length(); i++) {
try {
/*Dynamically create new Button which includes the question name
*/
AppCompatButton btn_question = new AppCompatButton(getActivity());
/*LayoutParams (int width, int height,float weight)
As LayoutParams is defaulted in px, I have called a method called dpToPX to make sure
the dynamically added EditText is the same size on all devices.
*/
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dpToPx(280), dpToPx(45), 1);
btn_question.setBackgroundColor(Color.parseColor("#3B5998"));
btn_question.setTextColor(Color.WHITE);
// btn_question.setText(String.valueOf(x));
btn_question.setText("Question "+ pref.getString(Constants.All_QUESTION_IDS,""));
btn_question.setGravity(Gravity.CENTER);
//generate unique ID for each new EditText dynamically created
View.generateViewId();
//Log.d("TEST VALUE", "Question1 generated ID = " + btn_question.generateViewId());
params.setMargins(0, dpToPx(10), 0, dpToPx(10));
btn_question.setPadding(0, 0, 0, 0);
btn_question.setLayoutParams(params);
allEds.add(btn_question);
mLayout.addView(btn_question);
} catch (Exception e) {
Log.d(TAG, "Failed to create new edit text");
}
}
However the above is adding the value as it appears in the array e.g [1,2,3] which is obviously not what I want.
I have added a photo in case my explanation isn't clear. I want a button with 1 number added to it each time the loop iterates but I am unable to figure this out.
I have looked through lots of resource but cannot find an answer that is relevant to my problem, although, if there is, I am not familiar enough to recognise a similar issue.
If someone can offer some assistance, I would appreciate it!
When you call editor.putString(Constants.All_QUESTION_IDS,((SOMETHING.toString())));, what is actually stored depends on the implementation of the toString method in the type of SOMETHING (in this case String[]). So avoid doing that. Instead, since you're already using Gson or Jackson (or others), store the question_idsas JSON:
final String jsonIds = gson.toJson (resp.getQuestion().getAll_question_ids());
editor.putString(Constants.All_QUESTION_IDS, jsonIds);
Your actual stored value no longer depends on the implementation of something that you don't control (String[].toString). It is a valid JSON array and regardless of what tool/library you use to read it back, it's valid.
Now, to read back the stored data:
final String storedJson = pref.getString(Constants.All_QUESTION_IDS, null);
if (null == storedJson) {
// TODO: No question ids found
}
final String[] ids = gson.fromJson (storedJson, String[].class);
for (int i = 0; i < ids.length; i++) {
// make your buttons
}
This is a problem of saving and then reading out a List of items (in this case, String instances).
You've chosen to save the list by calling editor.putString() with a value of getAll_question_ids().toString(). That toString() call is going to return a string representation of your list, or, in other words, a String instance with the value [1, 2, 3]. At this point, you no longer have a List proper, but a String that looks like a list.
This is all technically fine, but it means you have to take this into account when you're trying to read out that list.
You've written this to read the list back out:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
Once this line executes, questionNumber will be a String instance with the value [1, 2, 3]. Again, this is fine, but now we come to the key point: we have to convert this String back into a List.
If you know for sure that the values in this list won't have commas in them, you can do it easily:
Trim the braces off the string using substring()
Create a String[] using split()
Convert your array to a list using Arrays.asList() (you could even skip this step since iterating over an array is just as easy as iterating over a list)
Put that together and you get:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
questionNumber = questionNumber.substring(1, questionNumber.length() - 1);
String[] array = questionNumber.split(", ");
List list = Arrays.asList(array);
At this point, you can iterate over your array or list:
for (String value : list) {
...
btn_question.setText("Question " + value);
...
}

Android Importing Raw JSON into Database without a lot of coding

I have a sql lite database in my android project that gets fed its data from a web service giving JSON. The JSON is straight forward, no tags. It simply has the rows of table data in the same field order as the table in the database.
JSON
[["123","ny","45"],
["456","nj","76"],
["778","ca","33"]]
SQL Lite Customer Table CustomerID,State,NumofItems
How can I import this into the database without the overhead of creating classes for each table etc.. some tables have over 50 fields.
I am using Xamarin if it somehow makes things easier
It depends upon what you mean by without a lot of coding and how many rows you are populating ;-)
Using dynamics and Json.Net you can use DeserializeObject to obtain an array of dynamics and loop through those array elements and construct a SQL Insert statement bypassing column names and class/model definitions of each table... Using dynamics is slower but unless you are populating a hundred thousand rows every import/app launch/.... this works fine...
This is how I am populating a bunch of tables in a case very much like yours to import numeric sequences for drawing SparkLines within RecyclerView/CardViews, I removed the error checking to simplify the answer:
Batteries_V2.Init();
var sqlConn = new SQLiteConnection("foobar.db");
sqlConn.CreateCommand("create table Customer (CustomerID INT PRIMARY KEY NOT NULL, State TEXT NOT NULL, NumofItems INT NOT NULL)").ExecuteNonQuery();
var jsonString = #"
[[""123"",""ny"",""45""],
[""456"",""nj"",""76""],
[""778"",""ca"",""33""]]"
;
dynamic jsonResponse = JsonConvert.DeserializeObject(jsonString);
sqlConn.BeginTransaction();
foreach (var item in jsonResponse)
{
string aBunchOfValues = "";
var noOfColumns = item.Count;
for (int i = 0; i < noOfColumns; i++)
{
var isString = !((string)item[i]).TryParse(out float n);
aBunchOfValues += $"{(isString ? '"' : ' ')}{item[i]}{(isString ? '"' : ' ')} {(i < noOfColumns - 1 ? ',' : ' ')}";
}
var sqlInsertString = $"INSERT INTO Customer VALUES ({aBunchOfValues});";
sqlConn.CreateCommand(sqlInsertString).ExecuteNonQuery();
}
sqlConn.Commit();
Note: This is using FKrueger's sqlite-net to provide the SQLiteConnection, CreateCommand and the transaction, this is on top of ESink's SQLitePCL.raw, adjust accordingly...

Realtime database get name and value

i am using firebase real-time database.
there is the user name like - user1 and then some supplies he requested like the supplies name - markers and then the quantity - like 5.
this is my JSON file
{
"Users" : {
"User1" : {
"Markers" : 5,
"Scissors" : 1,
"Staplers" : 4
},
"User2" : {
"Markers" : 2,
"Scissors" : 5,
"Staplers" : 3
}
}
}
i want to get back the supplies whan i ask for in the format of:
markers 5
scissors 1
Staplers 4
the information comes out via a listview but i don't know how to get via the listview both name and quantity, i can get only one of them.
The code i am using to get only the names is:
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getKey());
}
and the code i am using to get only the quantity is:
// two first lines are the same
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getValue().toString());
}
Try something like this instead:
for (DataSnapshot supply : dataSnapshot.getChildren()) {
String key = supply.getKey();
String value = supply.getValue();
}
Also, you could have just saved i.next() to a variable, then you can access the key and value within the same loop without calling additional i.next() (which I presume is what the question is about).
i have changed the script to this one
key = (((DataSnapshot) i.next()).getKey());
value = ((dataSnapshot).child(key).getValue().toString());
set.add(key+" "+value);
it works very good, thanks any way.

Categories

Resources