I have created a news app and I wanted to pull articles from the different APIs via newsapi.org that would show up in different activities. I created
So for example, Techcrunch and Reuters. I have similar code for each activity but i switched the API link since it needs to pull from either TechCrunch and Reuters individually. Instead, only one of the activities work and the other is blank.
If i place the same API link in both activities, it works flawlessly. Please help
private void parseJSON () {
String url = "http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=*";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray =response.getJSONArray("articles");
for (int i = 0; i< jsonArray.length(); i++){
JSONObject article = jsonArray.getJSONObject(i);
String authorName = article.getString("author");
String imageUrl = article.getString("urlToImage");
String published = article.getString("publishedAt");
String description = article.getString("content");
String headline = article.getString("title");
mNewsList.add(new newsItem(imageUrl, authorName, published,description, headline ));
}
To get articles from a particular source use this URL :
https://newsapi.org/v2/top-headlines?sources=abc-news&apiKey="yourkey"
In you blank activity, do some break points and check network call returns success data or error. If network data success, then check your json parsing code to see it parses correctly.
You may try network logging interceptor to see what things are happening to your HTTP network calls.
Related
I am trying to pull Json string from url and put it into String[] inside my android application.
String i am getting from my url is "[\"What is your name?\",\"How do you do?\"]"
I am trying to create Quizz class in my app where i want to call constructor and then it pull data from url and put it into private variables.
I have tried many things but getting multiple errors (with network and other stuff) and now i am somewhere with async tasks where i got lost and think i am going totally wrong way.
Class i want to have is like this:
public class Quizz {
private String[] Questions;
public Quizz() {
// Here i want to load data from url into variable Questions
}
public String getQuestion(int id) {
return "Not implemented!";
}
}
And when i create Quizz object in my main activity i want to have questions loaded.
you can use the following article to help you decode your json
Article Link
Also, You can use JSONArray in the Following Article
Use Retrofit to Connect to API, and Use its converter to deserialize the JSON Response.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
it's very effective and has error handling built into it.
I know you are looking for a string[] array but in this case its best to use a arraylist as sizes can change when retrieving the response.
//create empty strings arraylist
List<String> strings = new Arraylist<>()
//try parse the response as a JSONarray object
try{
//get url string response as a json array
JSONArray jsonArray = (JSONArray) urlStringResponse;
//parse through json array and add to list
for(int i = 0; i < jsonArray.length(); i++){
String str = (String) jsonArray.getJSONObject(i);
strings.add(str);
}
} catch (JSONException e) {
Log.e("JSON", "Problem parsing the JSON results", e);
}
What about to use String.split() method?
val string = "[\"What is your name?\",\"How do you do?\"]"
val split: List<String> = string.subSequence(1, string.length - 1).split(',')
val array = split.toTypedArray()
array.forEach { println(it) }
And result will be
"What is your name?"
"How do you do?"
I am going to use Twitter for some semantic text analysis in a school class. I downloaded the Hosebird Client for Java and is running the FilterStreamExample.java: https://github.com/twitter/hbc/blob/master/hbc-example/src/main/java/com/twitter/hbc/example/FilterStreamExample.java
Running it, I get a lot of data about the users' profiles, their settings, background images, etc. I just want the tweeted text only. And maybe the location and username.
It may be a stupid question, but how do I make it only display the "texts" information? Right now, it just prints out everything.
// Do whatever needs to be done with messages
for (int msgRead = 0; msgRead < 1000; msgRead++) {
String msg = queue.take();
System.out.println(msg);
}
I could probably do a search for "text" in the strings themselves, but it seems a bit cumbersome. Isn't there any better way to do it?
The response from the twitter Streaming API is JSON String. Parse the string into JSON Object and get the value from the key "text"
import org.json.*;
for (int msgRead = 0; msgRead < 1000; msgRead++) {
String msg = queue.take();
JSONObject obj = new JSONObject(msg);
String text= obj.getString("text");
System.out.println(msg);
}
*Not Tested
Refer the following for parsing JSON in Java
How to parse JSON in Java
I have been trying to create a Json String with a large amount document but using the below code but i get out of range or have to wait till up to 5min b4 the String is greated any idiea how i could optimise the code?
public String getJson() throws NotesException {
...
View view1 = ...;
ViewNavigator nav =view1.createViewNav();
ViewEntry ve = nav.getFirst();
JSONObject jsonMain = new JSONObject();
JSONArray items = new JSONArray();
Document docRoot = null
while (ve != null) {
docRoot= ve.getDocument();
items.add(getJsonDocAndChildren(docRoot));
ViewEntry veTemp = nav.getNextSibling(ve);
ve.recycle();
ve = docTemp;
}
jsonMain.put("identifier", "name");
jsonMain.put("label", "name");
jsonMain.put("items", items);
return jsonMain.toJSONString();
}
private JSONObject getJsonDocAndChildren(Document doc) throws NotesException {
String name = doc.getItemValueString("Name");
JSONObject jsonDoc = new JSONObject();
jsonDoc.put("name", name);
jsonDoc.put("field", doc.getItemValueString("field"));
DocumentCollection responses = doc.getResponses();
JSONArray children = new JSONArray();
getDocEntry(name,children);//this add all doc that has the fieldwith the same value name to children
if (responses.getCount() > 0) {
Document docResponse = responses.getFirstDocument();
while (docResponse != null) {
children.add(getJsonDocAndChildren(docResponse));
Document docTemp = responses.getNextDocument(docResponse);
docResponse.recycle();
docResponse = docTemp;
}
}
jsonDoc.put("children", children);
return jsonDoc;
}
There are a few things here, ranging from general efficiency to optimizations based on how you want to use the code.
The big one that would likely speed up your processing would be to do view operations only, without cracking open the documents. Since it looks like you want to get responses indiscriminately, you could add the response documents to the original view, with the "Show responses in hierarchy" option turned on. Then, if you have columns for Name and field in the view (and no "Show responses only") columns, then a nav.getNext() walk down the view will get them in turn. By storing the entry.getIndentLevel() value for each previous entry and comparing it at the start of the loop, you could "step" up and down the JSON tree: when the indent level increases by one, create a new array and add it to the existing object; when it decreases, step up one. It may be a little conceptually awkward at first, having to track previous states in a flat loop, but it'd be much more efficient.
Another option, also having the benefit of not having to crack open each individual document, would be to have a view of the response documents categorized by #Text($REF) and then making your recursive method look more like:
public static void walkTree(final View treeView, final String documentId) {
ViewNavigator nav = treeView.createViewNavFromCategory(documentId);
nav.setBufferMaxEntries(400);
for (ViewEntry entry : nav) {
// Do code here
walkTree(treeView, entry.getUniversalID(), callback);
}
}
(That example is using the OpenNTF Domino API, but, if you're not using that, you could down-convert the for loop to the legacy style)
As a minor improvement any time you traverse through ViewNavigators, you can set view.setAutoUpdate(false) and then nav.setBufferMaxEntries(400) to improve the internal caching.
And finally, depending on your needs - say, if you're outputting the JSON directly to an HTTP response's output stream - you could use JsonWriter instead of JsonObject to stream the content out instead of building a huge object in memory. I wrote about it with some simple code here: https://frostillic.us/blog/posts/EF0B875453B3CFC285257D570072F78F
You should first determine where the time is spent in your code. Maybe it is in doc.getResponses() or responses.getNextDocument() which you did not show here.
The obvious optimization which could be done within your code snippet is the following:
Basically you have some data structure called Document and build up a corresponding in memory JSON structure consisting of JSONObjects and JSONArrays. This JSON structure is then serialized to a String and returned.
Instead of building the JSON structure you could directly use a JsonWriter (don't know what JSON library you are using but there must be something like a JsonWriter). This avoids the memory allocations for the temporary JSON structure.
In getJson() you start:
StringWriter stringOut = new StringWriter();
JsonWriter out = new JsonWriter(stringOut);
and end
return stringOut.toString();
Now everywhere where you creating JSONObjects or JSONArrays you invoke corresponding writer methods. e.g.
private void getJsonDocAndChildren(Document doc, JsonWriter out) throws NotesException {
out.name("name");
out.value(doc.getItemValueString("Name"));
out.name("field");
out.value(doc.getItemValueString("field"));
DocumentCollection responses = doc.getResponses();
if (responses.getCount() > 0) {
Document docResponse = responses.getFirstDocument();
out.startArray();
...
Hope you get the idea.
I'm designing a android application that has client and server side. The main database is in server which every android device db is trying to look like. Whenever Android device is online, the app syncs with server database(the main database). Because I can change the datas with adding, deleting or updating in the database in server(Users can't change database in Android device, a.k.a Sqlite db). After synchronization, the Sqlite db will be added, deleted or updated.
There are a lot of images in server database, and I'm sending all of data as json type from PHP.
$datas = array('cats' => $cats, 'news' => $news, 'products' => $products);
$datas_json = (object) array('datas' => $datas);
$json = json_encode($datas_json);
echo $json;
And the app reads with BufferReader.
HttpResponse response = httpclient.execute(httppost);
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
And afterwards, I'm trying to get all data is coming from server as string. There is a real problem about speed.
public String parseFromBuffer(BufferedReader rd) throws IOException
{
String line = "";
String full = "";
while ((line = rd.readLine()) != null)
{
full += line;
}
return full;
}
Because, If you think just one image may have 100.000 characters(in PHP side, I'm using base64 for images to send java and I'm decoding in java again.), imagine 1000 images! So, sometimes it takes 1-2 min to get 4-5 images with this way. After getting 'full' string(it could have 1.000.000 character!), I use jsonParser to get datas.
public jsonParser(String json_string) throws JSONException
{
json = new JSONObject(json_string);
}
...
public void parseJson() throws JSONException
{
JSONObject datas = json.getJSONObject("datas");
JSONArray cats = datas.getJSONArray("cats");
for(int i = 0; i < cats.length(); i++)
{
JSONObject c = cats.getJSONObject(i);
cat_id.add(c.getInt("cat_id"));
cat_name_tr.add(c.getString("cat_name_tr"));
cat_name_eng.add(c.getString("cat_name_eng"));
cat_upper_id.add(c.getInt("cat_upper_id"));
cat_order.add(c.getInt("cat_order"));
}
...
And finally, I insert, update or delete data which comes from jsonParser() to sqlite db.
In short, I have a problem or I need solution about speed of getting images across server-client and also in parseFromBuffer() method. You can suggest any advice, you can criticize of my way of doing this, may be I should serialize something, may be I should download all images in server to 'res' folder somehow...
Thanks in advance.
I want to share some information in google plus wall from my application.and I am trying for moment.insert, But getting 400 error . Can somebody help me
#Override
public JSONObject getGooglePlusAddUseractivities(Object token) {
Token accessToken = (Token) token;
OAuthService service = createOAuthServiceForGooglePlus();
OAuthRequest request = new OAuthRequest(Method.POST,"https://www.googleapis.com/plus/v1/people/me/moments/vault");
request.addQuerystringParameter("alt", "json");
service.signRequest(accessToken, request);
JSONObject object=new JSONObject();
try {
object.put("kind","plus#moment");
object.put("type","http://schemas.google.com/AddActivity");
JSONObject obj1=new JSONObject();
obj1.put("kind", "plus#itemScope");
obj1.put("url","https://plus.google.com/me");
obj1.put("description","Sign up now to claim and redeem your credits while shopping! ");
obj1.put("image","http://invite.png");
obj1.put("contentUrl", "www.abcd.com");
obj1.put("thumbnailUrl", "http://logo1_favicon.png");
object.putOpt("target", obj1);;
}catch(Exception ex) {
ex.printStackTrace();
}
request.addPayload(object.toString());
request.addHeader("Content-Type", "application/json");
System.out.println("request : "+request.getBodyContents());
Response response = request.send();
String responseBody = response.getBody();
JSONObject googleJSON = null;
try {
googleJSON = new JSONObject(responseBody);
}
catch (JSONException e) {
System.out.println("can not create JSON Object");
}
getting 400 error ?? anyone can tell me..... where am wrong ..!!`
It isn't clear from the documentation, but you can't provide both the target.url and most other target metadata. This is currently opened as bug 485 in the issue tracking system - please go there and star the issue to make sure they properly prioritize a fix.
If you remove the target.url value and add a target.id value, it should work.
(As an aside, this does not post in the user's stream, but will post an App Activity in their app moment vault. They must manually share the activity if they choose.)
At this time, it is not possible to programmatically write to a user's Stream. As a developer, you have two options:
Write an AppActivity (formerly known as a Moment), which writes information to Google, but not to a Google+ Stream. These activities are visible at plus.google.com/apps, and will be used by Google in additional ways over time.
Create an Interactive Post Share button, which a user must initiate. However, you can pre-fill both the text of the post and up to 10 intended recipients. The user can make changes if they want and then perform the actual share. You can learn more at https://developers.google.com/+/web/share/interactive or by watching this Google+ Developers Live episode: http://www.youtube.com/watch?v=U4Iw28jWtAY.