Android JSONObject need print null - java

data from:
{"i":"One","o":"two","u":"","a":"four"}
code:
JSONObject data;
for (int i = 0; i < list.length(); i++) {
data = list.optJSONObject(i);
mSearchList.add(data.optString("o") + " " +
data.optString("u")+ " " + data.optString("a"));
}
print:
i=one
o=two
u=
a=four
I need print:
i=one
o=two
u=null
a=four
how to do?Thank you read my question ,please help me

As Sotirios Delimanolis said, you can check if that is a empty string, return "null" text.
for (int i = 0; i < list.length(); i++) {
data = list.optJSONObject(i);
mSearchList.add(
data.optString("o").equals("") ? "null" : data.optString("o") + " " +
data.optString("u").equals("") ? "null" : data.optString("u") + " " +
data.optString("a").equals("") ? "null" : data.optString("a"));
}

Use this method
getValidString(JSONObject json,String key){
String value="";
try{
value=json.getString(key);
}catch(Exception e){
e.printStackTrace();
}
if(value.length==0){
value="null";
}
}

Related

How to fetch the distinct values from JSONObject in Android

I have the output in following JSONObject format. I want to fetch each and every value in this JSONObject. How can I do it? Need help! Thank you in advance.
{
"410": 19082,
"443": 19097,
"667": 19172
}
you can used below login for parsing key's value's of JSON
String json ="{\n" +
" \"410\": 19082,\n" +
" \"443\": 19097,\n" +
" \"667\": 19172\n" +
" }";
try {
JSONObject obj = new JSONObject(json);
for(int i = 0; i<obj.length(); i++){
Log.e("json parse", "Key = " + obj.names().getString(i) + " value = " + obj.get(obj.names().getString(i)));
}
}catch (Exception e)
{
e.printStackTrace();
}

public static runtime incremental change - android

I have a simple class named A which has two private fields.
public class A {
private String a;
private String b;
} // A
When I get all declared fields from class instance, I get one extra field named $change of type com.android.tools.fd.runtime.IncrementalChange. Where is it coming from ? I am totally not getting this.
Field[] fields = cls.getDeclaredFields();
for (int i = 0, len = fields.length; i < len; i++) {
Field field = fields[i];
field.setAccessible(true);
Log.d("TAG", field.getName());
if (field.isAnnotationPresent(Primary.class)) {
query += getFromalName(field.getName()).toUpperCase() + " " + getSchemaType(field.getType().getSimpleName()) + " PRIMARY KEY, ";
continue;
}
if (field.isAnnotationPresent(NotNull.class)) {
query += getFromalName(field.getName()) + " " + getSchemaType(field.getType().getSimpleName()) + " NOT NULL, ";
continue;
}
query += getFromalName(field.getName()) + " " + getSchemaType(field.getType().getSimpleName()) + ", ";
} // end for
query = query.substring(0, query.lastIndexOf(","));
query += " )";
It was added to support instant run. Disabling instant run solved the problem. here
is the link to android issue tracker

How to replace a string inside of Json using java

[
"label": {
"originalName" : "Case #",
"modifiedLabel" : "Case #",
"labelId" : "case_number_lbl",
"isEditable" : "true",
"imageClass" : ""
}
]
In the above Json Array I need to replace "Case #" with "Ticket #". This is occuring in somany places. Any one update please.
Thanks In advance.
I think a simple loop should solve your problem:
public static void main(String[] args) throws JSONException {
JSONArray array = new JSONArray("[" +
" {" +
" originalName : \"Case #\"," +
" modifiedLabel : \"Case #\"," +
" labelId : \"case_number_lbl\"," +
" isEditable : \"true\"," +
" imageClass : \"\"" +
" }" +
"]");
System.out.println(array.toString(2));
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
JSONArray keys = object.names();
for (int j = 0; j < keys.length(); j++) {
String key = keys.getString(j);
if (object.getString(key).equals("Case #")) {
object.put(key, "Ticket #");
}
}
}
System.out.println();
System.out.println(array.toString(2));
}
You can use GSON to convert your json to java Object and then you can change your string .
You can exchange the value with the help String.replaceAll()
String jSONString = ...; // Your JSon string
String newString = jSONString.replace("Case #", "Ticket #");

How to save fields of object into database using jdbc

I'm trying to make my own ORM framework. I get the values from object into arrayList and I'm trying to save them in one time. I have to make for loop to save them all, but I'm confused how to make it?
prepareteState = connect.prepareStatement(Query);
for (int y = 1; y <= obs.size() ; y++) {
for(Object obj : obs){
prepareteState.setObject(y, obj);
System.out.println(Query);
System.out.println(prepareteState.toString());
}
}
prepareteState.execute();
thanks for good advices but, i found the solution :) it is a little bit different than the first idea but, works fine for me:) instead of using prepareState and setObject one by one i`m using StringBuilder to make String and execute query
private String makeInsertQuery(List<String> listOfColumnsNames, List<Object> listOfParameters, String tableName){
StringBuilder columns = new StringBuilder();
StringBuilder parameters = new StringBuilder();
String query = null;
if(listOfColumnsNames != null && listOfColumnsNames.size() != 0 && listOfParameters != null && listOfParameters.size() != 0 && tableName != null){
for(String string : listOfColumnsNames){
columns.append(string + ",");
}
columns.deleteCharAt(columns.length() - 1);
for(Object object : listOfParameters){
parameters.append ("'" + object + "'" + ",");
}
parameters.deleteCharAt(parameters.length() - 1);
query = "INSERT " + "INTO " + tableName + " ( " + columns.toString() + " ) " + " VALUES " + "( " + parameters.toString() + " )" ;
}
//TODO if you need check for null
return query;
}

Google calendar indexoutofbounds when getTimes()

I'm trying to write a simple method, that gets events from Google calendar. The problem is that if i'm trying to call getTimes() on my events, i get an Indexoutofbounds exception.
I just can't figure out what the problem is.
Thanks in advance :)
jTextArea1.setText("");
try {
CalendarService myService = new CalendarService("myApp");
myService.setUserCredentials(username, password);
String eventTitle = "";
for (URL u : urls) {
CalendarQuery myQuery = new CalendarQuery(u);
myQuery.setMinimumStartTime(convertStartDateToDateTime());
myQuery.setMaximumStartTime(convertEndDateToDateTime());
myQuery.setFullTextQuery(searchTF.getText());
CalendarEventFeed resultFeed = myService.query(myQuery, CalendarEventFeed.class);
// System.out.println(resultFeed.getTitle().getPlainText());
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEventEntry entry = resultFeed.getEntries().get(i);
if (resultFeed.getEntries().size() > 0) {
jTextArea1.setText(jTextArea1.getText()
+ resultFeed.getTitle().getPlainText()
+ "\n");
eventTitle = resultFeed.getEntries().get(i).getTitle().getPlainText();
jTextArea1.setText(jTextArea1.getText() + eventTitle + "\n");
jTextArea1.setText(jTextArea1.getText()
+ "Start: " + resultFeed.getEntries().get(i).getTimes().get(i).getStartTime().toString() + "\n"
+ "Slut: " + resultFeed.getEntries().get(i).getTimes().get(i).getEndTime().toString() + "\n");
}
jTextArea1.setText(jTextArea1.getText() + "\n");
}
}
My guess is something is wrong with your second get(i),
resultFeed.getEntries().get(i).getTimes().get(i).getStartTime().toString()
While the first "i" in the get(i) is guaranteed to work because of i < resultFeed.getEntries().size(); condition in the for loop, the second "i" in the get(i) doesn't have any condition to check its range.
Kindly Post your full exception trace if this isn't your problem.

Categories