Error : java.lang.IllegalArgumentException: invalid type for ParseObject: class org.json.JSONObject
I have moved parse server on "centOS" and also database from parse.com to mangoDB. I'm getting Above error when I make below request from my android app.
Note : I'm using android parse sdk(v1.13.1)
I have tried to add jsonObject as arraylist using addAllUnique() method because I have to store jsonObject as datatype of "array" in parse database.
Below i share my code :
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("__type", "Pointer");
jsonObj.put("className", className);
jsonObj.put("objectId", objectId);
} catch (JSONException e1) {
e1.printStackTrace();
}
ParseUser user = ParseUser.getCurrentUser();
user.addAllUnique("Keyword",Arrays.asList(jsonObj));
user.saveInBackground();
I have also tried user.addAll() method insted of addAllUnique() but it's also not working.
Please help me to resolve this. Thanks
You can try something like this instead of JSON Object.
List<ParseObject> pointerList = new ArrayList<>();
pointerList.add(ParseObject.createWithoutData("YourClassName", "yourobjectId"));
pointerList.add(ParseObject.createWithoutData("YourClassName", "yourobjectId"));
...
user.addAllUnique("keyWord", pointerList);
user.saveInBackground();
Haven't tested the code yet. But technically, it should work.
Hope this helps :)
Related
I have an ordering app, I am using SQLite to store what the user has added to it's cart. My problem is that how would I be able to upload all the data in the SQLite database to the server.
So for say, when the user presses the ORDER button, it will upload all the data in the SQLite to the databse.
I am doing this so that the person who will be delivering can retrieve and view the order details of the user, but I am just baffled and stuck on how would I be able to approach or do this.
If anyone has any insight or links that could give me an idea, or maybe provide me an alternative approach it would be great. Thanks in advance everybody! :D
WELL I SOLVED MY PROBLEM and this is my Solution for anyone who needs it!
Cursor data = db.getCartItems();
TotalOrderArray = new JSONArray();
data.moveToFirst();
while(data.isAfterLast() == false)
{
int totalColumn = data.getColumnCount();
TotalOrderObject = new JSONObject();
for (int i = 0; i < totalColumn; i++)
{
try {
TotalOrderObject.put(data.getColumnName(i), data.getString(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
TotalOrderArray.put(TotalOrderObject);
data.moveToNext();
}
data.close();
it gets all of the data in the SQLite database as JSON and then I just upload it to the server. Thanks to everyone who helped!
Step 1: Just fetch the data from SQLite database.
Step 2: Encode this data to JSON format.
eg:-
ArrayList<Product_bean > all_product_list = db.getAllProductInCart(cart_id); // here get the products
JSONArray jarray = new JSONArray();
JSONObject product;
for(Product_bean bean : all_product_list){
product = new JSONObject();
product.put("product_id",bean.getP_id());
......
}
jarray.put(product);
jarray is your request jSON.
Step 3: Send the JSON to your Http... url.
Like the title , my json str sometimes like this:
{
"data": {
"changebaby": "no change",
"changemama": {
"mamacontext": "mama is a good mama",
"mamaico": "",
"mamatitle": "mama"
}
}
}
sometimes it like this:
{
"data": {
"changebaby": "no change",
"changemama": "no change"
}
}
as you see,the value of the "changebaby" key and the "changemama" key sometimes is a String, sometimes is a object, how should i parse it by gson? Could anybody help me?
Don't use the android api to parse the json string, need to use the gson lib of google to parse the json string, could anybody help me?
if(jsonObject.optJSONObject("changemama") != null)
{
JSONObject changemama=jsonObject.optJSONObject("changemama");
//Its JSON object, do appropriate operation
}
else if(jsonObject.optString("changemama") != null)
{
//Its string, do appropriate operation
}
if you have more number of possibilities like boolean or int or long, refer this
optJSONObject
Returns the value mapped by name if it exists and is a JSONObject, or
null otherwise.
Or go with the way lawrance has given : Determine whether JSON is a JSONObject or JSONArray
Try with this :
JSONObject changemama=jsonObject.optJSONObject("changemama");
if(changemama== null){
String str=jsonObject.optString("changemama");
}
Try this code.
JSONObject data;
try {
data = jsonObj.getJSONObject("changemama");
// do stuff
} catch (JSONException e) {
data = jsonObj.getString("changemama");
// do stuff
}
try this :
if(obj.has("changemama")){
if(obj.optString("changemama").length() > 0){}
else if(obj.optJSONObject("changemama").length() > 0){}}
To simplyfy android development, we can ask for the backend developers to change the Mobile API.The new API could returen the json string that cann't change the value.The value of all keys cann't sometimes be a string, sometimes a object.
I am trying to retrieve a new column called "address" I created in Parse User in my android app. But it returns me nullPointerException error and returns me nothing although I filled the address in the table.
This link only shows the way to store your custom field in the user table but I need to retrieve what I stored there.
This is my code:
ParseUser pUser = ParseUser.getCurrentUser();
userAddress.setText(pUser.getString("address").toString());
I tried get("address") as well but still it returns me nothing. Is there something I'm missing here?
Alright, I found the answer on my own. It turns out that Parse caches the ParseUser.getCurrentUser() object locally and the reason I wasn't able to get the data from server was because I changed the data on server and the client cache wasn't updated.
I was able to fix this by fetching the ParseUser object from the server:
ParseUser.getCurrentUser().fetchInBackground();
and then after the object is retrieved from the server I was able to get the address field on my client.
You need to call it using a Query, then display it in a textView/editText. Try the following:
final ParseQuery<ParseObject> address = ParseQuery.getQuery("//Class Name");
address.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject reqAdd, ParseException e) {
if (address != null) {
Log.d("quizOne", "Got it");
//Retrieve Age
String //CreateNewString = reqAdd.getString("//Column name");
TextView //textView Name = (TextView) findViewById(R.id.//textView ID);
//textViewName.setText(//StringName);
Toast.makeText(getApplicationContext(),
"Successfully Recieved Address",
Toast.LENGTH_LONG).show();
} else {
Log.d("//EnterName", "//Enter Error Message");
Toast.makeText(getApplicationContext(),
"Can't receive address", Toast.LENGTH_LONG)
.show();
}
}
});
Short answer: that user probably just doesn't have an address set.
Long answer: your code snippet will throw exceptions often, and you should expect and handle those, or use tests to avoid throwing them.
Read this page: http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException
Key example/excerpt:
Object obj = null;
obj.toString(); // This statement will throw a NullPointerExcept
So pUser.getString("address") appears correct. But calling .toString() on the result requires you to be try/catching the exception. Maybe do
ParseUser pUser = ParseUser.getCurrentUser();
if (pUser.getString("address") != null) {
userAddress.setText(pUser.getString("address"));
}
BTW, I believe the error is "nullPointerException" fyi! :)
I am creating an app which will tell the weather condition of a city using the OpenWeatherMap.org api. In this app I let user to write a city name and the data will be fetched from the web. But what if the user entered wrong city.
For example if a user entered Lomdon instead of London.
What should I do in that case. The Api I am using is
"http://api.openweathermap.org/data/2.5/weather?q="+city name
Thanks in advance for the help, I am new to android development.
If the city is incorrect your API returns an error message. You can check it like this:
"http://api.openweathermap.org/data/2.5/weather?q=Lomdon"
try {
String msg = jsonObject.getString("message");
if (msg.equalsIgnoreCase("Error: Not found city")) {
Log.e("TAG", "City not found");
} else {
// Use the data
}
} catch (JSONException e) {
e.printStackTrace();
}
The reason I didn't use cod which looks like the return code, is that if the city is found cod is an int and if it's not found it's a string. Kind of misleading to design the JSON like that.
I want to read json attribute value, my json format like this
{"content":{"#attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}},
I want to read total_record's value from json attributes. How can I read ? Please help me
Thanks
John Rick
First of all check your JSON String.Change it to
{"content":{"#attributes" : { "start_limit" :"x","end_limit" : "x","total_records" : "x"}},"item":[{"category":"x","distance':"x"}]}} from
{"content":{"#attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}}
In which you left one closing curly brace before "item".
Now below is the code to get value of "total_records"
String jsonString = "{'content':{'#attributes' : { 'start_limit' :'x','end_limit' : 'x','total_records' : 'x'}},'item':[{'category':'x','distance':'x'}]}}";
public String getTotalRecords(String jsonString){
try {
JSONObject mainObject = new JSONObject(jsonString);
JSONObject contentObject = mainObject.getJSONObject("content");
JSONObject attributesObject = contentObject.getJSONObject("#attributes");
String totalRecords = attributesObject.getString("total_records");
Log.i("Total Records", totalRecords);
} catch (JSONException e) {
e.printStackTrace();
}
return totalRecords;
}
Hope you understand the problem.
Simply use JSONObject.
JSONObject obj = new JSONObject(src);
String totalRecs = obj.getString("total_records");
Not 100% sure it works, but it is a good example where to start.
Hope you've already given it a try before asking in SO. If not, here are a few urls (which I googled):
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/ and http://about-android.blogspot.com/2010/03/androind-json-parser.html