jsonObject.getString("String in UTF8" ) giving blank - php

I am fetching a string from my MySql DB on and online server using webservice in JSON format.
I am able to see that Android Studio is fetching it correctly as I see it in debugging mode.
But when I go ahead and add it to a List list, I get nothing.
Here's some more info:
What I am getting:
{"products":[{"veg_name_eng":"Corn","veg_name_hindi":"मक्का"}],"success":1}
My concern is with: "veg_name_hindi":"मक्का"
When I go ahead and try to put it in a dataitem list, I get nothing:
public static List<DataItem> dataItemList;
dataItemList.add(jsonObject.getString(veg_name_eng),jsonObject.getString(veg_name_hindi))
veg_name_eng and veg_name_hindi are the column names at my table.
After the above code I get dataItemList = null, So nothing is adding to it.
In my server side MySql DB, I am using UTF-8 encoding.
I am using android studio.
UPDATE 1:
I am parsing the JSON as :
JSONObject jsonObject = new JSONObject(myJSONString);
veg_list = jsonObject.getJSONArray("products");
try {
while (TRACK < veg_list.length()) {
JSONObject jsonObject = veg_list.getJSONObject(TRACK);
addItem(new DataItem(jsonObject.getString(veg_name_eng), jsonObject.getString(veg_name_hindi)));
TRACK = TRACK + 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
// and the addItem function is as follows:
private static void addItem(DataItem item) {
dataItemList.add(item); //While Debugging, I can see that value of item is correct. (i.e., item: DataItem{veg_name_eng='Cork', veg_name_hindi='मक्का'} )
dataItemMap.put(item.getVeg_id(), item);
}

Firstly, Make a model of the your JSON String using
http://json2java.azurewebsites.net/
and then map your JSON String to your Model using Gson. It's much easy to use.
Another way to get your required String for this particular result is parse json string yourself.
For Example :
String vegNameEng,vegNameHindi;
vegNameEng = vegNameHindi = "";
try{
JSONObject obj = new JSONObject(yourJsonString);
JSONArray arr = obj.getJSONArray("products");
vegNameEng = arr.getJSONObject(0).getString("veg_name_eng");
vegNameHindi = arr.getJSONObject(0).getString("veg_name_hindi");
}catch(JSONException ex){
}
Now vegNameEng and vegNameHindi have the required data.

I figured out, It was a silly mistake, the variable I was using to put data into the database was overwritten by some other variable with the same name. Closing the thread for now. Thanks #Umer-Farooq.

Related

How to send JSON Array output from android studio to PHP

The code below gets all the rows in my Android SQLite database and covert it to JSON Array. Now I want to get the JSON Array using PHP to store it to my online database. What should I do? Please help.
This is the code that I use:
private JSONArray getResults()
{
String myPath = this.getDatabasePath("cart.db").toString();// Set path to your database
String myTable = CartContract.CartEntry.TABLE_NAME;//Set name of your table
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
Log.d("TAG_NAME", cursor.getString(i) );
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("FINAL RESULT", resultSet.toString() );
return resultSet;
}
This is the output:
FINAL RESULT: [{"id":"1","food_id":"52","food_price":"30","food_name":"Pink Lemonade","quantity":"5","amount":"150","special_request":""},{"id":"2","food_id":"51","food_price":"30","food_name":"House Blend Iced Tea","quantity":"3","amount":"90","special_request":""}]
and I want to put these values here: (online database)
attached picture
how should I do that?
UPDATE: I already send the result of my JSONArray and stored it in "$data" but my problem now is how to insert the values to my online database. By the way, in my PHP code, here is where I store the JSONArray as a string:
$data = $_POST["data"];
UPDATE: I already made it! Thanks for noticing and answering my question
I will give you some general guidelines. Sending JSON on HTTP calls can get weird because it can contain characters that are special to HTTP. To get around this, encode the JSON with Base 64 on Android and decode it in PHP.
I assume that you can figure out how to base64 encode with Java.
On PHP, you get back your original JSON.
$originalJson = base64_decode($inputFromAndroid);
$object = json_decode($originalJson, true);
// Now you have the data as a PHP array.

Display Student details in text view after validation in android

This is my previous question: display result of json data in textview of android
And this is json result:
{"can_data":[{"name":"dfsdfd","address":"gdgfsdf","course":"dfdfdsf"}]}
I want to display this details in text view of DetailsActivity.java after validating user input IMEI_Val.java class. How can I do this.Please help me to solve this.
If you want to parse the above json then here it is.
Send the response as putExtra to your IMEI_Val.java activityClass.
To fetch the details,
try {
JSONObject responseObject = new JSONObject(jsonObject);
JSONArray canData = responseObject.getJSONArray("can_data");
JSONObject canDataJSONObject = canData.getJSONObject(0);
String name = canDataJSONObject.getString("name");
String address = canDataJSONObject.getString("address");
String course = canDataJSONObject.getString("course");
} catch (JSONException e) {
e.printStackTrace();
}
You can set it to your text view now.

getting issue in json parsing

i have to download a demo apk. I am inserting some values in database using php. but at some point of time it is throwing an error
org.json.JSONException: Value at validity_days of type java.lang.String cannot be converted to int
the code snippet in java:
private void upgradeVersion(String apkPath) {
System.out.println("SDCARD path checked5:-"+apkPath);
if(saveUserInfo()==true)
{
System.out.println("validity...."+validity);
if (apkPath != null) {
progressDialog.dismiss();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(apkPath)),
"application/vnd.android.package-archive");
intent.putExtra("validity_days", validity);
startActivityForResult(intent, 1);
Toast.makeText(getApplicationContext(),"NetVidya ebook app has been successfully installed.", Toast.LENGTH_LONG).show();
}
}
and the php response:
{"users":[{"status":"added","installeddate":"","active":"Y","validity_days":""}]}
which im getting null here thats y throwing error.
is it possible to handle that exception in android itself? or i have to make some changes in php.
please suggest
Without seeing your JSON parser I'm assuing the issue is becuase you need to use validity_days and that string, at least some of the time, may have no value.
try{
JSONObject fullString = new JSONObject(thatLongStringYouPosted);
JSONArray users = fullString.getJSONObject("users");
String validity_days = users.getJSONObject(0),getString("validity_days");
if(!validity_days.isEmpty() && validity_days != null)
//do whatever you want with it
}
} catch (JSONException e){
Log.e(TAG, e.toString());
}
When parsing JSON you will get back a null value only if what you are looking for does not exist - i.e. there is no "validity_days" string in the response. Otherwise you will just get an empty string. Simply checking for the null and/or the empty string should fix your problem.
Also the try catch block will handle this excpetion within the android code. You can modify your PHP if you want to ensure you always get back a specific value if empty (e.g. you may want to always reuturn a 0 instead of nothing when a field is blank).
According to the Exception you placed above, I think you are getting Exception at this line:
startActivityForResult(intent, 1);
Just replace this line with
startActivity(intent);
and get JSONString in other activity as
Intent i = getIntent();
String str = i.getStringExtra("validity_days");
Why don't you parse your variable validity_days to integer before it throws exception..

how to send long array from android to php server

I try to send long array from android to PHP via JSON. I did the same thing with Javascript and worked but with JAVA it gets confusing. When I send the parameters, long array list changes.
This is the part that creates the list.
JSONArray list = new JSONArray();
for (int i = 0; i < users.size(); i++) {
list.put(users.get(i).getId());
}
This is the code in JAVA that send the data.
public JSONObject sendFacebookFriendList(JSONArray list) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("list", list.toString()));
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.getJSONFromUrl(accountServer, params);
return json;
}
And this is the code that receives the data in PHP.
$list = $_POST['list'];
$result = array("success" => 1, "list" => $list);
While sending with Javascript the $list variable was becoming long array directly but I couldn't send it same way with JAVA.
When I send the list back to JAVA from PHP without any change I see that each array element has \" at the head and the end
So this list:
list= ["517565130","523709375","524503024","524620558","524965930", ...
becomes this:
"list":"[\"517565130\",\"523709375\",\"524503024\",\"524620558\", ...
So I cannot parse this array in PHP.
I couldn't find any way to send the long/int array in a proper way.
I appreciate if someone can fix this or suggest another way.
Thanks
I solved the problem. The thing I skipped was decoding the json array that encoded at android part. So after getting the posted data it is needed to be decoded like this;
$list = $_POST['list'];
$obj = json_decode($list);
And then I can use $obj as array.

PHP/Android and JSONObject; I can only seem to access the last element

I have a set up where it is returning a possibly decent amount of info. Here is the logcat:
04-17 22:38:21.886: DEBUG/TestMYSQL(12603): Result of sql:
[{"id":"1","front_text":"the dog was so cute","back_text":"its name was dolly"},
{"id":"2","front_text":"plants use the sun","back_text":"isn't that interesting"},
{"id":"3","front_text":"plants can use the sun to create","back_text":"energy"},
{"id":"4","front_text":"a plant also needs minerals","back_text":"from the soil"},
{"id":"5","front_text":"without water the plant would","back_text":"probably die"},
{"id":"6","front_text":"plants are little machines","back_text":"who love to eat"}]
To gain this info, I have it execute a php file. Here is some pertinent Java, android code:
.....
result = sb.toString();
Log.d(TAG, "Result of sql: " + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
JSONObject json_data = null;
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
}
return json_data;
It turns results into a jsonObject, to which I can play with.
So here is a step before, the query part in php:
include 'connectMySQL.php';
mysql_select_db("card_db");
$q=mysql_query("SELECT * FROM ".$packname);
while($e=mysql_fetch_assoc($q)){
$output[]=$e;
}
print(json_encode($output));
mysql_close();
The problem is I only seem to have access to the FINAL... eh row. That is, in the above data, I can only seem to access id:6 row.
I'm looking at the auto_complete and JSONOBJECTs but I don't have enough experience to figure this out at the moment, and it is late.
Any ideas on how to loop through the jsonObject in java?
Let me take a minute and analyze the structure for a second before turning in. I don't know much about JSON, but here is what it looks like:
I query the database with tables I've set up, blah blah.
It returns rows of data.
I suppose my question then is how does a row of key value pairs get encoded into a JSON OBJECT, and how can I access different 'rows'?
You're overwriting the JSONObject referenced by json_data in each iteration of the loop. So at the end, it always returns the last element in jArray.
Since you need to return multiple objects, you could:
simply return the jArray to the calling function. However, this means that the caller will have to deal with the details of the data transfer implementation and if you decided to change libraries or move over to XML, it'll break a lot of code and make it much harder.
return an array or List of the actual objects that the calling code is aware of and should be dealing with. For example, you might declare a value-object (VO) that has id, front_text, back_text and for each JSONObject in jArray, you'd create a new VO and put it into an array and return that.
public class MyVO
{
final public String id;
final public String frontText;
final public String backText;
public MyVO(String id, String ft, String bt)
{
this.id = id;
this.frontText = ft;
this.backText = bt;
}
}
List<MyVo> vos = new ArrayList<MyVO>();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
vos.add(new MyVO(json_data.getString("id"), json_data.getString("front_text"), json_data.getString("back_text"));
}
In the calling code, you could then go over the VOs:
for(MyVO vo : vos)
{
//vo.id or vo.frontText or vo.backText
}

Categories