android api json array within array parsing java - java

I'm making a simple news app for my class and i'm using an api from The Guardian to populate my feed. I had it all working with the article Title, Date, and URL, but upon adding the Section and Author name I cant seem to get it to populate the feed. The device is saying No News Found and the log is saying "Error response code: 429"
Any help/criticism is greatly appreciated!
Activity
public class NewsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
private static final String LOG_TAG = NewsActivity.class.getName();
private static final String GUARDIAN_REQUEST_URL =
"http://content.guardianapis.com/search?section=games&order-by=newest&api-key=test&show-tags=contributor";
private static final int NEWS_LOADER_ID = 1;
private NewsAdapter mAdapter;
private TextView mEmptyStateTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_activity);
ListView newsListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
newsListView.setEmptyView(mEmptyStateTextView);
mAdapter = new NewsAdapter(this, new ArrayList<News>());
newsListView.setAdapter(mAdapter);
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
News currentNews = mAdapter.getItem(position);
Uri newsUri = Uri.parse(currentNews.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);
startActivity(websiteIntent);
}
});
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
} else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
return new NewsLoader(this, GUARDIAN_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_news);
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
updateUi(news);
}
}
private void updateUi(List<News> news) {
}
#Override
public void onLoaderReset(Loader<List<News>> loader) {
mAdapter.clear();
}
}
Adapter
public class NewsAdapter extends ArrayAdapter<News> {
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.news_list_item, parent, false);
}
News currentNews = getItem(position);
TextView titleView = (TextView) listItemView.findViewById(R.id.title);
String title = currentNews.getTitle();
titleView.setText(title);
TextView dateView = (TextView) listItemView.findViewById(R.id.date);
String dateToString = String.valueOf(currentNews.getDate());
String date = dateToString.substring(0, 10);
dateView.setText(date);
TextView authorView = (TextView) listItemView.findViewById(R.id.firstname);
String authorFirstName = currentNews.getAuthorFirstName();
authorView.setText(authorFirstName);
TextView lastNameView = (TextView) listItemView.findViewById(R.id.lastname);
String authorLastName = currentNews.getAuthorLastName();
lastNameView.setText(authorLastName);
TextView sectionView = (TextView) listItemView.findViewById(R.id.section);
String section = currentNews.getSection();
sectionView.setText(section);
return listItemView;
}
}
QueryUtils
public class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<News> fetchNewsData(String requestUrl) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<News> newss = extractResultFromJson(jsonResponse);
return newss;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
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 news JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<News> extractResultFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> newss = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject mainResponse = baseJsonResponse.getJSONObject("response");
JSONArray newsArray = mainResponse.getJSONArray("results");
for (int i = 0; i < newsArray.length(); i++) {
JSONObject currentNews = newsArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
String section = currentNews.getString("sectionName");
JSONArray tagsArray = currentNews.getJSONArray("tags");
for (int j = 0; j < tagsArray.length(); j++) {
JSONObject currentTag = tagsArray.getJSONObject(j);
String authorFirstName = currentTag.getString("firstName");
String authorLastName = currentTag.getString("lastName");
News news = new News(title, date, url, authorFirstName, authorLastName, section);
newss.add(news);
}
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
return newss;
}
}

Related

why ListView does not filled while I am using AsyncTask?

I am writing an app that uses Google book search API , what the app suppose to do is to display a list of books based on a search query that i provide within the app's code as a String, i use an AsyncTask inner class to handle the background work (making HTTP request , JSON formatting ...etc), I also have book costume adapter and book class to get the data from , my problem is the app dose not display any book in the list view .
here's my code:
My Activity:
public class MainActivity extends AppCompatActivity {
final static String bookUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=6";
private BookAdapter bookAdapter;
private ArrayList<Book> books;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
new BookAsynck().execute(bookUrl);
}
private class BookAsynck extends AsyncTask<String, Void, ArrayList<Book>> {
#Override
protected ArrayList<Book> doInBackground(String... strings) {
books = Utils.fetchBookData(bookUrl);
return books;
}
#Override
protected void onPostExecute(ArrayList<Book> books) {
bookAdapter = new BookAdapter(MainActivity.this, books);
list.setAdapter(bookAdapter);
}
}
}
My Util class :
public class Utils {
public static final String LOG_TAG = Utils.class.getSimpleName();
public static ArrayList<Book> fetchBookData(String requestUrl) {
ArrayList<Book> bookList = new ArrayList<>();
URL url = CreateURl(requestUrl);
String json = null;
try {
json = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing input stream", e);
}
bookList = extractBookData(json);
return bookList;
}
public static URL CreateURl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
//make http request and return a string containing the response
public static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
//if the url is null return empty string
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlcon = null;
InputStream inputstream = null;
try {
urlcon = (HttpURLConnection) url.openConnection();
urlcon.setRequestMethod("GET");
urlcon.setReadTimeout(1000 /*milleseconds*/);
urlcon.setConnectTimeout(1500 /*milleseconds*/);
urlcon.connect();
//if the request wass Successul (code 200)
// get the input stream and decode it
if (urlcon.getResponseCode() == 200) {
inputstream = urlcon.getInputStream();
jsonResponse = readFromStream(inputstream);
} else {
Log.e(LOG_TAG, "Error response code " + urlcon.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the book JSON results", e);
} finally {
if (urlcon != null) {
urlcon.disconnect();
}
if (inputstream != null) {
inputstream.close();
}
}
return jsonResponse;
}
//decode the inputstream into string that conatin the Jsresponse from the Server
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
public static ArrayList<Book> extractBookData(String json) {
ArrayList<Book> booklist = new ArrayList<>();
if (TextUtils.isEmpty(json)) {
return null;
}
try {
JSONObject base = new JSONObject(json);
JSONArray itemsArray = base.optJSONArray("items");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject first = itemsArray.getJSONObject(i);
JSONObject volume = new JSONObject("volumeInfo");
String title = volume.getString("title");
JSONArray authorsArray = volume.getJSONArray("authors");
String author = authorsArray.getString(0);
Book b = new Book(title, author);
booklist.add(b);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the book JSON results", e);
}
return booklist;
}
}
My Book Adapter:
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context c, ArrayList<Book> book) {
super(c, 0, book);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View list = convertView;
if (list == null) {
list = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
}
Book b = getItem(position);
TextView titleTextView = (TextView) list.findViewById(R.id.title);
titleTextView.setText(b.getName());
TextView author = (TextView) list.findViewById(R.id.author);
author.setText(b.getAuthor());
return list;
}
}
It looks like you missed calling your asynctask inside activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
new BookAsynck().execute(bookUrl);
}
Welcome to stackoverflow !!
Beginning at Android 9, requests without encryption will not work, that means HttpsURLConnection will work but HttpURLConnection will not.
Then the URL you try to connect must have a https:// access or you should include this in your manifest
android:usesCleartextTraffic="true"
Change the below line from onCreate()
ListView list = (ListView) findViewById(R.id.list);
to
list = (ListView) findViewById(R.id.list);

Lisview inside a Listview not working

I am making an android app that shows weather using OWM 5day 3hour forecast API, The ui consists of EditText to input a city name, a button to initiate the call process, a listview that will display 5 entries (five days) and each day entry includes another listview that displays decription and temperature for every 3 hours in a day,
I am able to see the listview for days but cannot see the nested listview for the hourly data. My classes include : MainActivity, WeatherAdapter to show 3hourly weather, DayAdapter to show day entries, and JsonToWeather data class that extracts data out of the Json response and make an Arraylist of data for only one particular day. I tried to log the error and highlighted the error position by a comment.
MainActivity :
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private String responseJSON = null;
ListView listView;
ArrayList<WeatherData> weatherDataArrayList;
WeatherAdapter weatherAdapter = null;
EditText cityName;
String city = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.dayList);
cityName = (EditText) findViewById(R.id.cityName);
Button load = (Button) findViewById(R.id.loadButton);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
city = cityName.getText().toString();
Log.d(TAG, "onClick: city is : " + city);
if(city == null){
Toast toast = null;
toast.makeText(MainActivity.this,"Please Enter a city before continuing",Toast.LENGTH_LONG);
toast.show();
} else {
String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + (city.toLowerCase()) + "&units=metric&appid=8b10912e19fde267f36f6cb785ee7efd";
Log.d(TAG, "onCreate: staring download task");
DownloadJSON downloadJSON = new DownloadJSON();
downloadJSON.execute(url);
Log.d(TAG, "onCreate: after downloadtask");
}
}
});
if(weatherDataArrayList == null){
Log.d(TAG, "onCreate: ArrayList is Still null");
}
}
private class DownloadJSON extends AsyncTask<String, Void, String>{
private static final String TAG = "DownloadJSON";
private String downloadJSON(String url){
StringBuilder jsonResult = new StringBuilder();
try{
URL apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int responseCode = connection.getResponseCode();
Log.d(TAG, "downloadJSON: Response code "+ responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charReader;
char[] inputBuffer = new char[500];
while(true){
charReader = reader.read(inputBuffer);
if(charReader < 0){
break;
}
if(charReader > 0){
jsonResult.append(String.copyValueOf(inputBuffer, 0, charReader));
}
}
reader.close();
return jsonResult.toString();
}catch (MalformedURLException e){
Log.e(TAG, "downloadJSON: URL is Invalid");
}catch (IOException e){
Log.e(TAG, "downloadJSON: IO Error");
}
return null;
}
#Override
protected String doInBackground(String... strings) {
Log.d(TAG, "doInBackground: url is : " + strings[0]);
String jsonResponse = downloadJSON(strings[0]);
if(jsonResponse == null){
Log.e(TAG, "doInBackground: Error downloading");
}
return jsonResponse;
}
#Override
protected void onPostExecute(String jsonResponse) {
super.onPostExecute(jsonResponse);
Log.d(TAG, "onPostExecute: json received is : " + jsonResponse);
if(jsonResponse != null){
JsonToWeatherData jtwd = new JsonToWeatherData();
weatherDataArrayList = jtwd.extractor(jsonResponse);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String date1 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date2 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date3 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date4 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date5 = simpleDateFormat.format(calendar.getTime());
ArrayList<String> days = new ArrayList<>();
days.add(date1);
days.add(date2);
days.add(date3);
days.add(date4);
days.add(date5);
DayAdapter day = new DayAdapter(MainActivity.this,R.layout.layout_day_card,days,weatherDataArrayList);
listView.setAdapter(day);
} else {
Log.d(TAG, "onPostExecute: no json recieved, city is Wrong");
Toast toast = Toast.makeText(MainActivity.this,"Please provide a valid city!",Toast.LENGTH_LONG);
toast.show();
}
}
}
}
WeatherAdapter :
public class WeatherAdapter extends ArrayAdapter<WeatherData> {
private static final String TAG = "WeatherAdapter";
private final int layoutResourceID;
private LayoutInflater layoutInflater;
private ArrayList<WeatherData> block;
public WeatherAdapter(#NonNull Context context, int resource, ArrayList<WeatherData> block) {
super(context, resource, block);
this.layoutResourceID = resource;
this.block = block;
this.layoutInflater = LayoutInflater.from(context);
Log.d(TAG, "WeatherAdapter: called constructor");
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if(convertView == null){
convertView = layoutInflater.inflate(layoutResourceID,parent,false);
}
Log.d(TAG, "getView: entered");
WeatherData weatherData = block.get(position);
TextView temp = (TextView) convertView.findViewById(R.id.temperature);
temp.setText(weatherData.getTemp());
TextView shortDesc = (TextView) convertView.findViewById(R.id.descrip);
shortDesc.setText(weatherData.getShortDesc());
return convertView;
}
}
DayAdapter :
public class DayAdapter extends ArrayAdapter<String> {
private static final String TAG = "DayAdapter";
private ArrayList<String> dayBlock;
private LayoutInflater layoutInflater;
private int layoutresourceID;
private ArrayList<WeatherData> dayWeather, fullBlock;
private Context context;
JsonToWeatherData json = new JsonToWeatherData();
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock) {
super(context, resource, dayBlock);
this.context = context;
this.dayBlock = dayBlock;
this.fullBlock = weatherBlock;
layoutInflater = LayoutInflater.from(context);
this.layoutresourceID = resource;
if(fullBlock == null){
Log.e(TAG, "DayAdapter: full block is null");
}
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
convertView = layoutInflater.inflate(layoutresourceID,parent,false);
}
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView minTempFoDay = (TextView) convertView.findViewById(R.id.minTempOfDay);
TextView maxTempFoDay = (TextView) convertView.findViewById(R.id.maxTempOfDay);
ListView weatherHolderListView = (ListView) convertView.findViewById(R.id.wHoldLV);
String dateString = dayBlock.get(position);
dayWeather = json.extractByDate(fullBlock,dateString);
if(fullBlock == null){
Log.d(TAG, "getView: fullblock is null");
}
if(dayWeather == null){
Log.d(TAG, "getView: dayweather array is null");
} else {
Log.d(TAG, "getView: dayweather is not null");
}
String test = dayWeather.get(position).getTemp(); // error occured here
Log.d(TAG, "getView: test string : " + test);
date.setText(dateString);
DecimalFormat df = new DecimalFormat(".##");
float mint = 500, maxt = 0;
String mint1 = "", maxt1 = "";
for(WeatherData data : dayWeather){
if(mint > Float.parseFloat(data.getMinTemp())){
mint = Float.parseFloat(data.getMinTemp());
mint1 = df.format(mint);
Log.d(TAG, "getView: mint : " + mint);
}
if (maxt > Float.parseFloat(data.getMaxTemp())){
maxt = Float.parseFloat(data.getMaxTemp());
maxt1 = df.format(maxt);
}
}
minTempFoDay.setText(mint1);
maxTempFoDay.setText(maxt1);
WeatherAdapter weatherAdapter = new WeatherAdapter(context,R.layout.weather_holder,dayWeather);
weatherHolderListView.setAdapter(weatherAdapter);
return convertView;
}
}
JsonToWeatherData:
public class JsonToWeatherData {
private static final String TAG = "JsonToWeatherData";
public ArrayList<WeatherData> extractor(String jsonData){
Log.d(TAG, "extractor: in the method");
if(jsonData == null){
return null; // if there is no json data is received
} else {
ArrayList<WeatherData> weatherDataArrayList = new ArrayList<WeatherData>();
Log.d(TAG, "extractor: in the else field");
try{
Log.d(TAG, "extractor: in try block");
JSONObject root = new JSONObject(jsonData);
int count = root.getInt("cnt");
JSONArray wList = root.getJSONArray("list");
for (int i = 0; i < count; ++i){
WeatherData weather = new WeatherData();
JSONObject wBlock = wList.getJSONObject(i);
weather.setDate(wBlock.getString("dt_txt"));
JSONObject mainObj = wBlock.getJSONObject("main");
weather.setTemp(String.valueOf(mainObj.getDouble("temp")));
weather.setMinTemp(String.valueOf(mainObj.getDouble("temp_min")));
weather.setMaxTemp(String.valueOf(mainObj.getDouble("temp_max")));
weather.setHumidity(String.valueOf(mainObj.getInt("humidity")));
JSONArray warray = wBlock.getJSONArray("weather");
JSONObject weatherObj = warray.getJSONObject(0);
weather.setDescription(weatherObj.getString("description"));
weather.setShortDesc(weatherObj.getString("main"));
weather.setIconID(weatherObj.getString("icon"));
weatherDataArrayList.add(weather);
Log.d(TAG, "extractor: temp field is :" + weather.getTemp());
}
}catch (JSONException e){
e.printStackTrace();
}
return weatherDataArrayList;
}
}
public ArrayList<WeatherData> extractByDate(ArrayList<WeatherData> fullList,String date){
ArrayList<WeatherData> dayweatherList = new ArrayList<WeatherData>();
for( WeatherData weather : fullList ){
if( ( weather.getDate().substring(0,9) ).equals(date) ){
dayweatherList.add(weather);
}
}
return dayweatherList;
}
}
What should I do?
Error message : (
08-19 23:11:39.914 12148-12148/com.jugalmistry.apps.fivedaysofweather D/DayAdapter: getView: dayweather is not null
08-19 23:11:39.916 12148-12148/com.jugalmistry.apps.fivedaysofweather D/AndroidRuntime: Shutting down VM
08-19 23:11:39.918 12148-12148/com.jugalmistry.apps.fivedaysofweather E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jugalmistry.apps.fivedaysofweather, PID: 12148
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.jugalmistry.apps.fivedaysofweather.DayAdapter.getView(DayAdapter.java:58)
I have attempted to help you with the full code below.
I would also recommend you implement the ViewHolder pattern ViewHolder pattern example for increased performance.
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "MainActivity";
EditText cityName;
String city = null;
ListView dayListView;
ArrayList<WeatherData> weatherDataArrayList;
DayAdapter dayAdapter;
//private String responseJSON = null;
//WeatherAdapter weatherAdapter = null; // Creating this adapter within the DayAdapter
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText) findViewById(R.id.cityName);
Button load = (Button) findViewById(R.id.loadButton);
dayListView = (ListView) findViewById(R.id.dayList);
load.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
city = cityName.getText().toString();
Log.d(TAG, "onClick: city is : " + city);
if (city == null)
{
Toast toast = null;
toast.makeText(MainActivity.this,"Please Enter a city before continuing",Toast.LENGTH_LONG);
toast.show();
}
else
{
String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + (city.toLowerCase()) + "&units=metric&appid=8b10912e19fde267f36f6cb785ee7efd";
Log.d(TAG, "onCreate: staring download task");
DownloadJSON downloadJSON = new DownloadJSON();
downloadJSON.execute(url);
Log.d(TAG, "onCreate: after downloadtask");
}
}
});
}
public void SetDayListData(ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
if (dayAdapter == null)
{
dayAdapter = new DayAdapter(MainActivity.this,R.layout.layout_day_card, days, weatherDataArrayList);
dayListView.setAdapter(dayAdapter);
}
else
{
//created a new method "UpdateData" just to update the data in the adapter
dayAdapter.UpdateData(days, weatherDataArrayList);
dayAdapter.notifyDataSetChanged();
}
}
private class DownloadJSON extends AsyncTask<String, Void, String>
{
private static final String TAG = "DownloadJSON";
private String downloadJSON(String url)
{
StringBuilder jsonResult = new StringBuilder();
try
{
URL apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int responseCode = connection.getResponseCode();
Log.d(TAG, "downloadJSON: Response code "+ responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charReader;
char[] inputBuffer = new char[500];
while (true)
{
charReader = reader.read(inputBuffer);
if (charReader < 0)
{
break;
}
if (charReader > 0)
{
jsonResult.append(String.copyValueOf(inputBuffer, 0, charReader));
}
}
reader.close();
return jsonResult.toString();
}
catch (MalformedURLException e)
{
Log.e(TAG, "downloadJSON: URL is Invalid");
}
catch (IOException e)
{
Log.e(TAG, "downloadJSON: IO Error");
}
return null;
}
#Override
protected String doInBackground(String... strings)
{
Log.d(TAG, "doInBackground: url is : " + strings[0]);
String jsonResponse = downloadJSON(strings[0]);
if (jsonResponse == null)
{
Log.e(TAG, "doInBackground: Error downloading");
}
return jsonResponse;
}
#Override
protected void onPostExecute(String jsonResponse)
{
super.onPostExecute(jsonResponse);
Log.d(TAG, "onPostExecute: json received is : " + jsonResponse);
if (jsonResponse != null)
{
JsonToWeatherData jtwd = new JsonToWeatherData();
weatherDataArrayList = jtwd.extractor(jsonResponse);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String date1 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date2 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date3 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date4 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date5 = simpleDateFormat.format(calendar.getTime());
ArrayList<String> days = new ArrayList<>();
days.add(date1);
days.add(date2);
days.add(date3);
days.add(date4);
days.add(date5);
SetDayListData(days, weatherDataArrayList);
}
else
{
Log.d(TAG, "onPostExecute: no json recieved, city is Wrong");
Toast toast = Toast.makeText(MainActivity.this,"Please provide a valid city!",Toast.LENGTH_LONG);
toast.show();
}
}
}
}
public class DayAdapter extends ArrayAdapter<String>
{
private static final String TAG = "DayAdapter";
private Context context;
private LayoutInflater layoutInflater;
private int layoutresourceID;
private ArrayList<String> dayBlock;
private ArrayList<WeatherData> dayWeather, weatherBlock;
JsonToWeatherData json = new JsonToWeatherData();
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
super(context, resource, dayBlock);
this.context = context;
this.dayBlock = dayBlock;
this.weatherBlock = weatherBlock;
layoutInflater = LayoutInflater.from(context);
this.layoutresourceID = resource;
if (weatherBlock == null)
{
Log.e(TAG, "DayAdapter: full block is null");
}
}
#Override
public int getCount()
{
return dayBlock.getSize();
}
public void UpdateData(#NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
this.dayBlock = dayBlock;
this.weatherBlock = weatherBlock;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
{
convertView = layoutInflater.inflate(layoutresourceID,parent,false);
}
if (weatherBlock == null)
{
Log.d(TAG, "getView: weatherBlock is null");
return convertView;
}
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView minTempFoDay = (TextView) convertView.findViewById(R.id.minTempOfDay);
TextView maxTempFoDay = (TextView) convertView.findViewById(R.id.maxTempOfDay);
ListView weatherHolderListView = (ListView) convertView.findViewById(R.id.wHoldLV);
String dateString = dayBlock.get(position);
dayWeather = json.extractByDate(weatherBlock, dateString);
if (dayWeather == null)
{
Log.d(TAG, "getView: dayweather array is null");
return convertView;
}
if (position > dayWeather.getSize() - 1)
{
Log.d(TAG, "getView: the position is too great for the dayWeather array");
return convertView;
}
String test = dayWeather.get(position).getTemp(); // error occured here
Log.d(TAG, "getView: test string : " + test);
date.setText(dateString);
DecimalFormat df = new DecimalFormat(".##");
float mint = 500, maxt = 0;
String mint1 = "", maxt1 = "";
for (WeatherData data : dayWeather)
{
if (mint > Float.parseFloat(data.getMinTemp()))
{
mint = Float.parseFloat(data.getMinTemp());
mint1 = df.format(mint);
Log.d(TAG, "getView: mint : " + mint);
}
if (maxt > Float.parseFloat(data.getMaxTemp()))
{
maxt = Float.parseFloat(data.getMaxTemp());
maxt1 = df.format(maxt);
}
}
minTempFoDay.setText(mint1);
maxTempFoDay.setText(maxt1);
WeatherAdapter weatherAdapter = new WeatherAdapter(context, R.layout.weather_holder, dayWeather);
weatherHolderListView.setAdapter(weatherAdapter);
return convertView;
}
}

NullPointerException come out into onPostExecute Method [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainFragment extends Fragment {
//private poster_adapter movieInfos;
private ArrayAdapter<MovieInfo> movieInfos;
private String LOG_TAG = MainFragment.class.getSimpleName();
public MainFragment() {
}
#Override
public void onStart() {
super.onStart();
FetchMovieInfo update = new FetchMovieInfo();
update.execute();
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName());
/*movieInfos = new ArrayAdapter<String>(
getActivity(),
R.layout.poster_item_layout,
R.id.poster_item,
new ArrayList<String>()
);*/
View rootView = inflater.inflate(R.layout.activity_main_fragment, container, false);
// Log.d(LOG_TAG,movieInfos[]);
//infoAdapter = new poster_adapter(getActivity(), Arrays.asList(movieInfos));
GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
gridView.setAdapter(movieInfos);
return rootView;
}
public class FetchMovieInfo extends AsyncTask<Void, Void, String[]> {
String LOG_TAG = MainActivity.class.getSimpleName();
private String[] getMovieInfoFromJSON(String moviesInfoJSONStr) throws JSONException {
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName().toString());
JSONObject moviesInfoJSON = new JSONObject(moviesInfoJSONStr);
JSONArray movieInfoJSON = moviesInfoJSON.getJSONArray("results");
String[] poster_urls = new String[movieInfoJSON.length()];
for (int i = 0; i < movieInfoJSON.length(); i++) {
JSONObject movieInfo = movieInfoJSON.getJSONObject(i);
poster_urls[i] = movieInfo.getString("poster_path");
}
return poster_urls;
}
#Override
protected String[] doInBackground(Void... params) {
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName().toString());
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
String movieInfoStr = null;
try {
final String BASE_URL = "http://api.themoviedb.org/3/movie/popular?";
final String API_KEY_PARAM = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(API_KEY_PARAM, BuildConfig.OPEN_MOVIE_INFO_API_KEY)
.build();
URL url = new URL(builtUri.toString());
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
movieInfoStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error" + e);
return null;
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error" + e);
}
}
}
try {
return getMovieInfoFromJSON(movieInfoStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] results) {
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName().toString());
if (results != null) {
movieInfos.clear();
for (String movieInfo : results) {
movieInfos.add(new MovieInfo(movieInfo));
}
}
}
}
}
Here is code.
When i was debugging,NullPointerException will come out as soon as i step into onPostExecute method.
I want to put some path string into my movie info adapter.
And when i was debugging,it will stop at some other libraries instead of code i wrote.
Your ArrayAdapter movieInfos was not instantiated. So when it ran to the line
movieInfos.clear();
NullPointerException wolud come out.
In your method onCreateView,you comment these code out:
/*movieInfos = new ArrayAdapter<String>(
getActivity(),
R.layout.poster_item_layout,
R.id.poster_item,
new ArrayList<String>()
);*/
So the movieInfos is a null object,never instantiated.Please cancel commenting these code out,you should instance movieInfos before your use it.

Results not showing in the ListView Android

I've been working on an android app ... I am stuck at a point ... after getting the JSON data from the internet I am having trouble to show it in the ListView ... Below is my code ...
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.name_lst_view,
R.id.name_list_view_textview,
blogTitles
);
ListView listView = (ListView) rootView.findViewById(R.id.listview_name);
listView.setAdapter(titleAdapter);
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
}
}
}
From the above code you can see that i am getting that data through doInBackground method of AsyncTask ... Data is coming through perfectly as I can see through the logcat ... The issue is somewhere in this method which I can't seem to figure out ..
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
The above method is called in onPostExecute I mean if i print to logcat within this method I can see the results being printed but when I try to show those results in the onCreateView method results don't show up not even in the logcat ... Any help will be appreciated ... Thanks
Change your code as following:
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
ListView listView;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listview_name);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
return rootView;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.name_list_view,
R.id.name_list_view_textview,
blogTitles
);
listView.setAdapter(titleAdapter);
}
}
}
Use same array list in both update and initialize so globally declare a single array list and update it in updateList() method,
Try like this,
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];//remove this and use the
//same as you are using in adapter
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
titleAdapter.notifyDataSetChanged();//here
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
OR even you can use in onPostExecute
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
titleAdapter.notifyDataSetChanged();//here
}
find the listview : ListView listView = (ListView) rootView.findViewById(R.id.listview_name); before calling
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
and put this line listView.setAdapter(titleAdapter); in your onPostExecute method.

Android strange error

I have made an listview application, then i created a new one with fragments and want to implement listview to fragments. But when i do i got an strange error.
public class Fragment1 extends Fragment {
private ArrayList<FeedItem> feedList = null;
private ProgressBar progressbar = null;
private ListView feedListView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_row_layout, container, false);
progressbar = (ProgressBar)rootView.findViewById(R.id.progressBar);
String url = "";
new DownloadFilesTask().execute(url);
return rootView;
}
public void updateList() {
feedListView= (ListView)getActivity().findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
**feedListView.setAdapter(new CustomListAdapter(this, feedList));**
feedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
FeedItem newsData = (FeedItem) o;
**Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);**
intent.putExtra("feed", newsData);
startActivity(intent);
}
});
}
public class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
if (null != feedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.getString("title"));
item.setDate(post.getString("description"));
item.setId(post.getString("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("description"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
feedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Problems are on this lines
feedListView.setAdapter(new CustomListAdapter(this, feedList));
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
Multiple markers at this line
- Line breakpoint:Fragment1 [line: 57] - updateList()
- The constructor CustomListAdapter(Fragment1, ArrayList<FeedItem>) is
undefined
No enclosing instance of the type FeedListActivity is accessible in scope
CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = (FeedItem) listData.get(position);
holder.headlineView.setText(newsItem.getTitle());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getAttachmentUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
in this line feedListView.setAdapter(new CustomListAdapter(this, feedList)); just replace this with getActivity();

Categories

Resources