0

Im trying to parse a json string that is exist in a online server and store in an empty string like this String data = ""; but when i try to parse it and i see the log i see that the response from the server show all the json code (brackets and quotes and jsonobject) when i only need it to parse one specific string to be stored in the empty string. here are the json:

{
"main1": {"bnl":"code"}
}

the httphanlder

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;


public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}

and this is the mainactivity

public class MainActivity extends ActionBarActivity {

DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
private NativeExpressAdView mNativeExpressAdView;
// URL of object to be parsed
// This string will hold the results

private String TAG = MainActivity.class.getSimpleName();
String data = "";
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://yourdomain.com/test.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
    }
    new GetAd().execute();
    LinearLayout layout = (LinearLayout)findViewById(R.id.layoutId);
    // Create a native express ad. The ad size and ad unit ID must be set before calling
    // loadAd.
    mNativeExpressAdView = new NativeExpressAdView(MainActivity.this);
    mNativeExpressAdView.setAdSize(new AdSize(AdSize.FULL_WIDTH, 90));
    mNativeExpressAdView.setAdUnitId(data);
    // Create an ad request.
    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
    // Start loading the ad.
    mNativeExpressAdView.loadAd(adRequestBuilder.build());
    // Add the NativeExpressAdView to the view hierarchy.
    layout.addView(mNativeExpressAdView);
    Typeface bold = Typeface.createFromAsset(getAssets(),
            "fonts/extrabold.otf");
    db = new DataBaseHandler(this);
    db.openDataBase() ;
    TextView cat = (TextView) findViewById(R.id.titlecat);
    cat.setTypeface(bold);
    TextView alls = (TextView) findViewById(R.id.titlest);
    alls.setTypeface(bold);
    TextView fav = (TextView) findViewById(R.id.titlefav);
    fav.setTypeface(bold);
    TextView qday = (TextView) findViewById(R.id.titleqday);
    qday.setTypeface(bold);
    TextView rate = (TextView) findViewById(R.id.titleqrate);
    rate.setTypeface(bold);
    btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
    //btn_authors= (Button) findViewById(R.id.btn_authors);
    btn_categories = (ImageView)  findViewById(R.id.btn_categories);
    btn_favorites = (ImageView)  findViewById(R.id.btn_favorites);
    btn_qteday = (ImageView)  findViewById(R.id.btn_qteday);
    btn_rateus = (ImageView)  findViewById(R.id.btn_rateus);

    btn_quotes.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this,
                    QuotesActivity.class);
            intent.putExtra("mode", "alltext");
            startActivity(intent);
        }
    });

    /*btn_authors.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent author = new Intent(MainActivity.this,
                    AuteursActivity.class);
            startActivity(author);
        }
    });*/

    btn_favorites.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent favorites = new Intent(MainActivity.this,
                    QuotesActivity.class);
            favorites.putExtra("mode", "isFav");
            startActivity(favorites);
        }
    });

    btn_categories.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent category = new Intent(MainActivity.this,
                    CategoryActivity.class);
            startActivity(category);
        }
    });

    btn_qteday.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            preferences = PreferenceManager
                    .getDefaultSharedPreferences(context);

            Intent qteDay = new Intent(MainActivity.this,
                    QuoteActivity.class);
            qteDay.putExtra("id",
                    preferences.getInt("id", IntialQteOfDayId));
            qteDay.putExtra("mode", "today");
            startActivity(today);
        }
    });

    btn_rateus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    MainActivity.this);
            builder.setMessage(getResources().getString(
                    R.string.ratethisapp_msg));
            builder.setTitle(getResources().getString(
                    R.string.ratethisapp_title));
            builder.setPositiveButton(
                    getResources().getString(R.string.rate_it),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                            int which) {
                            // TODO Auto-generated method stub
                            Intent fire = new Intent(
                                    Intent.ACTION_VIEW,
                                    Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName()));           //dz.amine.thequotesgarden"));
                            startActivity(fire);

                        }
                    });

            builder.setNegativeButton(
                    getResources().getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                            int which) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();

                        }
                    });
            dialog = builder.create();
            dialog.show();
        }
    });




}
void startTheThingWithData(){
    //Here data has value
    Log.e(data, data);
}
/**
 * Async task class to get json by making HTTP call
 */
private class GetAd extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);



        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                JSONObject dataa = jsonObj.getJSONObject("main1");
                String ad =  dataa.getString("bnl");
                data = ad;
                Log.e(TAG, "Response from url: " + ad);


            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        startTheThingWithData();
    }}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.menu_settings) {
        Intent i = new Intent(this, UserSettingActivity.class);
        startActivityForResult(i, RESULT_SETTINGS);
    }

    return super.onOptionsItemSelected(item);
}

this is what it shows in the log

E/MainActivity: Response from url: {

            "main1": {

            "bnl":"code"
            }
}
3
  • 1
    Maybe instead of turning JSON into a String you can just get it as a JSON object and then use the built in methods for finding the key/value you want. Commented Oct 6, 2017 at 15:48
  • can you please give me example code, im little bit newbie at json Commented Oct 6, 2017 at 15:52
  • I'm sure if you Google for 'JSON object in Android' you will find many code examples. Commented Oct 6, 2017 at 15:55

1 Answer 1

1

You are printing the jsonStr while the content you want is the data.

AyncTasks runs async, meaning that code runs paralalel: check this simple sample for better undestanding.

String b = "s"; 
void onCreate(Bundle b) {
   afterAsyncHere();
   new Task().execute();
   afterAsyncHere();
}

void afterAsyncHere() {
   Log.e("onCreate", b);
}

class Task extends AsyncTask {
    Object doInBackground(Object ... args) {
        b ="value b";
        try { Thread.sleep(1000); }catch(Exception e) {}
    }
    void onPostExecute(Object r) {
        afterAsyncHere();
    }
}
}

The above code will call afterAsyncHere() three times, two in onCreate and one in onPostExecute. The printed result will be: "s" from onCreate "s" from onCreate "value b" from onPostExecute

Note that in onPostExecute your Task was concluded and the value of 'b' was updated. While in the second call (right after starting the task) the value is still "s".

  String ad =  dataa.getString("bnl");
  data = ad;
  Log.e(TAG, "Response.data from url: " + data);

The actual code that would works is:

public class MainActivity extends ActionBarActivity {

DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;

final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// This string will hold the results
String data = "";
private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://yourdomain.com/test.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
    new GetAd().execute();

  }

void startTheThingWithData(){
   mNativeExpressAdView.setAdUnitId(data);
   //Here data has value
   Log.e(data, data);
}
 /**
 * Async task class to get json by making HTTP call
 */
private class GetAd extends AsyncTask<Void, Void, Void> {

    @Override
protected void onPreExecute() {
    super.onPreExecute();
    // Showing progress dialog
    pDialog = new ProgressDialog(MainActivity.this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
    HttpHandler sh = new HttpHandler();

    // Making a request to url and getting response
    String jsonStr = sh.makeServiceCall(url);

    Log.e(TAG, "Response from url: " + jsonStr);

    if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            JSONObject dataa = jsonObj.getJSONObject("main1");
              String ad =  dataa.getString("bnl");
            data = ad;



        } catch (final JSONException e) {
            Log.e(TAG, "Json parsing error: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }
    } else {
        Log.e(TAG, "Couldn't get json from server.");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Couldn't get json from server. Check LogCat for possible errors!",
                        Toast.LENGTH_LONG)
                        .show();
            }
        });

    }

    return null;
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    // Dismiss the progress dialog
    if (pDialog.isShowing())
        pDialog.dismiss();
    startTheThingWithData();
}}

Note I added a callback method on the Activity and called it from the onPostExecute

Sign up to request clarification or add additional context in comments.

16 Comments

yes, i use the log just to see what im getting from the code, what im trying to do is store the value of "bnl" in the declared empty string String data = "";
Check my answer, you are printlning the jsonStr not the data variable, your variable is already correct
yes, but when i execute the code the String data = ""; doesnt store the string ad value, do you think it should be store on the doInBackground
Show where you trying to use the variable, just to say, your variable will be filled ONLY after onPostExecute is done, and you may start using that there
sample: Exactly after new GetAd().execute(); the variable will still be empty, you need to do whatever you want with its value after onPostExecute
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.