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..
Related
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.
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.
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");
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 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
}