简体   繁体   中英

Returning value from an IF statement

I would like to return a string from an IF statement. Below is the code. I am parsing a JSON object and need to insert the data into a sql lite table.

if (object.has("message")) {
    JSONObject message = object.getJSONObject("message");
    String newtype_mod = object.getJSONObject("message").getString("type");
    String newcontent_mod = object.getJSONObject("message").getString("content");
    objSample = new GetSetMethod();
    objSample.setnewcontent_mod(newcontent_mod);
    objSample.setnewtype_mod(newtype_mod);
    Log.v("##" + newcontent_mod, "V " + newtype_mod);
}

objSample = new GetSetMethod();
objSample.setNewreportid(newreportid);
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
Log.v("" + newcontent_mod, "" + newtype_mod);

As you would have understood newcontent_mod and newtype_mod will not be accessible from the IF statement. And I need the IF statement compulsorily.

I understand the question is basic. Please help a fellow newbie !

Thanks!

Can you not simply declare them outside the if?

String newtype_mod = "";
String newcontent_mode = "";
if ((object.has("message"))) {
    //
    // do stuff here
    //
}
// continue as before...

You can declare it outside the if statement and just assign the value to these variables

for example:

String newtype_mod="";
String newcontent_mod="";

if ((object.has("message"))) 
{
     JSONObject message = object.getJSONObject("message");
     newtype_mod = object.getJSONObject("message")
                        .getString("type");
     newcontent_mod = object.getJSONObject("message")
                     .getString("content");
     objSample = new GetSetMethod();
     objSample.setnewcontent_mod(newcontent_mod);        
     objSample.setnewtype_mod(newtype_mod);
     Log.v("##"+newcontent_mod,"V "+newtype_mod);
}

otherwise

You can declare both at Global level ie class level variables

Declare the 2 string outside the if statement like

String newcontent_mod,newtype_mod;
if ((object.has("message"))) {
    JSONObject message = object.getJSONObject("message");
    newtype_mod = object.getJSONObject("message")
                        .getString("type");
    newcontent_mod = object.getJSONObject("message")
                        .getString("content");
    objSample = new GetSetMethod();
    objSample.setnewcontent_mod(newcontent_mod);        
    objSample.setnewtype_mod(newtype_mod);
    Log.v("##"+newcontent_mod,"V "+newtype_mod);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM