1

When I'm compiling the app it isn't updating the Textviews, even it's not showing any error on the android monitor. Can someone explain me how to map JSON to java object and array?

Main Activity.java

public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private MovieDetails mmoviedetails;
private TextView Title;
private TextView id;
private TextView releasedate;
private TextView originaltitle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Title=(TextView)findViewById(R.id.titleid);
    id=(TextView)findViewById(R.id.id);
    releasedate=(TextView)findViewById(R.id.releasedateid);
    originaltitle=(TextView)findViewById(R.id.originaltitleid);



    String forecastUrl = "https://api.themoviedb.org/3/movie/550?api_key=6d349f745d2d8b31d1bfd1cccfbd7e0";
    if (isNetworkAvailable()) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(forecastUrl)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String jsonData = response.body().string();
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mmoviedetails = getCurrentDetails(jsonData);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateDisplay();
                            }
                        });

                    } else {
                        alertUserAboutError();
                    }
                }
                catch (IOException e) {
                    Log.e(TAG, "Exception caught: ", e);
                }
                catch (JSONException e) {
                    Log.e(TAG, "Exception caught: ", e);
                }
            }
        });
    }
    else {
        Toast.makeText(this, getString(R.string.network_unavailable_message),
                Toast.LENGTH_LONG).show();
    }

    Log.d(TAG, "Main UI code is running!");
}

private void updateDisplay() {

    originaltitle.setText(mmoviedetails.getOriginal_title()+"");
    id.setText(mmoviedetails.getId()+"");
    Title.setText(mmoviedetails.getTitle()+"");
    releasedate.setText(mmoviedetails.getRelease_date()+"");
}

private MovieDetails getCurrentDetails(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    JSONObject currently = forecast.getJSONObject("JSON");

    MovieDetails moviedetails = new MovieDetails();
    moviedetails.setId(currently.getInt("Id"));
    moviedetails.setOriginal_title(currently.getString("Original_title"));
    moviedetails.setTitle(currently.getString("Title"));
    moviedetails.setRelease_date(currently.getString("Release_date"));
    return moviedetails;
}


private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }

    return isAvailable;
}

private void alertUserAboutError() {

}

MovieDetails.java

public class MovieDetails {
private String Title;
private String Release_date;
private int Id;
private String original_title;

public String getTitle() {
    return Title;
}

public void setTitle(String title) {
    Title = title;
}

public String getRelease_date() {
    return Release_date;
}

public void setRelease_date(String release_date) {
    Release_date = release_date;
}

public int getId() {
    return Id;
}

public void setId(int id) {
    Id = id;
}

public String getOriginal_title() {
    return original_title;
}

public void setOriginal_title(String original_title) {
    this.original_title = original_title;
}}

Thanks in advance.

atiqkhaled
  • 386
  • 4
  • 19

1 Answers1

0

well the api that you've mentioned is not giving and invalid api error(i am assuming you have posted a wrong one on purpose (y))
the api i am getting using my own api key is something like this

{
  "adult": false,
  "backdrop_path": "/wSJPjqp2AZWQ6REaqkMuXsCIs64.jpg",
  "belongs_to_collection": null,
  "budget": 63000000,
  "genres": [
    {
      "id": 18,
      "name": "Drama"
    }
  ],
  "homepage": "http://www.foxmovies.com/movies/fight-club",
  "id": 550,
  "imdb_id": "tt0137523",
  "original_language": "en",
  "original_title": "Fight Club",
  "overview": "A ticking-time-bomb insomniac and a slippery soap salesman     channel      primal male aggression into a shocking new form of therapy. Their      concept catches on, with underground \"fight clubs\" forming in every town, until     an eccentric gets in the way and ignites an out-of-control spiral toward     oblivion.",
  "popularity": 5.419718,
  "poster_path": "/adw6Lq9FiC9zjYEpOqfq03ituwp.jpg",
  "production_companies": [
    {
      "name": "Regency Enterprises",
      "id": 508
    },
    {
      "name": "Fox 2000 Pictures",
      "id": 711
    },
    {
      "name": "Taurus Film",
      "id": 20555
    },
    {
      "name": "Linson Films",
      "id": 54050
    },
    {
      "name": "Atman Entertainment",
      "id": 54051
    },
    {
      "name": "Knickerbocker Films",
      "id": 54052
    }
  ],
  "production_countries": [
    {
      "iso_3166_1": "DE",
      "name": "Germany"
    },
    {
      "iso_3166_1": "US",
      "name": "United States of America"
    }
  ],
  "release_date": "1999-10-14",
  "revenue": 100853753,
  "runtime": 139,
  "spoken_languages": [
    {
      "iso_639_1": "en",
      "name": "English"
    }
  ],
  "status": "Released",
  "tagline": "How much can you know about yourself if you've never been in a                   fight?",
  "title": "Fight Club",
  "video": false,
  "vote_average": 8.1,
  "vote_count": 5876
}  

now this is one big JSON value with a lot of jsonarrays and the POJO you've made i.e. MovieDetails.java doesn't have the above mentioned fields
to explain to you how a pojo is made here are a few points

  1. you have to make an individual pojo for every time content is wrapped inside { }, so there is the default root { } after that we have to make individual pojos for every JSONArray, here the json arrays are named "genres","production_companies","production countries","spoken_language" so in total 5 pojos will be made let us name them MainPojo.java,Genres.java,Prod1.java,Prod2.java,Spoken.java
  2. to make pojos an easy task you can use POJO generators online for eg. http://www.jsonschema2pojo.org/
  3. in you main pojo you will have to define arraylists of the different POJO types for ex. ArrayList genre = new ArrayList(); and same for rests

now coming to the point that how you would parse this data
for that you can use libraries like jackson or Gson
or else do it on your own using JSONObject and JSONArray classes

the elements inside {} are JSONObjects and elements wrapping [] are json arrays
here genre, production_companies,production_countries,spoken_languages are json arrays

so basically your parsing will go like this

MainPojo main = new MainPojo();
 JSONObject jo = new JSONObject(url);
 main.adult = jo.getString("adult"); //remember the string that is passed in     as argument should be same as you see in the json  and you should be using getter ans setters for assigning values
main.backdrop = jo.getString("backdrop_path"); and so on 
.  
.  
.  
.  
//now we know genres is a jsonarray so  
Genres g;

 JSONArray genres = jo.getJSONArray("genres");
  for(int i =0;i<genres.length();i++)
   {
     g  = new Genres();
     JSONObject genObject = genres.getJSONObject(i);
     g.id = genObject.getString("id");
     genres.add(g);
   }

same procedure will be followed for every other jsonarray
i would recommend you to generate the POJOs for the api from the link i have mentioned for better clarification!!

Hope it helps!

Abhishek Tiwari
  • 936
  • 10
  • 25