Hi All I'm calling one php script from my Android code to insert record into the database. On successful insert I'm getting one string in following format-
{"success":1,"message":"Member registered successfully."}
And in case of error I'm getting the following string-
{"success":0,"message":"Oops! An error occurred."}
Now I wants to parse that string to check whether record is inserted successfully or not for that I have tried following code
JSONArray jsonarray = new JSONArray(response);
JSONObject jsonobj = jsonarray.getJSONObject(0);
String strResp=jsonobj.getString("success");
but strResp is getting null..! Please help. Thank you..!
The code.
JSONObject jObj = new JSONObject(response);
String strResp = jObj.getString("success");
Try this
JSONObject jObj = new JSONObject(response);
String strResp = String.valueOf(jObj.getInt("success"));
Because success in your json response is int.
{ } means json object...and [ ] means json array..
here, {"success":1,"message":"Member registered successfully."} is json object...
so,
JSONObject jsonobj = jsonarray.getJSONObject(response);
String strResp=jsonobj.getString("success");
Related
Below is the code. The code works perfectly fine. It displays the content when both the EditText is left blank or has some string value that is available in the mysql database . My problem is that i want to display an error message when the input from the editText does not match with the JSON object or the returnString that store the result of the Mysql query after decoding JSON.
for eg if input='abi' //input from edittext
khasi:abirt //khasi is column from the database with value abirt
output : khasi abirt will be displayed
but i want an error to be displayed when input does not match at all with any of the words from the khasi column of the database instead of a blank page activity.
for eg : input='kljfldskfsldhf'
khasi column does not consist the input word
outout : blank page activity
String result;
String returnString;// to store the result of MySQL query after decoding JSON
String input;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_meaning);
Intent intent = getIntent();
intent.setClass(DisplayMeaningActivity.this, MainActivity.class);
input =intent.getStringExtra(MainActivity.MEANING_INPUT);
tv = (TextView) findViewById(R.id.textView1);
// declare parameters that are passed to PHP script i.e. the name "meaning" and its value submitted by user
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://kffg.netii.net/konnect.php?name="+input, // your ip address if using localhost server
postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
//parse json data
try{
returnString = "";
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", Khasi: "+json_data.getString("Khasi")+
", English: "+json_data.getString("English")
);
//Get an output to the screen
returnString += "\n\n" + "Kyntien : " + json_data.getString("Khasi") + "\n"+ "Meaning: " + "\n"+ "" + json_data.getString("English");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
need to use an if loop with stringValue.contains("editTextvalue") condition.
It'l be like:
if (inputString.contains(columnNames)) {
//yes
} else {
//no, then print error
}
Since you already have your "result" in String, that shouldn't be a problem (?) .
Did not exactly understand the columns of the database issue but for the khasi column of your database, you can make an arrayList of of names and compare the string with a for each loop.
for(String string: columnNames){
if(input.equals(name)){}
}
Maintain an arrayList where you add string for each time you get data for khasi like:
arrayList.add(json_data.getString("Khasi"));
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..
I am new to JSON. KIndly help me with the JSON parsing in php sent from android.
I have a class A, having members phoneNumber and name. I have an arrayList of object A
private ArrayList<A> contactList = new ArrayList<A>();
contactList.add(a1);
contactList.add(a2); [objects of A]
Now I am trying to send this arrayList to php server using JSON.
JSONObject json = new JSONObject();
json.put("contactList", contactList);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("");
StringEntity se = new StringEntity("JSON: " + json.toString());
post.setEntity(se);
HttpResponse resP = client.execute(post);
Please let me know how to I parse it in the php server side to get phoneNumber and name of each object A.
I tried to create a same class A in the php server side and trying this way.
<?php
$contactList = array();
if(isset($_POST["contactList"])) {
$contactList = json_decode($_POST["contactList"]);
include_once './eachContactClass.php';
foreach ($contactList->contactList as $eachContact) {
$eachObj = new eachContactClass();
$eachObj = $eachContact;
$name = $eachObj->getName();
$phoneNumber = $eachObj->getPhone();
}
}
Please let me know whether the approach is correct, or kindly help me to correct it
First of all, may I suggest you to use a library for handling the JSON serialization/deserialization. GSON would be suited for your work.
Then, you should check the result JSON for validity before sending it to any remote server.
To parse it in PHP, use the json_decode() function that will return your an object representing your JSON. You can also get a hash if you prefer, just look in the doc.
I think your problem is that your JSON is invalid, as the JSONObject doesn't correctly serialize your ArrayList. Your should probably check that.
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.
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
}