Json Parser with volley library - android

I was searching a solution but I could not solve it.
thats my JSON
{"Error":"","Filme":[{
"title": "Dawn of the Planet of the Apes",
"image": "http://api.androidhive.info/json/movies/1.jpg",
"rating": 8.3,
"releaseYear": 2014,
"genre": ["Action", "Drama", "Sci-Fi"]
},
{
"title": "District 9",
"image": "http://api.androidhive.info/json/movies/2.jpg",
"rating": 8,
"releaseYear": 2009,
"genre": ["Action", "Sci-Fi", "Thriller"]
},
...
...
}]}
and that's my code
// Movies json url
private static final String url = "https://d....url....";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private HorizontalListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (HorizontalListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url ,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i).getJSONObject(TAG_MOVIE);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
//Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
but the result is only a white layout. I think it is because my code don't find "Filme" variable in JSON but i don't know how to fix it.
any idea??
Thank you!!

"Filme" is not a JSONObject, it is a JSONArray actually. Simply parse it as a JSONArray :-)
EDIT:
First of all, use a StringRequest, not JSONArray, as the root of what you receive is NOT an JSONArray.
And then, once you have a simple String as a result, do something like this:
JSONObject root = new JSONObject(result);
JSONArray films = root.getJSONArray("Filme");
JSONObject obj;
for (int i = 0; i < films.length(); i++) {
obj = films.getJSONObject(i);
//Put all the parsing for a single Movie JSONObject here
}

Here is the solution that I made with “Kelevandos” help.
Maybe it can help someone.
// Request a string response from the provided URL.
StringRequest movieReq = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.d(TAG, response.toString());
hidePDialog();
JSONObject root;
try {
root = new JSONObject(response);
JSONArray films = root.getJSONArray("Filme");
JSONObject obj;
for (int i = 0; i < films.length(); i++) {
obj = films.getJSONObject(i);
//Put all the parsing for a single Movie JSONObject here
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);

Related

How to Parse nested JSON using Volley?

MainClass.java
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
private Toolbar mToolbar;
private List<Onwardflights> onwardflights;
private static final String url = "http://tripofareapi.herokuapp.com/flightapi/src=DEL&dest=BOM&depdate=20180420&arrdate=20180422"; // https: url will insert here
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flight_suggestion);
mToolbar = (Toolbar) findViewById(R.id.flight_suggestion_appbar);
Bundle bundle = getIntent().getExtras();
String from = bundle.getString("from");
String to = bundle.getString("to");
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(from + "-" + to);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setTitleTextColor(Color.WHITE);
recyclerView = (RecyclerView) findViewById(R.id.flight_suggestion_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
onwardflights = new ArrayList<>();
getdata();
}
This is what i have done
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait, while we load the data");
progressDialog.show();
//*Could not understand how to parse FARE objects*
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
Try this.
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait, while we load the data");
progressDialog.show();
//*Could not understand how to parse FARE objects*
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray returnflights = data.getJSONArray("returnflights");
JSONArray onwardflights = data.getJSONArray("onwardflights");
for (int i = 0; i < returnflights.length(); i++) {
JSONObject returnFlightChild = returnflights.getJSONObject(i);
//returnFlights objects
}
for (int i = 0; i < onwardflights.length(); i++) {
JSONObject onwardFlightsChild = onwardflights.getJSONObject(i);
//onwardFlight objects
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
First check your response format in Json formatter and validator.
Your json response has 2 json object
data
data_length
to get JSONObject form a Json user getJSONObject("key") and to get JSONArray from Json use getJSONArray("key").
As node data is a JSONObject use getJSONObject("key")` to get that.
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray jsArray1 = data.getJSONArray("returnflights");
JSONArray jsArray2 = data.getJSONArray("onwardflights");
for (int i = 0; i < jsArray1.length(); i++) {
JSONObject jo = jsArray1.getJSONObject(i);
}
..................
Check this tutorial to learn how to parse Json

How to access object>array>object>array>object in json?

I have to fetch text via json in url .
The hierarchy is given below :
object>array>object>array>object.
I want to get text with this code .But I am getting error :org.json.JSONException: No value for text
Below is the code :-
public class ListViewActivity extends Activity {
// Log tag
private static final String TAG = ListViewActivity.class.getSimpleName();
// change here url of server api
private static final String url = "http://2e9b8f52.ngrok.io/api/v1/restaurants?per_page=5&km=1&location=true&lat=19.0558306414&long=72.8339840099";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = movieList.get(position);
Intent intent = new Intent(ListViewActivity.this, SecondActivity.class);
intent.putExtra("name", movie.getName());
intent.putExtra("average_ratings", movie.getAverage_ratings());
intent.putExtra("full_address", movie.getAddress());
intent.putExtra("image_url", movie.getThumbnailUrl());
intent.putExtra("cuisine",movie.getCuisine());
intent.putExtra("cost",movie.getCost());
startActivity(intent);
}
});
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Please Keep patience.Its loading...");
pDialog.show();
// Creating volley request obj
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray
restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
//movie.setThumbnailUrl(obj.getString("image"));
movie.setThumbnailUrl(obj.getString("org_image_url"));
movie.setAverage_ratings(obj.getString("average_ratings"));
movie.setCuisine(obj.getString("cuisine"));
movie.setAddress(obj.getJSONObject("address").getString("area"));
// movie.setAddress(obj.getJSONObject("address").getString("full_address"));
movie.setCost(obj.getString("cost"));
movie.setDistance( obj.getDouble("distance"));
movie.settext(obj.getString("text"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
I am attaching snapshot of json data. In the snapshot we can see the color "Text=15% discount on bill " i have to access .
try {
String yourresponseString ="";// this string refer to your api response
JSONObject jsonObject = new JSONObject(yourresponseString);
JSONArray objJsonArray = new JSONArray(jsonObject.getString("restaurants"));
for (int i = 0; i < objJsonArray.length(); i++) {
JSONArray objInnerJsonArray = objJsonArray.getJSONObject(i).getJSONArray("restaurant_offers");
for (int j = 0; j < objInnerJsonArray.length(); j++) {
//Here you can acess youe bill discount value
JSONObject objInnerJSONObject = objInnerJsonArray.getJSONObject(j);
System.out.println("Discount==>" + objInnerJSONObject.getString("text"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You can parse like this.And using this classes you can parse any type of hierarchy.
JSONArray restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
JSONArray textJSONArray= obj.getJSONArray("restaurant_offers");
for (int j = 0; j < textJSONArray.length(); j++) {
JSONObject txtobj =textJSONArray.getJSONObject(i);
movie.settext(txtobj .getString("text"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
try this code restaurant_offers is a JSONArray so you can parse like this
You can parse like this
JSONObject apiResponseJsonObject= // Your API Response
try {
JSONArray restaurantJSONArray = apiResponseJsonObject.getJSONArray("restaurants");
// you can get any text from an object like this
restaurantJSONArray.getJSONObject(index).getString("name");
restaurantJSONArray.getJSONObject(index).getString("cost"); // Like this
//If you want to access phone numbers of specific object
JSONArray phoneJSONArray=restaurantJSONArray.getJSONObject(index).getJSONArray("phone_numbers");
// And you can get specific data from phoneNumber like this
phoneJSONArray.getJSONObject(phoneNumberIndex).getString("number");
//TO get Address, you can use like this
JSONObject addressJSONObject=restaurantJSONArray.getJSONObject(index).getJSONObject("address");
//Like this you can parse whatever you want.
} catch (JSONException e) {
e.printStackTrace();
}
You must change the for loop content like this
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
JSONArray restauranstOffersJSONArray = obj.getJSONArray("restaurants_offers");
for (int i = 0; i < restauranstOffersJSONArray.length(); i++) {
JSONObject offersObj = restauranstOffersJSONArray.get(i);
String text = offersObj.getString("text");
}

Fetch Data from JSON using volley in Fragment

I am trying to get data from a URL using volley everything is alright(no errors) but i can't see anything on opening the fragment not even progress dialogue.
You can find the reference here: Custom List View i just want to use code in a Fragment.
Thanks in advance
here's my code:
public class FragmentMain extends Fragment {
private static final String TAG = FragmentMain.class.getSimpleName();
// Movies json url
private static final String url = "http://api.example.com/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<>();
private CustomListAdapter adapter;
public FragmentMain() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ListView listView = (ListView) getActivity().findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public class FragmentMain extends Fragment {
private static final String TAG = FragmentMain.class.getSimpleName();
private static final String url = "http://api.example.com/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<>();
private CustomListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) view.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
// Inflate the layout for this fragment
return view;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}

OnClick open URL (Json, ListView) Android

hello i have a list of item (listview) in json here's the code:
listView = (ListView) v.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
And this is the Json file:
"title": "Dawn of the Planet of the Apes",
"image": "http://api.androidhive.info/json/movies/1.jpg",
"rating": 8.3,
"releaseYear": 2014,
"genre": ["Action", "Drama", "Sci-Fi"]
},
{
"title": "District 9",
"image": "http://api.androidhive.info/json/movies/2.jpg",
"rating": 8,
"releaseYear": 2009,
"genre": ["Action", "Sci-Fi", "Thriller"]
},
{
"title": "Transformers: Age of Extinction",
"image": "http://api.androidhive.info/json/movies/3.jpg",
"rating": 6.3,
"releaseYear": 2014,
"genre": ["Action", "Adventure", "Sci-Fi"]
},
{
"title": "X-Men: Days of Future Past",
"image": "http://api.androidhive.info/json/movies/4.jpg",
"rating": 8.4,
"releaseYear": 2014,
"genre": ["Action", "Sci-Fi", "Thriller"]
},
I want to put a Link in every item of the json, something like "url": "http://google.com" and that the app open the link (Action_VIEW). Sorry for my english.
Please Look into:
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
movie.setUrlLink("http://google.com");
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
}
And for Action View: Put these Code in the Click Listner:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(movie.getUrlLink())));
Note: I think You know about the how to get the data from bean.

passing json data downloaded using volley between activities

i am trying to pass data loaded into my listview with volley.i know how to pass images and text through activities but not json data.It may be a duplicate question but i wasnt helped with the other responses.
Below is my activity code:
public class Movies extends ActionBarActivity{
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://api.androidhive.info/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent newActivity2=new Intent();
setResult(RESULT_OK, newActivity2);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError){
Toast.makeText(getBaseContext(), "Bummer..There's No Internet connection!", Toast.LENGTH_LONG).show();
}};
});
// Adding request to request queue
ParseApplication.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Movies.this, Detail.class);
startActivity(intent);
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I am supposed to implement this code snippet when passing the param:
intent.putExtra("json",jsonobj.toString());
and on my second activity;
JSONObject obj=new JSONObject(getIntent().getStringExtra("json")
But i dont get what to replace "json",jsonobj.toString() with from my own activity code.please help.
Thanks in advance
i was able to figure it out and passed the title.The image is still underway.I'm jus doing this to help someone who was stuck like me.This will jus give you the clue.
insert this before onCreate():
private static String Title="title";
Then in the onClick()
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
Intent intent = new Intent(Movies.this, Detail.class);
intent.putExtra(Title, name);
startActivity(intent);
And in the second activity,retrieve it a such:
Intent i=getIntent();
String name = i.getStringExtra(Title);
TextView lblName = (TextView) findViewById(R.id.name_label);
lblName.setText(name);}
After you have placed the following before onCreate():
private static String Title="title";
Thanks guys for all the help.

Categories

Resources