I have a edit text in login page, and I have a condition for edit text MaxLength="12". In my JSON response I have a string with 15 letters (or Nor's), I need to check (or compare) up to 12 letters(or Nor's) from it, If both letters are same up to 12 Letter(or Nor's), then I have to enter into my app.
{
ID No="123456789012.00"
}
Hello Suresh Use String#substring
try {
JSONObject jObj = new JSONObject("{\"id_no\":\"123456789012.00\"}");
String strJNumber = jObj.optString("id_no").substring(0,11);
String strENumber = etNumber.getText().toString();
if(strENumber.equals(strJNumber)){
// TODO: true both are same
}else {
// TODO: true both are not same
}
} catch (JSONException e) {
e.printStackTrace();
}
You can use "substring" and "equals" methods:
(I assume your strings' names are editTextString and jsonString)
First, get substring of first 12 chars from json string:
String jsonFirst12Chars = jsonString.substring(0,12);
Then use equals method to compare them:
if(editTextString.equals(jsonFirst12Chars)) {
// They are same, do something
} else {
// They are not same..
}
Related
I am working on an app in Android Studio that downloads a json file from a php query, however when I have managed to read the contents of the json file from android, this contents does not behave as text, because when comparing a text entered from the app against the read from the json file, it never matches despite being the same text. (Example: password text from app and the password from the json file).
Php Code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
include('functions.php');
$col=$_GET["col"];
$colbus=$_GET["colbus"];
$tabla=$_GET["nomtable"];
$todfilas=$_GET["todasf"];
$dbuser =$_GET["username"];
$dbpass=$_GET["password"];
$dbbase=$_GET["dbname"];
//echo "$todfilas <br>";
if($todfilas == 1){
$sqlt="SELECT * FROM $tabla";
}else{
$sqlt="SELECT * FROM $tabla WHERE $col='$colbus'";
}
//echo "$sqlt <br>";
if($resultset=getSQLResultSet($sqlt,$dbuser,$dbpass,$dbbase)){
while ($row = $resultset->mysqli_fetch_array(MYSQLI_NUM)){
echo json_encode($row);
}
}
?>
Code from Android Studio:
private class ConsultData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "No es posible cargar pagina web o la direccion es invalida!";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONArray ja = null;
try {
ja = new JSONArray(result);
Log.d("Password:",ja.getString(7)+"="+logPass.getText().toString().trim());
logPass2.setText(ja.getString(7).trim());
String pass1 =logPass2.toString();
String pass0 = logPass.toString().trim();
if(pass0==pass1){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I'm not sure if the way to create the json file in the php query is the problem? because I can see the contents of the json array in Android Studio, but when I compare text from json array, they do not match even if they are the same ("123" = "123").
As seeing your code you doing so many mistakes like you are getting textview value thats not right way
change code like this
String pass1 =logPass2.getText().toString();
String pass0 = logPass.getText().toString().trim();
Also comparsion of string
if(pass0.equals(pass1)){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
instead of this
if(pass0==pass1){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
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.
In my JSON response I am get nothing in value and at that I want to print message using textview I am trying but its not showing nothing,can any one help?the response is looks like this
{"name":"Patel Monali","age":24,"location":"","mother_tounge":"","occupation":"","income":"","height":"","cast":"","marital_status":"","religion":"","gotra":"","manglik":"","rashi":"","education":"","eating":"","drink":"","smoke":"","about_me":"","profile_pic":"Imaege","user_status":"Accept","interest_id":1288}
and here is the code:
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String user_name = jsonObj.getString(USER_NAME);
String user_age = jsonObj.getString(USER_AGE);
...............
final TextView uname = (TextView)findViewById(R.id.namedetail);
final TextView fdetail = (TextView)findViewById(R.id.firstdetail);
..............
uname.setText(user_name);
fdetail.setText(user_age+" years");
androidAQuery.id(ucover).image(user_pro, true, true);
}catch (JSONException e)
{
e.printStackTrace();
}
If I understand your question correctly here is what you need
if(user_name==null)
{
uname.setText("not willing to specify");
}
else
{
uname.setText(user_name);
}
If you need something more please update your question or tell me in comments.
.
Hope it help
All you have to do is check if the received string is null.
for example:
String user_occupation = jsonObj.getString(USER_OCCU);
if(user_occupation.length==0){
user_occupation="not willing to specify";//set your message here
}
OR
String user_occupation = jsonObj.getString(USER_OCCU);
if(user_occupation==null){
user_occupation="not willing to specify";//set your message here
}
In my Android project when user log in, it will access our server and return to the client a json data, when user enter a wrong username or password, server will return the json data just like this:
{"d":{"__type":"FMService.LoginUser:#StarHope.FMS.Web.Pages.Service","Error":"worng","Permissions":null,"UserInfo":null}}
But when user enter the right username and password the return data "Error" is null.So the value of key "Error" is null. I try this to deal with it.
try
{
//when Error is not null
String error = (String) map.get("Error");
}
catch (Exception e)
{
//when Error is null
}
Is this OK? Anything wrong with this? Thang you.
parse your json string as use isNull to check if jsonobject content NULL or not before adding value to Map:
JSONObject jobject=new JSONObject("YOUR_JSON_STRING");
if(!jobject.isNull("d")){
JSONObject jobjd=jobject.getJSONObject("d");
String strtype,strError;
if(jobjd.isNull("__type")){
strtype=jobjd.getString("__type");
}
else{
//do some code here
strtype="is null";
}
if(jobjd.isNull("Error")){
strError=jobjd.getString("Error");
}
else{
//do some code here
strError="is null";
}
//.....same code here for Permissions and UserInfo
}
else{
//do some code here
}
You can use getString(). This method will raise a JSONException if the mapping is missing.
public String getString (String name)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary.
Throws JSONException if no such mapping exists.
You can also test if the mapping exists or is null using isNull()
Note that the Error field is inside the d object, not the root.
i'm using in my android app native JSON-Library within Android OS. It works fine, but one thing makes me crazy.
If server interface changes and gives almost the same answer but the key notation will be a bit different (e.g. examplekeyofmyapp and exampleKeyOfMyApp) i have a problem.
Is there the way to ignore the case of the keys?
Or maybe anybody of you uses a workaround for these cases?
Thank you
if you had implemented your code like this
jsonobject.get(examplekeyofmyapp);
then modify your code. simply change the json String to lower case.
jsonString.toLowerCase(). thats it, all the upper case will get converted to lower case.
I faced the same problem and the best solution I found is to check if your key has an available value.
You still have to check all the possible cases you think you could have.
String TAG_URL_LOWER_CASE = "url";
String TAG_URL_UPPER_CASE = "URL";
String urlValue = "";
if (!obj.isNull(TAG_URL_LOWER_CASE)) {
urlValue = obj.getString(TAG_URL_LOWER_CASE);
} else if (!obj.isNull(TAG_URL_UPPER_CASE)) {
urlValue = obj.getString(TAG_URL_UPPER_CASE);
}
You will also avoid JsonException if your key has no value associated to you key.
Hope it helps
I know this is a few years old, but I thought my solution might help others:
String keyName = null;
for(Iterator<String> iter = jsonData.keys(); iter.hasNext();) {
String key = iter.next();
if (key.equalsIgnoreCase(jsonVar)) {
keyName = key;
break;
}
}
jsonData.get(keyName);
Obviously you can change the "get()" to other types of get methods
I have core methods that I use for each of the types that handles the error for you, e.g.
public static String getJSONString(JSONObject jsonData, String jsonVar) {
// start with a blank name
String keyName = null;
// loop through they keys to find the correct spelling
for(Iterator<String> iter = jsonData.keys(); iter.hasNext();) {
String key = iter.next();
if (key.equalsIgnoreCase(jsonVar)) {
keyName = key;
break;
}
}
// if the key isn't found, return a null
if (keyName == null) {
return keyName;
}
// need a try/catch around JSON stuff as the variable could be the wrong type or not exist
try {
return jsonData.getString(keyName);
}
catch (Exception e) {
// log the variable & the error
Log.w("getJSONString", "failed to getJSONstring "+jsonVar+" - "+e.toString());
// return an empty string because the "get" failed
return "";
}
}
Once you have all of the types made, it makes it easier to handle blank or missing values
I hope this helps somebody :)