I have some issues with using multiple jsonobjects I want to use "posts" and "attachments" jsonobjects.
but I tried to use the line and another for loop for attachments jsonObject but it doesnt work.
String postInfo = jsonObject.getString("attachments");
My Json looks like this:
{"posts":[
{"title":"Title","content":"Post content"}
]
}
{"attachments":[
{"url":"http://www.something.com"}
]
}
Java code:
public class NewsActivity extends FragmentActivity {
ViewPager viewPager;
int category;
ArrayList titleList;
ArrayList postList;
ArrayList imgList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Intent i = getIntent();
category=i.getIntExtra("locationInfo",-1);
try {
String encodedCatName = URLEncoder.encode(Integer.toString(category), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://www.something.co/api/get_category_posts/?id=" + encodedCatName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
postList = new ArrayList();
titleList = new ArrayList();
imgList = new ArrayList();
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not find", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String postInfo = jsonObject.getString("posts");
Log.i("Content", postInfo);
JSONArray arr = new JSONArray(postInfo);
JSONArray attachments = jsonObject.getJSONArray("attachments");
for(int i=0; i< attachments.length(); i++){
String url = "";
url = attachments.getJSONObject(i).getString("url");
imgList.add(url);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = "";
String post = "";
title = jsonPart.getString("title");
post = jsonPart.getString("content");
if (title != "" && post != "") {
message += title + ": " + post + "\r\n";
titleList.add(title);
postList.add(post);
}
}
viewPager = (ViewPager) findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager(),category,titleList,postList,imgList);
viewPager.setAdapter(swipeAdapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find ", Toast.LENGTH_LONG);
}
}
}
}
The type related to 'attachments' is an array, therefore you should call something like:
JSONArray attachments = jsonObject.getJSONArray("attachments")
for(int i=0; i< attachments.length(); i++){
attachments.getJSONObject(i).getString("url");
}
Related
Url
private static String JSON_URL ="https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784";
ArrayList<HashMap<String,String>> friendsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
friendsList= new ArrayList<>();
lv = findViewById(R.id.listview);
GetData getData= new GetData();
getData.execute();
}
Getting the data
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e){
e.printStackTrace();
}
return current;
}
Displaying the data
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject= new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("Friends"); //name of array
for(int i = 0; i <jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey=jsonObject.getString("name");
age= jsonObject1.getString("age");
//Hashmap
HashMap<String, String> friends = new HashMap<>();
friends.put("name",namey);
friends.put("age", age);
friendsList.add(friends);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
friendsList,
R.layout.row_layout,
new String[]{"name","age"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
}
It doesnt display anything and i believe it has something to do with the url, but i am not quite sure so please help and thank you in advance
Your mocky JSON from https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784 is wrong format, you need to remove the last character
I would like to show users a list of bar near by them, without map. I have tried by PlaceLikelihoods, it works fine but I can not put any restriction on the types of place found and it shows a map.
So I searched by URL, but the Try / Catch always leads to the exception, the toast found there shows the good result but the list of recyclerview is not filled.
I found a similar problem that said to move the notifyDataSetChanged(), I have done it.
I find APIs and parsing very complicated to master so it's probably a stupid mistake but it's been 2 weeks and I have not yet succeeded.
Thanks for reading.
public class TestMap extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private LocListAdapter mAdapter;
private EmptyStateRecyclerView mLocRecView;
private ArrayList<LocListUser> data;
private double longitudeUser;
private double latitudeUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc);
data = new ArrayList<>();
mAdapter = new LocListAdapter(data, TestMap.this);
mLocRecView = findViewById(R.id.locRecView);
mLocRecView.setItemAnimator(new DefaultItemAnimator());
mLocRecView.setLayoutManager(new LinearLayoutManager(TestMap.this));
mLocRecView.setHasFixedSize(true);
//data.clear();
mLocRecView.setAdapter(mAdapter);
mLocRecView.clearStateDisplays();
longitudeUser = getIntent().getDoubleExtra("long", 151.2106085);
latitudeUser = getIntent().getDoubleExtra("lat", -33.8523341);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(TestMap.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
StringBuilder sb;
sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=").append(latitudeUser).append(",").append(longitudeUser);
sb.append("&radius=5000");
sb.append("&types=" + "bar");
sb.append("&key=API_KEY");
url = new URL(String.valueOf(sb));
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
LocListUser locList = new LocListUser();
locList.setAddress(json_data.getString("vicinity"));
locList.setId(json_data.getString("reference"));
locList.setName(json_data.getString("place_name"));
locList.setLat(json_data.getJSONObject("geometry").getJSONObject("location").getString("lat"));
locList.setLon(json_data.getJSONObject("geometry").getJSONObject("location").getString("lng"));
locList.setType(json_data.getString("types"));
locList.setLatUser(latitudeUser);
locList.setLonUser(longitudeUser);
data.add(locList);
mAdapter.notifyDataSetChanged();
}
//mAdapter.notifyDataSetChanged();
mLocRecView.invokeState(EmptyStateRecyclerView.STATE_OK);
} catch (JSONException e) { //e.toString()
e.printStackTrace();
}
}
}
}
you are using hardcoded string
JSONArray jArray = new JSONArray("results");
you have to use
JSONArray jArray = new JSONArray(result);
I am trying to display main and description from json data i take from opneweathermap. And nothing happen, but I don't have errors.
I will not include the link.
Here is my MainActivity class
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mTextView = (TextView) findViewById(R.id.textView2);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask task = new DownloadTask();
task.execute("Link");
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while(data != -1){
char current = (char) data;
result+=current;
data = inputStreamReader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Toast.makeText(getApplicationContext(), "Soem"+message,Toast.LENGTH_LONG).show();
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i=0;i<array.length();i++){
JSONObject jsonPart = array.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != ""){
message += main + ": " + description + "\r\n";
}
}
if(message != ""){
mTextView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I have included uses-permissions and i have TextView and Button that will display the data from json in my layout file.
I'm trying to troubleshoot my code, which has a array within an array, and then I want to retrieve all of the ID values inside it
private TextView tvData;
private ImageView imgtest;
String ChampionName;
String ChampionNameInLowerCase;
String item2;
String item3;
String Booked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
imgtest = (ImageView) findViewById(R.id.imageView);
// http://api.champion.gg/champion/Ekko/
new JSONTask().execute("http://api.champion.gg/champion/Ekko/");
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject finalObject = jsonarray.getJSONObject(i);
ChampionName = finalObject.getString("key");
String role = finalObject.getString("role");
String items = finalObject.getString("items");
JSONObject ItemArray = new JSONObject(items);
item2 = ItemArray.getString("mostGames");
JSONObject ItemArray2 = new JSONObject(item2);
item3 = ItemArray2.getString("items");
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
ChampionNameInLowerCase = ChampionName.toLowerCase().replaceAll("'", "");;
int id = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ChampionNameInLowerCase+"_square_0", null ,null);
imgtest.setImageResource(id);
}
}
}
And then more closely the code up for question is this section;
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
When the code directly above is added, it gives an error
org.json.JSONException: No value for id
When I delete that small snippet of code, the code produces
The problem is here Booked = finalObject2.getString("id"); use Booked = finalObject2.getInt("id");
and by the way you can use
JSONObject finalObject2 = jsonarray.getJSONObject(jsonarray2.length()-1); instead the the for (int j=0;j<jsonarray2.length();j++)
In the for-loop where you iterate over jsonarray2 you access jsonarray instead of jsonarray2 to get your JSONObject.
How can I remove any null values from an array.
public class RecipeMethodActivity extends ListActivity {
Intent myIntent;
String value;
TextView editvalue;
TextView buttonPressed;
Intent intent;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result2 = null;
final Recipe[] mRecipesArray = { new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
if(!recipes[i].name.equals(value)){
recipes[i].steps = null;
Recipe[] tmp = new Recipe[recipes.length - 1];
//int j = 0;
//for (int k = 0; k < recipes.length; k++) {
// if (j != 1) {
// tmp[j++] = recipes[i];
// }
//}
recipes = tmp;
} else {
ret.add(recipes[i].name);
}
}
return ret;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
value = getIntent().getStringExtra("searchValue");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_name=json_data.getString("recipename");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
protected void onListItemClick(ListView l, View v, int position, long id){
Intent intent = new Intent(this, MethodActivity.class);
intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
startActivity(intent);
}
}
it returns a list view which when clicked should take you to the matching recipe but if i ask for Earth Destruction I get the portal cake recipe methods.
Thanks
This line of code is a problem
intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
Instead of using mRecipesArray[position] use ret.get(position).steps
and declare ArrayList<Recipe> ret = new ArrayList<Recipe>(); outside of the FetchRecipesRawArray() method so that it can be accessed inside onListItemClick() method.
also modify your code in FetchRecipesRawArray()
else {
ret.add(recipes[i]);
}
Hope this will help you..