-1

I try to get information from this link

and I don't get it !

This is my code:

    String s = getJSONFile();
    String myDataArray[] = {};

    try{
        JSONObject reportJSON = new JSONObject();
        JSONArray dateJSON = reportJSON.getJSONArray("terrestrial_date");

        myDataArray = new String[dateJSON.length()];
        for (int i = 0; i <dateJSON.length(); i++){
            JSONObject jsonObject = dateJSON.getJSONObject(i);
            myDataArray[i] = jsonObject.getString("terrestrial_date");
        }
}catch (JSONException e){
        e.printStackTrace();
    }

    ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.row, myDataArray);
    if (mListView != null){
        mListView.setAdapter(stringAdapter);
    }
}

this is the getJSONFile method:

public String getJSONFile() {
    String json = null;
    try {
        InputStream is = getResources().openRawResource(R.raw.weather_json);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

Thanks for help :)

Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
Bon
  • 19
  • 6

6 Answers6

0

You should use GSON librari and for the Model of this code http://www.jsonschema2pojo.org/

This is so easy.

Pabel
  • 652
  • 7
  • 15
0

terrstial_date is a String of report. try this,

String date=jsonObject.getString("terestial_date");

also your json parsing structere is not correct accroding to your json

{
"report": {
    "terrestrial_date": "2017-10-13",
    "sol": 1844,
    "ls": 73.0,
    "min_temp": -81.0,
    "min_temp_fahrenheit": -113.8,
    "max_temp": -28.0,
    "max_temp_fahrenheit": -18.4,
    "pressure": 869.0,
    "pressure_string": "Higher",
    "abs_humidity": null,
    "wind_speed": null,
    "wind_direction": "--",
    "atmo_opacity": "Sunny",
    "season": "Month 3",
    "sunrise": "2017-10-13T10:59:00Z",
    "sunset": "2017-10-13T22:43:00Z"
  }
}
UltimateDevil
  • 2,807
  • 2
  • 18
  • 31
himel
  • 500
  • 5
  • 14
0

You are doing in wrong way

1.report is a JsonObject inside your response means you have your report inside another JsonObject. First you have to parse your response to get report data

2.terrestrial_date is a string data so you have to use report.getJsonString("terrestrial_date") you are using reportJSON.getJSONArray("terrestrial_date"); which is used for Array data

For, more information get a look here How to parse JSON in Android

Try this,

String s = getJSONFile();
String terrestrial_date = "";

     try{
        JSONObject responce = new JSONObject(s);
        JSONObject report= responce.getJSONObject("report");
        terrestrial_date = report.getString("terrestrial_date");

        }catch (JSONException e){
        e.printStackTrace();
    }

EDIT

Try, Volley for fetching JSON data

First you need to add dependency of volley in build.gradle file-:

dependencies {
compile 'com.android.volley:volley:1.0.0'
}

Then use following code to fetch or parse your JSON data

// Tag used to cancel the request

String url = "http://marsweather.ingenology.com/v1/latest/?format=json";


StringRequest strReq = new StringRequest(Request.Method.GET,
                url, new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, response.toString());
                        String terrestrial_date = "";

                       try{
                          JSONObject responce = new JSONObject(response);
                          JSONObject report= responce.getJSONObject("report");
                          terrestrial_date = report.getString("terrestrial_date");

                       }catch (JSONException e){
                           e.printStackTrace();
                       }


                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "Error: " + error.getMessage());

                    }
                });


    // Adding request to request queue
Volley.newRequestQueue(this).add(strReq);

SCREENSHOT

enter image description here

As, You can see the screenshot above. I am getting response with the same code

UltimateDevil
  • 2,807
  • 2
  • 18
  • 31
0

This is how you can get response from OkHttp

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("http://marsweather.ingenology.com/v1/latest/?format=json")
  .get()
  .build();

try {
        Response response = client.newCall(request).execute();
        String json = response.body().string();
        JSONObject jsonObject = new JSONObject(json);
        JSONObject reportJson =  jsonObject.getJSONObject("report"); // your report object.
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();

    }
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
0

Put your Json file in your assets folder with .json extension and use this method to get JsonString from it

public String loadJSONFromAsset(String fileName) {
        String json = null;
        try {

            InputStream is = getAssets().open(fileName);

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

And get the String using this function like this

String jsonString = MyApplication.loadJSONFromAsset(this,"yourJsonFileName.json");

and Parse like that

try{
        JSONObject responce = new JSONObject(jsonString);
        JSONArray report= responce.getJSONObject("report");
        String terrestrial_date = report.getString("terrestrial_date");

}catch (JSONException e){
        e.printStackTrace();
    }
AbhayBohra
  • 2,047
  • 24
  • 36
0

this is my code after all the change:

  public void find_weather() {
    String url = "http://marsweather.ingenology.com/v1/latest/?format=json";

    JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONObject main_object = response.getJSONObject("results");
                JSONArray array = response.getJSONArray("");
                JSONObject object = array.getJSONObject(0);
                String date = object.getString("date");
                String tempMin = String.valueOf(main_object.getDouble("min_temp"));
                String tempMax = String.valueOf(main_object.getDouble("max_temp"));
                String atmo_opacity = object.getString("atmo_opacity");

                mMaxTemp.setText("max_temp");
                mMinTemp.setText("min_temp");
                mAtmoOpacity.setText("atmo_opacity");

                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("EEEE-MM-dd");
                String formatted_data = sdf.format(calendar.getTime());
                mDate.setText(formatted_data);

                double temp_max_int = Double.parseDouble(tempMax);
                double temp_min_int = Double.parseDouble(tempMin);

                mMaxTemp.setText(String.valueOf(i));
                mMinTemp.setText(String.valueOf(i));


            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(jor);
Bon
  • 19
  • 6