I am building a weather module for my app I am using accuweather api to get 5days forecast details. I have added internet permission in manifest.xml.I tried to get a log to get the weather URL and when I click the url it opens in the browser and shows the json file. This means that link is correct. But when I create a jsonobject and try to fetch data as JSON array It shows that there is no data:
Here are my codes:
MyWeatherActivity.java
public class MyWeather extends AppCompatActivity {
private final String TAG = "hello";
// TODO : If following are not used in activity then move the declaration to asynch task
private ArrayList<Weather> weatherArrayList = new ArrayList<>();
private ArrayList<String> dateArray = new ArrayList<>();
private ArrayList<String> minTempArray = new ArrayList<>();
private ArrayList<String>maxTempArray= new ArrayList<>();
private ArrayList<String> backgroundDayArray= new ArrayList<>();
private ArrayList<String>backgroundNightArray= new ArrayList<>();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_weather);
findViews();
}
protected void findViews()
{
listView = findViewById(R.id.list_item1);
startFetchWeatherDetailsAsyncTask();
}
protected void startFetchWeatherDetailsAsyncTask()
{
URL weatherUrl= NetworkUtils.buildURLForWeather();
new FetchWeatherDetails().execute(weatherUrl);
Log.d(TAG,"oncreate:weatherURL : " + weatherUrl);
}
// TODO : Please make below class static and pass all the list in execute parameters
// TODO : Not doing it will cause the memory leak and you should not access activity objects directly.
private class FetchWeatherDetails extends AsyncTask<URL,Void,String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(URL... urls) {
URL weatherUrl =urls[0];
String weatherSearchResults=null;
try {
weatherSearchResults=NetworkUtils.getResponseFromHttpUrl(weatherUrl);
} catch (IOException e) {
e.printStackTrace();
}
return weatherSearchResults;
}
#Override
protected void onPostExecute(String weatherSearchResults) {
if(weatherSearchResults !=null && !weatherSearchResults.equals("")){
weatherArrayList =parseJSON(weatherSearchResults );
}
super.onPostExecute(weatherSearchResults);
}
private ArrayList<Weather> parseJSON(String weatherSearchResults) {
if(weatherArrayList!=null){
weatherArrayList.clear();
}
if(weatherSearchResults!=null){
try {
JSONObject rootObject= new JSONObject(weatherSearchResults);
**JSONArray results= rootObject.getJSONArray("Daily Forecasts");**
// TODO : pass the context in constructor and use weakreference
Toast.makeText(getApplicationContext(),"toast:"+results,Toast.LENGTH_LONG).show();
for(int i= 0;i<results.length();i++){
Weather weather= new Weather();
JSONObject resultObj = results.getJSONObject(i);
String date = resultObj.getString("date");
dateArray.add(date);
weather.setDate(date);
JSONObject temperatureObj = resultObj.getJSONObject("Temperature");
String minTemp=temperatureObj.getJSONObject("Minimum").getString("Value");
minTempArray.add(minTemp);
weather.setMinTemp(minTemp);
String maxTemp=temperatureObj.getJSONObject("Maximum").getString("Value");
maxTempArray.add(maxTemp);
weather.setMaxTemp(maxTemp);
JSONObject backDayObj= resultObj.getJSONObject("Day");
String backday=backDayObj.getJSONObject("IconPhrase").getString("");
backgroundDayArray.add(backday);
weather.setBackgroundDay(backday);
JSONObject backNightObj =resultObj.getJSONObject("Night");
String backnight =backNightObj.getJSONObject("IconPhrase").getString("");
backgroundNightArray.add(backnight);
weather.setBackgroundNight(backnight);
weatherArrayList.add(weather);
}
if(weatherArrayList !=null){
WeatherAdapter weatherAdapter = new WeatherAdapter(MyWeather.this,weatherArrayList);
listView.setAdapter(weatherAdapter);
}else {
Toast.makeText(getApplicationContext(),"Data invalid",Toast.LENGTH_LONG).show();
}
return weatherArrayList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
}
A class for getter setter
public class Weather
{
private String date;
private String minTemp;
private String maxTemp;
private String backgroundDay;
private String backgroundNight;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMinTemp() {
return minTemp;
}
public void setMinTemp(String minTemp) {
this.minTemp = minTemp;
}
public String getMaxTemp() {
return maxTemp;
}
public void setMaxTemp(String maxTemp) {
this.maxTemp = maxTemp;
}
public String getBackgroundDay() {
return backgroundDay;
}
public void setBackgroundDay(String background) {
this.backgroundDay = background;
}
public String getBackgroundNight() {
return backgroundNight;
}
public void setBackgroundNight(String backgroundNight) {
this.backgroundNight = backgroundNight;
}
}
For connection:
package com.example.a49ersense;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class NetworkUtils {
private final static String WeatherDB_Base_URL=
"https://dataservice.accuweather.com/forecasts/v1/daily/5day/location key which I have deleted";
private final static String API_KEY="my api key which i have deleted";
private final static String PARAM_API_KEY="apikey";
private static final String TAG="hello";
public static URL buildURLForWeather(){
Uri builtUri = Uri.parse(WeatherDB_Base_URL).buildUpon()
.appendQueryParameter(PARAM_API_KEY,API_KEY)
.build();
URL url = null;
try {
url= new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
Log.d(TAG,"buildUrlForWeather:url:"+url);
return url;
}
public static String getResponseFromHttpUrl(URL url)throws IOException{
HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
try {
InputStream in= httpURLConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if(hasInput){
return scanner.next();
}else {
return null;
}
}finally {
httpURLConnection.disconnect();
}
}
}
error is:
W/System.err: org.json.JSONException: No value for Daily Forecasts
You are using Daily Forecasts which is wrong key. You should use DailyForecasts
Use
JSONArray results = rootObject.getJSONArray("DailyForecasts");
Instead of
JSONArray results = rootObject.getJSONArray("Daily Forecasts");
Related
I have built my app with one URL and it worked correctly. But there's a problem from the unmatched return of "onCreateLoader" method in the MainActivity.java.
I use a background thread to load all data without problems. The onCreateLoader method in MainActivity.java should return Loader> and there's a class NewsLoader.java that extends AsyncTaskLoader>.
I want to return new NewsLoader in the onCreateLoader method but there's an error of unmatched return for this method, even tough I have done this before in another similar app.
MainActivity.java
package com.example.newsapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.app.LoaderManager.LoaderCallbacks;
import android.app.LoaderManager;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Event>> {
private EventAdapter mAdapter;
private static final int LOADER_ID = 1;
private static final String REQUEST_URL_1 = "http://content.guardianapis.com/search?q=debates&api-key=test\n";
private static final String REQUEST_URL_2 = "https://content.guardianapis.com/search?q=debate&tag=politics/politics&from-date=2014-01-01&api-key=test\n";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView earthquakeListView = findViewById(R.id.list_of_news);
mAdapter = new EventAdapter(this, new ArrayList<Event>());
earthquakeListView.setAdapter(mAdapter);
earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Event currentEvent = mAdapter.getItem(position);
assert currentEvent != null;
Uri eventUri = Uri.parse(currentEvent.getURL());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, eventUri);
startActivity(websiteIntent);
}
});
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#NonNull
#Override
public Loader<List<Event>> onCreateLoader(int id, Bundle args) {
return new NewsLoader(MainActivity.this, REQUEST_URL_1, REQUEST_URL_2);
}
#Override
public void onLoadFinished(Loader<List<Event>> loader, List<Event> news) {
mAdapter.clear();
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader<List<Event>> loader) {
mAdapter.clear();
}
}
NewsLoader.java
package com.example.newsapp;
import android.content.Context;
import androidx.loader.content.AsyncTaskLoader;
import java.util.List;
public class NewsLoader extends AsyncTaskLoader<List<Event>> {
private static final String LOG_TAG = NewsLoader.class.getName();
private String mUrl1;
private String mUrl2;
public NewsLoader(Context context, String url1, String url2) {
super(context);
mUrl1 = url1;
mUrl2 = url2;
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public List<Event> loadInBackground() {
if (mUrl1 == null && mUrl2 == null) { return null; }
// Perform the network request, parse the response, and extract a list of earthquakes.
List<Event> news = QueryUtils.fetchNewsData(mUrl1, mUrl2);
return news;
}
}
QueryUtils.java
package com.example.newsapp;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class QueryUtils {
private static final String LOCATION_SEPARATOR = "T";
public static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<Event> fetchNewsData(String requestUrl1, String requestUrl2) {
URL url1 = createUrl(requestUrl1);
URL url2 = createUrl(requestUrl2);
String jsonResponse1 = null;
String jsonResponse2 = null;
try {
jsonResponse1 = makeHttpRequest(url1);
jsonResponse2 = makeHttpRequest(url2);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Event> news = extractEvents(jsonResponse1, jsonResponse2);
return news;
}
public static List<Event> extractEvents(String eventJSON1, String eventJSON2) {
// verify that there's data in one link at list
if (TextUtils.isEmpty(eventJSON1) && TextUtils.isEmpty(eventJSON2)) {
return null;
}
List<Event> news = new ArrayList<>();
try {
//getting results array from first link
JSONObject baseJsonResponse1 = new JSONObject(eventJSON1);
JSONObject mainObject1 = baseJsonResponse1.getJSONObject("response");
JSONArray eventArray1 = mainObject1.getJSONArray("results");
//getting results array from second link
JSONObject baseJsonResponse2 = new JSONObject(eventJSON2);
JSONObject mainObject2 = baseJsonResponse2.getJSONObject("response");
JSONArray eventArray2 = mainObject2.getJSONArray("results");
// reading required data from array of first link
for (int i = 0; i<eventArray1.length(); i++){
JSONObject currentEvent = eventArray1.getJSONObject(i);
//getting url
String webUrl = currentEvent.getString("webUrl");
//getting title
String webTitle = currentEvent.getString("webTitle");
//getting sectionName
String sectionName = currentEvent.getString("sectionName");
//getting webPublicationDate
String webPublicationDate = currentEvent.getString("webPublicationDate");
String date = "0000 - 00 - 00";
String time = "00:00:00";
if (webPublicationDate.contains(LOCATION_SEPARATOR)) {
String[] parts = webPublicationDate.split(LOCATION_SEPARATOR);
date = parts[0];
time = parts[1].substring(0, parts[1].length() - 1);
}
// Make Quake Of the Strings And Assigning it to earthquakes ArrayList<Quake>
Event quake = new Event(sectionName, webTitle, date, time, webUrl);
news.add(quake);
}
// reading required data from array of first link
for (int i = 0; i<eventArray2.length(); i++){
JSONObject currentEvent = eventArray2.getJSONObject(i);
//getting url
String webUrl = currentEvent.getString("webUrl");
//getting title
String webTitle = currentEvent.getString("webTitle");
//getting sectionName
String sectionName = currentEvent.getString("sectionName");
//getting webPublicationDate
String webPublicationDate = currentEvent.getString("webPublicationDate");
String date = "0000 - 00 - 00";
String time = "00:00:00";
if (webPublicationDate.contains(LOCATION_SEPARATOR)) {
String[] parts = webPublicationDate.split(LOCATION_SEPARATOR);
date = parts[0];
time = parts[1].substring(0, parts[1].length() - 1);
}
// Make Quake Of the Strings And Assigning it to earthquakes ArrayList<Quake>
Event quake = new Event(sectionName, webTitle, date, time, webUrl);
news.add(quake);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
// Return the list of earthquakes
return news;
}
private static URL createUrl(String requestUrl) {
URL url = null;
try {
url = new URL(requestUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}
I have found a solution.
the problem here is that Loader has been deprecated in 28-API. So, one cannot use androidx with it.
The solution here is in NewsLoader.java:
Replace: import androidx.loader.content.AsyncTaskLoader;
with: import android.content.AsyncTaskLoader;
If one needs to use a newer way: use ViewrModels
Hello I am trying to click ListView and Open URL from the ListView.
I could set the URL addresses using setter methods on the ListView, however when I try to display the URLs using Toast messages, it shows different URL.
I use for loop for adding multiple items on ListView news_ListView
If you have any suggestions, please help me out.
private NewsListAdapter newsListAdapter;
private ArrayList<NewsContents> newsContents_View;
private String title_String;
private String body_String;
private String source_String;
private String source_iconUrl_String;
private String image_Url_String;
private String url_String;
private int column_num;
private int num;
private int num_plus;
private int num_plus_plus;
private View mfooter;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView news_ListView = Objects.requireNonNull(getView()).findViewById(R.id.news_ListView);
newsContents_View = new ArrayList<>();
newsListAdapter = new NewsListAdapter(Objects.requireNonNull(getActivity()).getApplicationContext());
newsListAdapter.setNewsContents(newsContents_View);
news_ListView.setAdapter(newsListAdapter);
news_ListView.addFooterView(getfooter());
num = 0;
num_plus = num + 5;
//Set newsList
for (column_num = num; column_num < num_plus; column_num++){
//Set news to listview according to the column num
Set_Content_to_NewsList(column_num);
}
news_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),""+url_String,Toast.LENGTH_SHORT).show();
}
});
}
private void Set_Content_to_NewsList(final int column_num){
HttpRequest_News httpRequest_news = new HttpRequest_News(Objects.requireNonNull(getActivity()).getApplicationContext());
httpRequest_news.news_From_API(news_Url + news_Url1 + API_KEY, column_num, new HttpRequest_News.ApiCallback() {
#Override
public void onOkHttpResponse(String title, String body, String source, String source_iconurl, String img_url,String url) {
title_String = title;
body_String = body;
source_String = source;
source_iconUrl_String = source_iconurl;
image_Url_String = img_url;
url_String = url;
setItem(column_num,title_String,body_String,source_String,source_iconUrl_String,image_Url_String,url_String);
}
#Override
public void onOkHttpFailure(Exception exception) {}
});
}
private void setItem(int column_num,String title_String, String body_String, String source_String,String source_iconUrl_String, String image_Url_String, String url_String){
NewsContents newsContents = new NewsContents();
newsContents.setId(column_num);
newsContents.setTitle_Name(title_String);
newsContents.setBody_Name(body_String);
newsContents.setSource_Name(source_String);
newsContents.setSource_icon_imgUrl(source_iconUrl_String);
newsContents.setImgUrl(image_Url_String);
newsContents.setUrl(url_String);
newsContents_View.add(newsContents);
newsListAdapter.notifyDataSetChanged();
}
This is the HttpRequestNews class:
public class HttpRequest_News {
private Context context;
public HttpRequest_News(Context current){
this.context = current;
}
public void news_From_API(String url_news, final int index, final ApiCallback apiCallback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url_news)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
apiCallback.onOkHttpFailure(e);
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String jsonStr = Objects.requireNonNull(response.body()).string();
final String title_Str = jsonarray_news_extract_Title(jsonStr, index);
final String body_Str = jsonarray_news_extract_Body(jsonStr,index);
final String source_Str = jsonarray_news_extract_Source(jsonStr,index);
final String source_icon_url_Str = jsonarray_news_extract_icon_Source(jsonStr,index);
final String image_url_Str = jsonarray_news_extract_ImgUrl(jsonStr,index);
final String url_Str = jsonarray_news_extract_Url(jsonStr,index);
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
apiCallback.onOkHttpResponse(title_Str,body_Str,source_Str,source_icon_url_Str,image_url_Str,url_Str);
}
});
}
});
}
private String jsonarray_news_extract_Title(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_Body(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("body");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_Source(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("source");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_icon_Source(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
JSONObject jsonObject1 = jsonArray.getJSONObject(index).getJSONObject("source_info");
return jsonObject1.getString("img");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_ImgUrl(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("imageurl");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String jsonarray_news_extract_Url(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public interface ApiCallback{
void onOkHttpResponse(String title, String body, String source, String source_iconUrl, String img_url, String url);
void onOkHttpFailure(Exception exception);
}}
This is the NewsContents class:
public class NewsContents {
private long id;
private String Title_Name;
private String Body_Name;
private String Url;
private String Source_Name;
private String imgUrl;
private String source_icon_imgUrl;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle_Name() {
return Title_Name;
}
public void setTitle_Name(String title_Name) {
this.Title_Name = title_Name;
}
public String getSource_Name() {
return Source_Name;
}
public void setSource_Name(String source_Name) {
this.Source_Name = source_Name;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
this.Url = url;
}
public String getBody_Name() {
return Body_Name;
}
public void setBody_Name(String body_Name) {
Body_Name = body_Name;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getSource_icon_imgUrl() {
return source_icon_imgUrl;
}
public void setSource_icon_imgUrl(String source_icon_imgUrl) {
this.source_icon_imgUrl = source_icon_imgUrl;
}}
this is adapter for the listView
public class NewsListAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<NewsContents> newsContents;
public NewsListAdapter(Context current){
this.context = current;
this.layoutInflater = (LayoutInflater)current.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setNewsContents(ArrayList<NewsContents> newsContents){
this.newsContents = newsContents;
}
#Override
public int getCount() {
return newsContents.size();
}
#Override
public Object getItem(int position) {
return newsContents.get(position);
}
#Override
public long getItemId(int position) {
return newsContents.get(position).getId();
}
#SuppressLint({"ViewHolder", "InflateParams"})
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = layoutInflater.inflate(R.layout.news_row,parent,false);
((TextView)convertView.findViewById(R.id.News_Title)).setText(newsContents.get(position).getTitle_Name());
((TextView)convertView.findViewById(R.id.news_body)).setText(newsContents.get(position).getBody_Name());
((TextView)convertView.findViewById(R.id.news_sourceName)).setText(newsContents.get(position).getSource_Name());
((TextView)convertView.findViewById(R.id.url_text)).setText(newsContents.get(position).getUrl());
Picasso.
get().
load(newsContents.get(position).getImgUrl()).
into((ImageView) convertView.findViewById(R.id.news_img));
Picasso.
get().
load(newsContents.get(position).getSource_icon_imgUrl()).
into((ImageView) convertView.findViewById(R.id.news_icon_img));
return convertView;
}}
Thank you for reading the codes!
Your toast message is taken from 'url_String'.
The 'url_String' is updated when 'onOkHttpResponse()' is triggered.
The 'onOkHttpResponse()' is called when 'Set_Content_to_NewsList()' is triggered.
The 'Set_Content_to_NewsList()' is triggered 5 times.
The toast message will always get the latest 'url_String' and not from any other rows.
A quick fix would be to store each 'url_String' in an array, and using 'position' as an index to this array.
I have the next problem, I tried to send Arraylist<string> values from AsyncTask class to other class call graphics but I don’t know what I do wrong and how to get Arraylist<string> values in the other class, because I have a lot of sintaxis errors I my code
AsyncTask class
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//v funcional
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected ArrayList<String> doInBackground(Void... voids) {
String Id ="";
String Time ="";
String Pressure="";
ArrayList<String> IdArray = new ArrayList<String>();
ArrayList<String> TimeArray = new ArrayList<String>();
ArrayList<String> PressureArray = new ArrayList<String>();
String IdS=""+IdArray;
String TimeS=""+TimeArray;
String PresureS=""+PressureArray;
data.set(1,TimeS);
data.set(2,TimeS);
data.set(3,TimeS);
return data;
}
#Override
protected void onPostExecute(ArrayList<String> result){
super.onPostExecute(result);
Graphics.data.setText(data);
}}
The graphics class
public class Graphics extends AppCompatActivity {
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphics);
Button firstButton = (Button) findViewById(R.id.json);
data = (TextView) findViewById(R.id.msgTxt);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetch process = new fetch();
ArrayList<String> data= process.execute();
data.get(1);
}
});
}
you can create an interface which your "Graphics" implements it , and pass it to your AsyncTask class.
like this
public interface BlaBlaBla {
void doBla(ArrayList<String> myBla);
}
and in your "Graphics" :
class Graphics extends AppCompatActivity implements BlaBlaBla {
fetch process = new fetch(this);
}
and for asyncClass :
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//constructor
BlaBlaBla bla;
public fetch(BlaBlaBla bla){
this.bla=bla;
}
//when your task is complete use bla.doBla(pass your array here);
}
my solution
Fetch class
public class Fetch extends AsyncTask<Void,Void,String[][]> {
public static int KEY = 0;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected String[][] doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http:xxxxxxx/xxx.json";
String jsonStr = sh.makeServiceCall(url);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
int nTiempos=jsonObj.length();
String[] IdKeyArray = new String[nTie];
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(String.valueOf(i));
IdKeyArray[i] = c.getString("Key");
String[][] valores={IdKeyArray};
return valores;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
And this is the "call" the other class where I get the values
private String[][] valores;
Fetch process = new Fetch();
process.execute();
try {
valores=process.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
pm.setText(String.valueOf(valores[Fetch.Key][0]));
}
}
}
I am using volley to parse the Movie Details from a REST api and I am saving the parsed Data in an Arraylist of objects called detailsMovies. But I can't access the ArrayList outside the onResponse Method. I am new to Android So I dont know what to do exactly.
Any Help is appreciated!
Here's the code:`
public class MovieDetailsActivity extends AppCompatActivity {
TextView movieIdText;
private VolleySingleton volleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<MovieDetails> detailsMovies = new ArrayList<>();
// private String movieTitle ;
// private String movieSummary ;
// private int movieYear;
// private long movieRating;
// private String movieYoutubeId;
// private String movieUrlThumbnail;
// private String movieDownloadLink720p;
// private String movieQuality720p;
// private String moviefileSize720p;
// private String movieDownloadLink1080p;
// private String movieQuality1080p;
// private String moviefileSize1080p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Intent i = getIntent();
String movieId = i.getExtras().getString("movieId");
volleySingleton = VolleySingleton.getsInstance();
mRequestQueue = VolleySingleton.getmRequestQueue();
parseMovieDetails();
}
public void parseMovieDetails(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getUrl(100), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
MovieDetails movieDetails = new MovieDetails();
if (response == null || response.length() == 0) {
Toast.makeText(getApplicationContext(), "Null Object", Toast.LENGTH_LONG).show();
}
try {
JSONObject movieData = response.getJSONObject("data");
JSONObject movieDetailsObject = movieData.getJSONObject(Keys.EndPointMovieDetails.KEYS_MOVIE);
String movieTitle = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_TITLE_LONG);
long movieRating = movieDetailsObject.getInt(Keys.EndPointMovieDetails.KEYS_RATING);
String movieSynopsis = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_DESCRIPTION);
String moviePosterUrl = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_COVER);
String movieYoutubeId = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEY_YOUTUBE_ID);
movieDetails.setTitle(movieTitle);
movieDetails.setRating(movieRating);
movieDetails.setSummary(movieSynopsis);
movieDetails.setUrlThumbnail(moviePosterUrl);
movieDetails.setYoutube_id(movieYoutubeId);
detailsMovies.add(movieDetails);
JSONArray torrentDownloadLinks = movieDetailsObject.getJSONArray(Keys.EndPointMovieDetails.KEYS_TORRENTS);
for(int i=0;i<torrentDownloadLinks.length();i++) {
JSONObject urlInfo = torrentDownloadLinks.getJSONObject(i);
String urlTorrent = urlInfo.getString("url");
String quality = urlInfo.getString("quality");
String fileSize = urlInfo.getString("size");
movieDetails.setDownloadLink(urlTorrent);
movieDetails.setQuality(quality);
movieDetails.setFileSize(fileSize);
detailsMovies.add(movieDetails);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public String getUrl(int movieId){
return UrlEndPoints.URL_MOVIE_DETAILS+
UrlEndPoints.URl_CHAR_QUESTION+
UrlEndPoints.URL_PARAM_ID+movieId;
}
Define an Interface in your class and implement that.
So Simple trick here is interface with callback.
public class MovieDetailsActivity extends AppCompatActivity {
TextView movieIdText;
private VolleySingleton volleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<MovieDetails> detailsMovies = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Intent i = getIntent();
String movieId = i.getExtras().getString("movieId");
volleySingleton = VolleySingleton.getsInstance();
mRequestQueue = VolleySingleton.getmRequestQueue();
parseMovieDetails(new CallBack() {
#Override
public void onSuccess(ArrayList<MovieDetails> detailsMovies) {
// Do Stuff
}
#Override
public void onFail(String msg) {
// Do Stuff
}
});
}
public void parseMovieDetails(final CallBack onCallBack){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getUrl(100), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
MovieDetails movieDetails = new MovieDetails();
if (response == null || response.length() == 0) {
Toast.makeText(getApplicationContext(), "Null Object", Toast.LENGTH_LONG).show();
}
try {
JSONObject movieData = response.getJSONObject("data");
JSONObject movieDetailsObject = movieData.getJSONObject(Keys.EndPointMovieDetails.KEYS_MOVIE);
String movieTitle = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_TITLE_LONG);
long movieRating = movieDetailsObject.getInt(Keys.EndPointMovieDetails.KEYS_RATING);
String movieSynopsis = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_DESCRIPTION);
String moviePosterUrl = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEYS_COVER);
String movieYoutubeId = movieDetailsObject.getString(Keys.EndPointMovieDetails.KEY_YOUTUBE_ID);
movieDetails.setTitle(movieTitle);
movieDetails.setRating(movieRating);
movieDetails.setSummary(movieSynopsis);
movieDetails.setUrlThumbnail(moviePosterUrl);
movieDetails.setYoutube_id(movieYoutubeId);
detailsMovies.add(movieDetails);
JSONArray torrentDownloadLinks = movieDetailsObject.getJSONArray(Keys.EndPointMovieDetails.KEYS_TORRENTS);
for(int i=0;i<torrentDownloadLinks.length();i++) {
JSONObject urlInfo = torrentDownloadLinks.getJSONObject(i);
String urlTorrent = urlInfo.getString("url");
String quality = urlInfo.getString("quality");
String fileSize = urlInfo.getString("size");
movieDetails.setDownloadLink(urlTorrent);
movieDetails.setQuality(quality);
movieDetails.setFileSize(fileSize);
detailsMovies.add(movieDetails);
}
onCallBack.success(detailsMovies);
} catch (JSONException e) {
e.printStackTrace();
onCallBack.onFail(e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public String getUrl(int movieId){
return UrlEndPoints.URL_MOVIE_DETAILS+
UrlEndPoints.URl_CHAR_QUESTION+
UrlEndPoints.URL_PARAM_ID+movieId;
}
public interface CallBack {
void onSuccess(ArrayList<MovieDetails> detailsMovies);
void onFail(String msg);
}
I have successfully created a rest web service and it returns jsonarray which has two fields
id and city from data base.
My resr web service is
#GET
#Path("city")
#Produces("application/json")
public String getJson() {
PropertyPojo propojo=null;
ArrayList cityList = new ArrayList();
JSONArray list = new JSONArray();
Map m1 = new LinkedHashMap();
List l1 = new LinkedList();
String jsonString = null;
try{
cityList=PDao.CityList();
Iterator it=cityList.iterator();
while(it.hasNext())
{
propojo=(PropertyPojo)it.next();
m1.put(propojo.getKeyid(),propojo.getKeyvalue());
}
}catch(Exception e){
}
l1.add(m1);
jsonString = JSONValue.toJSONString(l1);
return jsonString;
}
I just need to put these values into a spinner...
My android code is
public class MainActivity extends Activity {
Spinner spinner;
private static final String SERVICE_URL = "http://192.168.1.6:8080/eSava_RestWeb/webresources/service";
private static final String TAG = "AndroidRESTClientActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.city);
}
public void retrieveSampleData(View vw) {
String sampleURL = SERVICE_URL + "/city";
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK,
this, "GETting data...");
wst.execute(new String[] { sampleURL });
}
#SuppressLint("NewApi")
public void handleResponse(String response) {
try {
// JSONObject jso = new JSONObject(response);
JSONArray json = new JSONArray(response);
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray) json;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
list.add(jsonArray.get(i).toString());
}
}
Spinner s = (Spinner) findViewById(R.id.city);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, list);
s.setAdapter(adapter);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext,
String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity()
.getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
JSONArray jsArray;
// jsArray = new JSONArray(response);
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
}
Its better to create Model class and then you can parse the response with gson.
For example,
Imagine that you have your response with two strings Name and Mail. Create a model with two strings.
public class Sample{
public Sample()
{
}
#SerializedName("Name")//if needed
String name;
#SerializedName("Email")//if needed
String email;
public void set(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void set(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
Then parse your response with gson.
Sample sample = gson.fromJson(jsonRes.toString(), Sample.class);
Then you can access the members of the object sample. Change the Sample class as you needed(with the array of strings and int. You can use ArrayList instead of Array)
String[] city= {};
String[] id= {};
JSONArray jsonDetailsObj = json.getJSONArray("cityList");
JSONObject jsonLoop = null;
int noOfPoints = jsonDetailsObj.length();
city= new String[noOfPoints];
id= new String[noOfPoints];
for (int i=0 ; i < noOfPoints ; i++)
{
jsonLoop=jsonDetailsObj.getJSONObject(i);
city [i] = jsonLoop.getString("CityName");
id[i] = jsonLoop.getString("ID");
}