how to check condition for json array elements - android

I am developing an app in which i am calling a service, in which data is coming as an array format.
As shown below:
[
{
"Image":null,
"FirstName":null,
"Active":false,
"HallTicketNumber":0,
"ReportingTime":null,
"EventDetails":null,
"CompanyName":null,
"Designation_Role":null,
"EventDate":null,
"StateName":null,
"CityName":null,
"FullAddress":null,
"HallTicket_Status":"HETSTOP"
}
]
In that i need to check the condition for HET_STATUS,if that StATUS is HET STOP then it should print that het stop. But when i am trying to check the condition it is showing nothing:
Below is my code:
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String CompanyName = json.optString("CompanyName ");
String Position = json.optString("Designation_Role");
String EventDate = json.optString("EventDate");
String StateName = json.optString("StateName ");
String CityName = json.optString("CityName");
String Address = json.getString("FullAddress");
String ReportingTime = json.getString("ReportingTime");
String HallTicket_Status = json.getString("HallTicket_Status");
if (HallTicket_Status == "HETSTOP") {
Toast toast = Toast.makeText(UpcomingEventsDetails.this, "HET STOP", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

Try this way,
if(HallTicket_Status.equalsIgnoreCase("HETSTOP")){
Toast toast = Toast.makeText(UpcomingEventsDetails.this, "HET STOP", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else{
//do something
}
boolean equals(String str): Case sensitive comparison
boolean equalsIgnoreCase(String str): Case in-sensitive comparison
== will still test object equality. It is easy to be fooled, however:
Integer a = 10;
Integer b = 10;
System.out.println(a == b); //prints true
Integer c = new Integer(10);
Integer d = new Integer(10);
System.out.println(c == d); //prints false. however:
Integer a = 10;
Integer b = 10;
System.out.println(a == b); //prints true
Integer c = new Integer(10);
Integer d = new Integer(10);
System.out.println(c == d); //prints false

Don't use == condition for strings. Instead of use str.equals("HEYSTOP") . This will return boolean. If you check string is null then you should use == or != conditions.

Related

compare subset of 2d array and string array

I have been working on this problem for about five hours, implementing many different ways to achieve this goal, but nothing seems to be working. I am at the point to where I can't even think straight any more, so I am posting this here.
I have a shared preference which retrieves a string. that string is converted into a string array. I have a 2d array with four arrays set to the index. I want to loop through the 2d array and compare my string array to it. If the contents of each 2d array index are found in my string array, print true, else, false.
final SharedPreferences sharedPref = CocktailsFrag.this.getActivity().getPreferences(Activity.MODE_PRIVATE);
//recall stored ingredients
String arrayString = sharedPref.getString("myIngredients", null);
if(arrayString ==null) {
//do nothing
} else {
String str1 = arrayString.replace("[", "");
String str2 = str1.replace("]", "");
String[] strValues = str2.split(",");
String drink1[] = {"Ale", "Brandy"};
String drink2[] = {"Vodka", "Tobasco Sauce"};
String drink3[] = {"Lager", "Stout"};
String drink4[] = {"Guiness", "Champagne"};
String[][] arrays = {drink1, drink2, drink3, drink4};
for(int i=0; i<arrays.length-1;i++) {
String[] indexValue = arrays[i];
if(strValues[i].contains(indexValue[i])) {
Toast.makeText(getActivity().getApplicationContext(), indexValue[i]+ "", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}
}
Any thoughts on how to achieve this?
This code is not as efficient as simply iterating over the arrays but it doesn't matter with the number of elements and it is easier to read.
final SharedPreferences sharedPref = CocktailsFrag.this.getActivity().getPreferences(Activity.MODE_PRIVATE);
//recall stored ingredients
String arrayString = sharedPref.getString("myIngredients", null);
if(arrayString ==null) {
//do nothing
} else {
String str1 = arrayString.replace("[", "").replace("]", "");
List<String> strValues2 = Arrays.asList(str1.split(","));
String drink1[] = {"Ale", "Brandy"};
String drink2[] = {"Vodka", "Tobasco Sauce"};
String drink3[] = {"Lager", "Stout"};
String drink4[] = {"Guiness", "Champagne"};
String[][] arrays = {drink1, drink2, drink3, drink4};
for(String[] drinkArr : arrays){
if(strValues2.containsAll(Arrays.asList(drinkArr))) {
Toast.makeText(getActivity().getApplicationContext(), "true", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}
}
If you wanted to do this using arrays only one option is the following.
for(String[] drinkArr : arrays) {
boolean allDrinksFound = true;
for(int i = 0; i < drinkArr.length; i++) {
boolean drinkFound = false;
for(int j = 0; j < strValues.length; j++) {
if(drinkArr[i].equals(strValues[j])) {
drinkFound = true;
break;
}
}
allDrinksFound = allDrinksFound && drinkFound;
}
if(allDrinksFound) {
Toast.makeText(getActivity().getApplicationContext(), "true", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}

While retrieving values from Preference, it is repeating 20 times

Hi I am storing BigInteger[] array into Preference, This is working fine, but while retrieving i am getting the same value 20 times, can someone tell me what's wrong with the code :
final String DELIMITER = "BOND";
final int DELIMITER_LENGTH = 4;
String str = null ;
//BigInteger [] integer = new BigInteger[50];
for(int l = 0; l < arrayTimes.length ; l++){
if(str == null){
str = arrayTimes[i].toString() + DELIMITER;
}else{
str += arrayTimes[i].toString() + DELIMITER;
}
}
savePreference("your_key", str);
Log.d("Prefs", "Array Time Saved");
String strone = loadPreference("your_key");
ArrayList<BigInteger> myBigInt = new ArrayList<BigInteger>();
while(strone != null){
int subStringLastIndex = 0;
if(strone.contains(DELIMITER) && strone.length() != DELIMITER_LENGTH){
subStringLastIndex = strone.indexOf(DELIMITER.charAt(0));
myBigInt.add(new BigInteger(strone.substring(0, subStringLastIndex)));
strone = strone.substring(subStringLastIndex + 4);
}else{
strone = null;
}
}
for(int m = 0; m < myBigInt.size(); m++){
Log.d("Prefs", myBigInt.get(m).toString()); //Here i am printing values
}
You seem to have a typo. Your for loop uses l but you reference the array with i. If arrayTimes has 20 items, you'll add the same value to the string 20 times.

Compare two JSONObject values and return the smaller between them

For the given JSON:
{
"month": {
"days": {
"day1": {
"start": 13914323164815,
"duration": 15
},
"day2": {
"start": 13914123164815,
"duration": 56
}
}
}
}
I want to get the values for duration (in this case 15 and 56), compare them and return the smaller value. First i got the month object and this is what i tried next:
JSONObject days = myMonthObject.getJSONObject("days");
JSONArray daysArray = days.names();
for (short r = 0; r<daysArray.length();r++){
String dayObject = daysArray.getString(r);
JSONObject allDaysObject = days.getJSONObject(dayObject);
String duration = allDaysObject.getString("duration");
Log.w(TAG, "THE DURATION IS: " + duration);
}
On the first iteration I got the message:
THE DURATION IS: 15,
and on the second iteration: THE DURATION IS: 56.
Now how to preserve the first found value for duration and on the next iteration of daysArray loop (the value will be 56) to compare both and return and smaller?
Any help will be appreciated! :)
Firstly, outisde the loop, create an int variable called max.
int max = 0;
Essentially, you're getting the value of each duration as a String (as in the example):
String duration = allDaysObject.getString("duration");
Now, you can get the int value of this by:
int intDuration = Integer.parseInt(duration);
Next, compare intDuration to max:
if (intDuration > max) max = intDuration;
Then you can let this iterate through the entire array. At the end of the loop, max will hold the highest duration.
Introduce a variable
String tmpDuration;
//in the for loop
if(tmpDuration.equals("") || duration < tmpDuration){
tmpDuration = duration;
}
Without modifying much what you've
int min = 0;
JSONObject days = myMonthObject.getJSONObject("days");
JSONArray daysArray = days.names();
for (int i = 0; i < daysArray.lenght(); i++){
JSONObject day = daysArray.getJSONObject(i);
String duration= day.getString("duration");
if(i = 0) {
min = Integer.valueOf(duration);
} else {
if (Integer.valueOf(duration) < min) {
min = Integer.valueOf(duration);
}
}
}
Also if you what the Object that has the highest duration
HashMap<String,Integer> map = new HashMap<String,Integer>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Integer> sorted_map = new TreeMap<String,Integer>(bcv);
JSONObject days = myMonthObject.getJSONObject("days");
JSONArray daysArray = days.names();
for (JSONObject day : daysArray){
map.put(day.toString(), Integer.valueOf(day.getString("duration"));
}
sorted_map.putAll(map);
class ValueComparator implements Comparator<String> {
Map<String, Integer> base;
public ValueComparator(Map<String,Integer> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
This should return
JSONObject "day1": {
"start": 13914323164815,
"duration": 15
15
I´ve taken the TreeMap code from here, any retribution for this goes to user157196:
Sort a Map<Key, Value> by values (Java)
Hope it helps. :)
Here is my solution, hope this helps:
int minValue = 99999;
int index = 0;
for (int f = 0; f < daysArray.length(); f++){
String dayObject = daysArray.getString(f);
JSONObject allDaysObject = days.getJSONObject(dayObject);
String duration = allDaysObject.getString("duration");
if(Integer.valueOf(duration) < minValue){
minValue = Integer.valueOf(duration);
index = f;
}
}
String dayObject = daysArray.getString(index);
JSONObject allDaysObject = days.getJSONObject(dayObject);
String duration = allDaysObject.getString("duration");

regular-expressions android

i have string like these for example
309\306\308\337_338
309\306\337_338
310
311\315_316\336_337
311\315_316\336_337
311\335_336
these strings means list of page number , for example string "309\306\308\337_339" means
pages 309,306,308,337,338,339
i want to pass one of these string to function which return it as string like this
309,306,308,337,338,339
this function do that but in c# , i want to impalement in android
private static string Get_PageNumbers(string str)
{
ArrayList arrAll = new ArrayList();
MatchCollection match;
string[] excar;
string strid, firstNumber, lastlNumber;
int fn, ln;
ArrayList arrID = new ArrayList();
//***In Case The Range Number Between "_"
if (str.Contains("_"))
{
// match_reg = new Regex("(w?[\\d]+)*(_[\\d]+)");
Regex matchReg = new Regex("(w?[\\69]+_[\\d]+)*(q?[\\d]+//)*(a?[\\d]+_[\\d]+)*(y?[\\d]+)*");
match = matchReg.Matches(str);
int count = match.Count;
excar = new string[0];
for (int i = 0; i < count; i++)
{
Array.Resize(ref excar, count);
excar[i] = match[i].Groups[0].Value;
if (excar[i] != string.Empty)
arrID.Add(excar[i]);
}
//******IF Array Contains Range Of Number Like"102_110"
if (str.Contains("_"))
{
for (int i = 0; i < arrID.Count; i++)
{
strid = arrID[i].ToString();
if (arrID[i].ToString().Contains("_"))
{
int idy = strid.LastIndexOf("_");
firstNumber = strid.Substring(0, idy);
if (idy != -1)
{
lastlNumber = strid.Substring(idy + 1);
fn = int.Parse(firstNumber);
arrAll.Add(fn);
ln = int.Parse(lastlNumber);
for (int c = fn; c < ln; c++)
{
fn++;
arrAll.Add(fn);
}
}
}
else
{
arrAll.Add(arrID[i].ToString());
}
}
//******If Array Contain More Than One Number
if (arrAll.Count > 0)
{
str = "";
for (int i = 0; i < arrAll.Count; i++)
{
if (str != string.Empty)
str = str + "," + arrAll[i];
else
str = arrAll[i].ToString();
}
}
}
}
//***If string Contains between "/" only without "_"
else if (str.Contains("/") && !str.Contains("_"))
{
str = str.Replace("/", ",");
}
else if (str.Contains("\\"))
{
str = str.Replace("\\", ",");
}
return str;
}
I think this is easier to do with split function:
public static String Get_PageNumbers(String str) {// Assume str = "309\\306\\308\\337_338"
String result = "";
String[] pages = str.split("\\\\"); // now we have pages = {"309","306","308","337_338"}
for (int i = 0; i < pages.length; i++) {
String page = pages[i];
int index = page.indexOf('_');
if (index != -1) { // special case i.e. "337_338", index = 3
int start = Integer.parseInt(page.substring(0, index)); // start = 337
int end = Integer.parseInt(page.substring(index + 1)); // end = 338
for (int j = start; j <= end; j++) {
result += String.valueOf(j);
if (j != end) { // don't add ',' after last one
result += ",";
}
}
} else { // regular case i.e. "309","306","308"
result += page;
}
if (i != (pages.length-1)) { // don't add ',' after last one
result += ",";
}
}
return result; // result = "309,306,308,337,338"
}
For example this function when called as follows:
String result1 = Get_PageNumbers("309\\306\\308\\337_338");
String result2 = Get_PageNumbers("311\\315_316\\336_337");
String result3 = Get_PageNumbers("310");
Returns:
309,306,308,337,338
311,315,316,336,337
310
if i can suggest different implementation....
first, split string with "\" str.split("\\");, here you receive an array string with single number or a pattern like "num_num"
for all string founded, if string NOT contains "" char, put string in another array (othArr named), than, you split again with "" str.split("_");, now you have a 2 position array
convert that 2 strings in integer
now create a loot to min val form max val or two strings converted (and put it into othArr)
tranform othArr in a string separated with ","

I'm not understanding the following code

I have to understand this code to create my own app(almost based on this function):
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0;
String ligne;
int j = 0;
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
s[0][j] = ligne;
else {
s[1][j] = ligne;
j++;
}
i++;
}
fIn.close();
ipsr.close();
return s;
}
catch (Exception e)
{}
I'm not understanding why the using of a 2D array? and with two rows ?(String[][] s = new String[2][i/2];)
here is the data that it will be stored in the file:
data = date + " : " + y + "L/100KM"+ " " + value1 + "L "+ value2 + "KM\n";
Necessary functions:
public void updatelv(Activity activity) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String fileName = getResources().getString(R.string.fileName);
fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
s = myIO.ReadFilePerLine(getApplicationContext(), fileDir+fileName);
ListView L = (ListView) findViewById(R.id.lv);
L.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, s[0]));
for (int i = 0; i< s[0].length; i++) {
Log.d("Saves",s[0][i]);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.histo);
context = getApplicationContext();
activity = this;
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
String fileName = getResources().getString(R.string.fileName);
fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
s = myIO.ReadFilePerLine(getApplicationContext(), fileDir + fileName);
updatelv(this);
ListView L = (ListView) findViewById(R.id.lv);
L.setTextFilterEnabled(true);
L.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String tmp = s[1][position];
if (tmp == null)
tmp = "Aucun fichier trouvé!";
Toast.makeText(getApplicationContext(), tmp, Toast.LENGTH_SHORT)
.show();
}
});
ReadFilePerLine function:
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0;
String ligne;
int j = 0;
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
s[0][j] = ligne;
else {
s[1][j] = ligne;
j++;
}
i++;
}
fIn.close();
ipsr.close();
return s;
}
catch (Exception e)
{
}
Thank you for you help.
The code is clearly reading from a file whose format consists of pairs of lines; it puts the first line of each pair in s[0][...] and the second line of each pair in s[1][...]. If your format doesn't have that peculiarity -- which it doesn't sound as if it does -- then you don't need to do that. Just make an ordinary 1-dimensional array of Strings.
It appears that what they are doing is breaking the file down into two lists (or String arrays, in this case), one which contains all the even-numbered lines, and one which contains all the odd-numbered lines. I'll comment up the code for you:
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
//open the specified input file and create a reader
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
//get the total number of lines in the file, and allocate
//a buffer large enough to hold them all
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0; //set the current line to 0
String ligne;
int j = 0; //set the section index to 0
//now read through the lines in the file, and place every
//even-numbered line in the first section ('s[0]'), and every
//odd-numbered line in the second section ('s[1]')
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
//even-numbered line, it goes into the first section
s[0][j] = ligne;
else {
//odd-numbered line, it goes into the second section
s[1][j] = ligne;
j++; //increment the section index
}
i++; //increment the line count
}
//done, cleanup and return
fIn.close();
ipsr.close();
return s;
}
catch (Exception e) {
//should at least log an error here...
}
}
As to why they chose to use a String[][], I cannot say. Probably for convenience, since they want a single object that they can return from this function that contains both lists. Personally I would use a Map that has two List instances in it, but the String[][] works just as well and is probably marginally more efficient.
Judging from your example data it does not appear that you need to use this format. But if you want to use it, you need to structure your data so that the key is on one line, and its associated value is on the next, like:
date
2011-03-19
userName
someGuy
it seems to read from a file, split it into the two dimensional array (based on row count).
Why it does it? I have no idea why you'd want that. Check out the function that it returns s to and find out!

Categories

Resources