Hello im new in android and thats my problem.
i have one activity where i have method to load Json file
and a method where i parse that file to my array object.
the name of the object[class with constracter] is "hotelSummary"
thats my parsing method:
public HotelSummary[] parseJson() {
String s = loadJSONFromAsset();
HotelSummary closeHotelsArray[] = {};
try {
JSONObject rootJSON = new JSONObject(s);
JSONArray hotelsJSON = rootJSON.getJSONObject("HotelListResponse").getJSONObject("HotelList").getJSONArray("HotelSummary");
closeHotelsArray = new HotelSummary[hotelsJSON.length()];
for (int i = 0; i < closeHotelsArray.length; i++) {
JSONObject jsonObject = hotelsJSON.getJSONObject(i);
HotelSummary hs = new HotelSummary();
hs.address1 = jsonObject.getString("address1");
hs.airportCode = jsonObject.getString("airportCode");
hs.hotelId = jsonObject.getInt("hotelId");
hs.confidenceRating = jsonObject.getInt("confidenceRating");
hs.hotelRating = jsonObject.getInt("hotelRating");
hs.lowRate = jsonObject.getInt("lowRate");
hs.name = jsonObject.getString("name");
hs.order = jsonObject.getInt("order");
hs.proximityDistance = jsonObject.getDouble("proximityDistance");
hs.proximityUnit = jsonObject.getString("proximityUnit");
hs.thumbNailUrl = jsonObject.getString("thumbNailUrl");
closeHotelsArray[i]= hs;
}
}catch (JSONException e) {
e.printStackTrace();
}
return closeHotelsArray;
}
ass you can see it returns me array
now i wanna pass that array to my main activity
to connect it to my listview
how can i pass the array?.
thanks for the help
and sorry for the bad english.
You can place this method in your mainActivity itself and then calling it will return the required array. Is there any restriction because of which you cannot place it in the main activity?
Related
I have the following Json Format file:
[
{
"id": 1,
"game_genre": "RPG"
},
{
"id": 2,
"game_genre": "Action"
}
]
on a remote location:
http://127.0.0.1:8000/genre/?format=json (Ddjango Format)
and i want to populate an Android spinner with the respective id so that can perform a search later depending on the id of the genre. I read the other threads but since i am new into android i don't know where to start.
i have the Json parser file included in my project
Here is the code for JSON parsing :
String json = "[ { id: 1, game_genre: RPG }, { id: 2, game_genre : Action }]";
if (json != null) {
try {
ArrayList<String> game = new ArrayList();
ArrayList<Integer> id = new ArrayList();
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
game.add(jsonObject1.getString("game_genre"));
id.add(Integer.parseInt(jsonObject1.getString("id")));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(Activity.this, "Cannot get json from server", Toast.LENGTH_SHORT).show();
}
Then you just need to pass the game ArrayList to the Spinner adapter.
How can I add items to a spinner in Android?
I have a problem pushing data to my index. My code is as follows:
Client client = new Client("APP_ID", "SEARCH_ID");
Index myIndex = client.initIndex("test");
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject()
.put("name", "Jimmie")
.put("username", "Barninger")
} catch (JSONException e) {
e.printStackTrace();
}
myIndex.addObjectAsync(jsonObject, null);
However nothing happens, and no data is visible in my dashboard. What am I doing wrong?
I had to change the api keys which previously was SEARCH_ID. I changed it to my ADMIN_API_KEY:
Client client = new Client("APP_ID", "ADMIN_API_KEY");
This is because the search-only API key can only be used for searching, while the Admin API key can change, delete or add an object.
The full code is now:
Client client = new Client("APP_ID", "ADMIN_API_KEY");
Index myIndex = client.initIndex("test");
JSONObject object = null;
try {
object = new JSONObject()
.put("username", "Jimmie")
.put("name", "Barninger");
} catch (JSONException e) {
e.printStackTrace();
}
// myIndex.addObjectAsync(object, "myID", null);
myIndex.addObjectAsync(object, "id", null);
In order to understand more, please replace the addobjectAsync line with something like this:
index.addObjectAsync(object, new CompletionHandler() {
#Override
public void requestCompleted(JSONObject content, AlgoliaException error) {
if (error != null) {
// Check what is the error Here
}
}
}
I have shopping cart program and I want to get product names using json from php file.
I can get the the json successfully from PHP file but when I put it in this class its not working and when I run the app it show nothing as name in listview !
here is part of the code:
public static List<Product> getCatalog(Resources res){
System.out.println("*****JARRAY*****" + CatalogActivity.name1);
if(catalog == null) {
catalog = new Vector<Product>();
catalog.add(new Product(name1, res
.getDrawable(R.drawable.deadoralive),
"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Watchmen", res
.getDrawable(R.drawable.watchmen),
"Watchmen by Alan Moore and Dave Gibbons", 14.99));
}
return catalog;
}
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
// System.out.println("*****JARRAY*****" + jsonMainNode.getJSONObject(0));
pro1 = jsonMainNode.getJSONObject(1);
pro2 = jsonMainNode.getJSONObject(2);
name1 = pro1.getString("name");
// System.out.println("*****JARRAY*****" + data);
System.out.println("*****JARRAY*****" + pro2);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
The code get the name1 string well but It don't show it in the listview...
I need to do something which it get the name1 from the web first, put it in getCatalog class and then make the listview and show the content...
how can I do that?
I'm parse site http://animecalendar.net with Jsoup. Аll is well parsed fine, but i have one problem. I get a mixed list of urls, but they are parsed correctly (see logs)
Code:
#Override
protected ArrayList<Order> doInBackground(String... urls) {
listItems.clear();
myAdapter.notifyDataSetChanged();
String dates = null;
String url = null;
try {
Document doc = Jsoup.connect(URL).get();
Elements main = doc.select("div.day");
for (Element m : main) {
titles = m.select("div.tooltip");
for (Element tts : titles) {
title = tts.select("td.tooltip_title h4").text();
time = tts.select("td.tooltip_info h4").text();
img = tts.select("td.tooltip_desc img[src]");
Order o = new Order();
o.setLink(URL + img.attr("src"));
o.setTextName(title);
o.setTextTime(time);
o.setTextDate(dates);
o.setDetailsUrl(URL + url); // incorrect (mixed) displayed urls list in device
listItems.add(o);
}
Elements date = m.select("h2");
for (Element m1 : date) {
dates = m1.select("a").attr("href");
}
Elements links = m.select("h3");
for (Element link : links) {
url = link.select("a").attr("href"); // parse urls from site
System.out.println(url); // in LogCat displayed correct urls list
}
}
} catch (IOException e) {
e.printStackTrace();
}
return listItems;
}
LogCat:
01-21 12:55:55.429: I/System.out(8036): /show/596/Cardfight%21%21_Vanguard%3A_Asia_Circuit_Hen
01-21 12:55:55.429: I/System.out(8036): /show/583/Inazuma_Eleven_GO_2%3A_Chrono_Stone
01-21 12:55:55.445: I/System.out(8036): /show/671/Ai_Mai_Mi_
01-21 12:55:55.445: I/System.out(8036): /show/697/Mangirl%21
etc...
As a result, I get a mixed list of urls.
Screen:
How to resolve it?
Thanks.
Problem resolved like this
Elements epBox = doc.select("div.ep_box h3");
int urlcount = 0;
for (Element ep : epBox) {
url = ep.select("a").attr("href");
if (urlcount < listItems.size()) {
Order o = (Order) listItems.get(urlcount);
o.setDetailsUrl(URL + url);
newarraylist.add(o);
}
urlcount++;
}
After making a call to the "me/home" Graph API, while parsing the JSON result, I am trying to make another query using FQL. The FQL query problem was solved in my earlier question.
The background of my implementation is: I am using a BaseAdapter and from the main activity, I am sending the data parsed from JSON using multiple ArrayLists. If I am not making the FQL query, everything is peachy. But when I introduce the FQL query, the query is always run after the adapter has been set to the ListView. This keeps causing the arrayindexoutofbound exception.
This is the code that I am using including the additional FQL query while parsing the JSON result. To keep the code short, I will include the relevant part as the rest works just fine. If more is needed, however, I will put that up too.
// GET THE POST'S LIKES COUNT
if (json_data.has("likes")) {
JSONObject feedLikes = json_data.optJSONObject("likes");
String countLikes = feedLikes.getString("count");
postLikesCountArrayList.add(countLikes);
// TEST STARTS
Runnable run = new Runnable() {
#Override
public void run() {
graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'"
+ finalThreadID + "\'";
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
Utility.mAsyncRunner.request(null, params, new LikesListener());
}
};
TestNewsFeeds.this.runOnUiThread(run);
// TEST ENDS
} else {
String countLikes = "0";
postLikesCountArrayList.add(countLikes);
}
And this is the code for the LikesListener class. It is a private class declared in the same activity:
private class LikesListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
// Log.e("response", response);
try {
JSONArray JALikes = new JSONArray(response);
// Log.v("JALikes", JALikes.toString());
for (int j = 0; j < JALikes.length(); j++) {
JSONObject JOTemp = JALikes.getJSONObject(j);
// Log.e("JOTemp", JOTemp.toString());
if (JOTemp.has("likes")) {
JSONObject optJson = JOTemp.optJSONObject("likes");
// Log.v("optJson", optJson.toString());
if (optJson.has("user_likes")) {
String getUserLikeStatus = optJson.getString("user_likes");
Log.e("getUserLikeStatus", getUserLikeStatus);
arrayLikeStatus.add(getUserLikeStatus);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have figured out using debugging that the cause of the crash is the setAdapter being called before the second query completes. I see the log's being added to logcat after the crash has occured.
Any help on a solution for this is appreciated
UPDATE: Figured out the solution almost when I was about to give up.
SOLUTION
So instead of calling the BaseRequestListener as used in the question, this modification had to be made.
try {
graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'"
+ finalThreadID + "\'";
// Log.d("finalThreadID", finalThreadID);
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
// Utility.mAsyncRunner.request(null, params, new LikesListener());
String fqlResponse = Utility.mFacebook.request(params);
// Log.e("fqlResponse", fqlResponse);
JSONArray JALikes = new JSONArray(fqlResponse);
// Log.v("JALikes", JALikes.toString());
for (int j = 0; j < JALikes.length(); j++) {
JSONObject JOTemp = JALikes.getJSONObject(j);
// Log.e("JOTemp", JOTemp.toString());
if (JOTemp.has("likes")) {
JSONObject optJson = JOTemp.optJSONObject("likes");
// Log.v("optJson", optJson.toString());
if (optJson.has("user_likes")) {
String getUserLikeStatus = optJson.getString("user_likes");
// Log.e("getUserLikeStatus", getUserLikeStatus);
arrayLikeStatus.add(getUserLikeStatus);
// Log.d("arrayLikeStatus", arrayLikeStatus.toString());
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
Hope this helps someone save time if they are stuck like I was.