I need to receive the "extract" part of the following Json:
https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=turkey
With my current code i receive the whole Json and dont really know how to go on:
public class MainActivity extends AppCompatActivity {
private Button btnSendRequest;
private TextView tvText;
private RequestQueue mRequestQueue;
private StringRequest stringRequest;
private JsonObjectRequest jsonObjectRequest;
private String url = "https://de.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=ilmenau";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendRequest = (Button) findViewById(R.id.btnSendRequest);
tvText = (TextView) findViewById(R.id.tvText);
btnSendRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//send request and print the response using volley library
sendRequestAndPrintResponse();
}
});
}
private void sendRequestAndPrintResponse() {
mRequestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
tvText.setText("Response : " + response.toString());
// Log.i(TAG,"Response : " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tvText.setText("Error : " + error.toString());
//Log.i(TAG,"Error : " + error.toString());
}
});
mRequestQueue.add(jsonObjectRequest);
}
}
So currently I am getting the whole Json back, but I only need to get the "extract" part of the Json.
Can anyone help me?
Try this
try {
JSONObject jsonObject = new JSONObject(response.toString());
Iterator < String > keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
Log.v("key", key);
Log.v("value", value);
if (key.equals("query")) {
JSONObject jsonObject1 = new JSONObject(jsonObject.getString(key));
Iterator < String > keysinner = jsonObject1.keys();
while (keysinner.hasNext()) {
String key1 = keysinner.next();
String value1 = jsonObject1.getString(key1);
Log.e("key1", key1);
Log.e("value1", value1);
if (key1.equals("pages")) {
JSONObject jsonObject2 = new JSONObject(jsonObject1.getString(key1));
Iterator < String > keyPagenumber = jsonObject2.keys();
while (keyPagenumber.hasNext()) {
String keyPageNumber = keyPagenumber.next();
String valuePagenumber = jsonObject2.getString(keyPageNumber);
Log.e("Pages key :", keyPageNumber);
Log.e("Pages value :", valuePagenumber);
if (key1.equals("pages")) {
JSONObject jsonObjectPages = new JSONObject(jsonObject2.getString(keyPageNumber));
Iterator < String > keyPages = jsonObjectPages.keys();
while (keyPages.hasNext()) {
String keyPageDetail = keyPages.next();
String valuePageDetail = jsonObjectPages.getString(keyPageDetail);
Log.e("PagesDetail key :", keyPageDetail);
Log.e("PagesDetail value :", valuePageDetail);
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
OUTPUT
Use GSON library!
So let's say that you deduce the whole json content of your jsonObjectRequest as a string that i will name theWholeContentOfYourJsonObjectRequestAsAString
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(theWholeContentOfYourJsonObjectRequestAsAString);
JsonObject jsonObject = jsonTree.getAsJsonObject();
JsonElement f1 = jsonObject.get("extract");
Something like
JSONObject pages = response.getJSONObject("query").getJSONObject("pages");
JSONObject firstPage = pages.getJSONObject(pages.names().get(0));
String extract = firstPage.getString("extract");
should work.
To extract a piece of JSON Object (another JSON Object, Integer, String etc.) you don't have to use any external libraries like GSON.
You can manage it with the following code.
JSONObject jObj = new JSONObject(response);
String InterestString = jObj.getJSONObject("local").getString("interests");
private void sendRequestAndPrintResponse() {
mRequestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject query = response.getJSONObject("query");
JSONObject pages = query.getJSONObject("pages");
JSONObject nos = pages.getJSONObject("11125639");
String extract = nos.getString("extract");
Log.e(TAG, "onResponse: " + extract);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tvText.setText("Error : " + error.toString());
//Log.i(TAG,"Error : " + error.toString());
}
});
mRequestQueue.add(jsonObjectRequest);
}
modify your code add these lines like this you should get extract
Related
// I've declared everything here, everything looks fine from here. I don't think i have problems here
public class MainActivity extends AppCompatActivity {
private TextView mTextViewResult;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
mQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://fetch-hiring.s3.amazonaws.com/hiring.json";
// I don't know what my problem is here, i've declared everything and nothing is showing up, I was thinking i should've declared an array instead of an Object, but im still having difficulties
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
Since the response is a Json Array, you need to use JsonArrayRequest instead of JsonObjectRequest, and receive a JSONArray in onResponse.
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<org.json.JSONArray>() {
#Override
public void onResponse(org.json.JSONArray response) {
try {
for (int i = 0; i < response.length(); i++){
..... etc.
See https://javadoc.io/static/com.android.volley/volley/1.1.1/com/android/volley/toolbox/JsonArrayRequest.html
Try with following code.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++){
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
I am trying to return value from my remote server, add it to an ArrayList and display it on my drawer in Android studio but I am getting null. The first name and last name in volley contains that from my remote server, but the name ArrayList returns null
GetName.java
public List<String> getDriverName(Context contenxt){
String COMPLETE_URL = TRANSACTION_DETAIL_URL + Preferences.getDefaults("email", contenxt);
Log.i("url", COMPLETE_URL);
name = new ArrayList<String>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, COMPLETE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("info", response.toString());
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("success");
if (jsonArray.length() > 0){
for (int i=0; i <= jsonArray.length()-1; i++){
JSONObject productJson = jsonArray.getJSONObject(i);
first_name =productJson.getString("firstName");
last_name = productJson.getString("lastName");
name.add(first_name);
name.add(last_name);
Log.d(null, "onResponse: " + last_name);
}
}else{
first_name = "";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
first_name = ""; }
});
int socketTimeout = 10000;
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
RequestQueue requestQueue = Volley.newRequestQueue(contenxt);
requestQueue.add(stringRequest);
return name;
}
Dashboard Activity
NameAndEmail nameAndEmail = new NameAndEmail();
Log.d(null, "result: " + nameAndEmail.getDriverName(getApplicationContext()));
Result
D/: result: []
W/art: Before Android 4.1, method int
android.support.v7.widget.DropDownListView.lookForSelectablePosition(int,
boolean) would have incorrectly overridden the package-private method in
android.widget.ListView
I/info: {"success":[{"firstName":"usfdh","lastName":"hseheh"}]}
D/: onResponse: hseheh
You are returning name variable before your data has not arrived.
You should process on name variable after data came and assigned to that variable.
You can do something like this:
NameAndEmail nameAndEmail = new NameAndEmail();
getDriverName(getApplicationContext()); // Remove return params from method.
Your getDriverName() method will be like:
public void getDriverName(Context contenxt){
String COMPLETE_URL = TRANSACTION_DETAIL_URL + Preferences.getDefaults("email", contenxt);
Log.i("url", COMPLETE_URL);
name = new ArrayList<String>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, COMPLETE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("info", response.toString());
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("success");
if (jsonArray.length() > 0){
for (int i=0; i <= jsonArray.length()-1; i++){
JSONObject productJson = jsonArray.getJSONObject(i);
first_name =productJson.getString("firstName");
last_name = productJson.getString("lastName");
name.add(first_name);
name.add(last_name);
Log.d(null, "onResponse: " + last_name);
/******************************
****** DO PROCESS HERE ********
******************************/
}
}else{
first_name = "";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
first_name = ""; }
});
int socketTimeout = 10000;
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
RequestQueue requestQueue = Volley.newRequestQueue(contenxt);
requestQueue.add(stringRequest);
}
Hope it will work. Thank you.
Json image link I'm trying to extract an integer from a Json Object using Volley and I can't seem to return the value. I tried to extract it as a String (worked for double values) but it's not working for my int value. The Json response and my code is below. it's the "id" I'm trying to retrieve and use as part of building a URL for another network call.
[json image link][1]
// parse Json using volley to make network call
private String parseMovieJSON(final String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
mMoviesList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject movie = jsonArray.getJSONObject(i);
//Get json data as strings
int id = movie.optInt("id");
String posterPath = movie.optString("poster_path");
String originalTitle = movie.optString("title");
String overview = movie.getString("overview");
String releaseDate = movie.optString("release_date");
String voteAverage = movie.optString("vote_average");
mMoviesList.add(new Movies(id, posterPath, originalTitle, overview, releaseDate, voteAverage));
}
myMoviesAdapter = new MyMoviesAdapter(MainActivity.this, mMoviesList);
myMoviesAdapter.setOnItemClickListener(MainActivity.this);
mRecyclerView.setAdapter(myMoviesAdapter);
myMoviesAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof NetworkError) {
if (checkConnection()) {
parseMovieJSON(url);
} else if (!checkConnection()) {
Toast.makeText(MainActivity.this, "Check Network Connection", Toast.LENGTH_LONG).show();
mMoviesList = null;
}
}
}
});
mRequestQueue.add(request);
checkConnection();
return url;
}
// network call for Trailers
private void extractTrailer(String s) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, uriBuilder(), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject results = jsonArray.getJSONObject(i);
//Get json data as strings
int idNumber = results.optInt(KEY_ID);
String movieKey = results.optString(KEY_URL);
String movieName = results.optString(KEY_NAME);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
mRequestQueue.add(request);
}
private String uriBuilder() {
// http://api.themoviedb.org/3/movie/157336/videos?api_key=### (template example)
Uri.Builder builder = Uri.parse(Constants.BASE_URL).buildUpon();
builder.appendPath("movie").
appendPath(String.valueOf(Constants.MOVIE_ID)).
appendPath("videos").
appendQueryParameter("api_key", BuildConfig.ApiKey);
return builder.build().toString();
}
I am developing an app for Downloading Images and their Description from Flickr.
I am setting Description String into GetterAndSetter Class's ArrayList and when i want to fetch the Data from that class,
even logger not Printing. And so that when i tried to set the values from stringArray onto the UI, I am getting ArrayIndexoutofBound Exception.
My Code is Following :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
LoadImages(this);
...
}
My LoadImages Method :
private void LoadImages(MainActivity mainActivity) {
if (checkInternet()) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
// Getting String Array from GetterAndSetter Class...
// Not Properly Getting from there...
List<String> Details = getterAndSetter.getStringList();
// Printing Check
for (String urls:urlList) {
Log.d("urls", urls);
}
// Printing Check
for (String title:titles) {
Log.d("titles", title);
}
// Problem is here, Not Getting
**This is not even Executing...**
for (String str: Details) {
Log.d("GetDetails", str);
}
...
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mView.show(getSupportFragmentManager(), "Loading...");
} else {
Toast.makeText(this, "Turn Internet on...", Toast.LENGTH_SHORT).show();
}
}
My ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
...
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL);
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My AddtoList Method :
public void AddtoList(String CreateURL) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Desc", response);
JSONObject root = null;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String FormattedStr = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
// Properly Working...
Log.d("Describe", FormattedStr);
// I cant say about this...
getterAndSetter.getStringList().add(FormattedStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My GetterAndSetter Class :
public final class GetterAndSetter {
private final ArrayList<String> stringList = new ArrayList<>();
public ArrayList<String> getStringList() {
return stringList;
}}
I am working on a project and below my code basically takes an array of objects and sets the Id to each object, However, when I click on my objects I would like to get that Id. I tried a local variable and I could only get the Id of the last object, how do I do this? I would like to get the value of String Answerid = currentQuestions.getString("id"); into my OnDown clicklistener.
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
String globalVar = " ";
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
public void OnDown(View view) {
System.out.println("VOTED Down");
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
}
Your click listener OnDown(View view) gets a view that was clicked. That's the only way you can identify what was clicked.
You should use View.getTag() to get the id:
Object obj = view.getTag();
The question is where can you add this code to set it:
View view = ...; // new View()?
view.setTag(object);