I'm new in android. I have a problem about loading the image from Json Url to ListView. ListView works only without image.
This is my json url:
{"infoBooks":[{"user_name":"carlo","title":"Title: Il potere del cane\nAuthor\/s: Don Winslow","author":"","urlImage":"https:\/\/books.google.it\/books\/content?id=qiLanQEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"},{"user_name":"ff","title":"Title: Incontro con la storia. Con espansione online. Per la Scuola media\nAuthor\/s: Luisa Benucci","author":"","urlImage":"https:\/\/books.google.it\/books\/content?id=qTzFSgAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"}]}
My SearchBooks.java :
public class SearchBooks extends AppCompatActivity {
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_books);
String strUrl = "http://192.168.1.118:8888/webappdb/listViewBooks.php";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
mListView = (ListView) findViewById(R.id.listView);
}
private String downloadUrl (String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
}catch (Exception e){
Log.d("Exception while downloading url", e.toString());
}finally {
iStream.close();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (IOException e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute(result);
}
}
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
customAdapter customAdapter = new customAdapter();
customAdapter.parse(jObject);
} catch (JSONException e) {
Log.d("JSON Exception1", e.toString());
}
customAdapter customAdapter = new customAdapter();
List<HashMap<String, Object>> books = null;
try {
books = customAdapter.parse(jObject);
} catch (Exception e){
Log.d("Exception", e.toString());
}
String infoFrom[] = {"user_name", "details"};
int infoTo[] = {R.id.user_name_search, R.id.bookDescriptionSearch};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), books, R.layout.row_list_books, infoFrom, infoTo);
return adapter;
}
#Override
protected void onPostExecute(SimpleAdapter adapter) {
mListView.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("urlImage");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("urlImage", imgUrl);
hm.put("position", i);
imageLoaderTask.execute();
}
}
}
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("urlImage");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
File cacheDirectory = getBaseContext().getCacheDir();
File tmpFile = new File (cacheDirectory.getPath() + "/wpta_" + position + ".jpeg");
FileOutputStream fOutputStream = new FileOutputStream(tmpFile);
Bitmap b = BitmapFactory.decodeStream(iStream);
b.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
hmBitmap.put("launcherImage", tmpFile.getPath());
hmBitmap.put("position", position);
return hmBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
String path = (String) result.get("launcherImage");
int position = (Integer) result.get("position");
SimpleAdapter simpleAdapter = (SimpleAdapter) mListView.getAdapter();
HashMap<String, Object> hm = (HashMap<String, Object>) simpleAdapter.getItem(position);
hm.put("launcherImage", path);
simpleAdapter.notifyDataSetChanged();
}
}
}
this is my customAdapter.java :
public class customAdapter{
public List<HashMap<String, Object>> parse(JSONObject JObject) {
JSONArray infoBooks = null;
try {
infoBooks = JObject.getJSONArray("infoBooks");
} catch (JSONException e) {
e.printStackTrace();
}
return getBooks(infoBooks);
}
private List<HashMap<String, Object>> getBooks(JSONArray infoBooks){
int booksCount = infoBooks.length();
List<HashMap<String, Object>> bookList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> book;
for(int i = 0; i < booksCount; i++) {
try {
book = getBook((JSONObject) infoBooks.get(i));
bookList.add(book);
} catch (JSONException e) {
e.printStackTrace();
}
}
return bookList;
}
private HashMap<String, Object> getBook(JSONObject jBook){
HashMap<String, Object> book = new HashMap<String, Object>();
String user_name = "";
String title = "";
String author = "";
String urlImage = "";
try {
user_name = jBook.getString("user_name");
title = jBook.getString("title");
author = jBook.getString("author");
urlImage = jBook.getString("urlImage");
String details = "Title: " + title + "\n" +
"Author/s: " + author;
book.put("user_name", user_name);
book.put("details", details);
book.put("launcherImage", R.mipmap.ic_launcher);
book.put("urlImage", urlImage);
} catch (JSONException e) {
e.printStackTrace();
}
return book;
}
}
This is my logcat :
03-10 08:56:13.194 969-1433/? E/PersonaManagerService: inState(): stateMachine is null !!
03-10 08:56:13.994 969-1585/? E/PersonaManagerService: inState(): stateMachine is null !!
03-10 08:56:14.134 5005-5562/gamingproject.sellmybooks E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
Process: gamingproject.sellmybooks, PID: 5005
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.doInBackground(SearchBooks.java:176)
at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.doInBackground(SearchBooks.java:169)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
03-10 08:56:14.244 969-1049/? E/InputDispatcher: channel '14e67292 gamingproject.sellmybooks/gamingproject.sellmybooks.Profile (server)' ~ Channel is unrecoverably broken and will be disposed!
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.264 5566-5566/? E/Zygote: v2
03-10 08:56:14.274 5566-5566/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
03-10 08:56:14.774 270-270/? E/SMD: DCD OFF
03-10 08:56:17.784 270-270/? E/SMD: DCD OFF
Thank you in advance.
Why are you making the code so complex ? Keep it simple.
I have a Demo code. Maybe it can help you.
Just Create a Model Class Which you Require. Other things are the same.
public class MainActivity extends AppCompatActivity {
private Button btnHit;
private HttpURLConnection connection = null;
private URL url;
private BufferedReader reader = null;
private StringBuffer buffer;
private ListView lvMovies;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading !! Please wait..");
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
lvMovies = (ListView) findViewById(R.id.lvMovies);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<MovieModel> doInBackground(String... params) {
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = gson.fromJson(finalObject.toString(), MovieModel.class);
movieModelList.add(movieModel);
}
return movieModelList;
} 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(List<MovieModel> result) {
super.onPostExecute(result);
dialog.dismiss();
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, result);
lvMovies.setAdapter(adapter);
// TODO Need to set Data on List
}
}
public class MovieAdapter extends ArrayAdapter {
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.ivMovieIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
holder.tvMovie = (TextView) convertView.findViewById(R.id.tvMovie);
holder.tvTagline = (TextView) convertView.findViewById(R.id.tvTagLine);
holder.tvYear = (TextView) convertView.findViewById(R.id.tvYear);
holder.tvDuration = (TextView) convertView.findViewById(R.id.tvDuration);
holder.tvDirector = (TextView) convertView.findViewById(R.id.tvDirector);
holder.rbMovieRating = (RatingBar) convertView.findViewById(R.id.rbMovie);
holder.tvCast = (TextView) convertView.findViewById(R.id.tvCast);
holder.tvStory = (TextView) convertView.findViewById(R.id.tvStory);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
holder.tvMovie.setText(movieModelList.get(position).getMovie());
holder.tvTagline.setText(movieModelList.get(position).getTagline());
holder.tvYear.setText("Year : " + movieModelList.get(position).getYear());
holder.tvDuration.setText(movieModelList.get(position).getDuration());
holder.tvDirector.setText(movieModelList.get(position).getDirector());
// Rating Bar
holder.rbMovieRating.setRating(movieModelList.get(position).getRating() / 2);
Log.v("Rating is", "" + movieModelList.get(position).getRating() / 2);
StringBuffer stringBuffer = new StringBuffer();
for (MovieModel.Cast cast : movieModelList.get(position).getCastList()) {
stringBuffer.append(cast.getName() + ", ");
}
holder.tvCast.setText(stringBuffer);
holder.tvStory.setText(movieModelList.get(position).getStory());
return convertView;
}
class ViewHolder {
private ImageView ivMovieIcon;
private TextView tvMovie;
private TextView tvTagline;
private TextView tvYear;
private TextView tvDuration;
private TextView tvDirector;
private RatingBar rbMovieRating;
private TextView tvCast;
private TextView tvStory;
}
}
}
Related
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;
}
}
So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.show();
}
#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 parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.
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.
I am creating an app where the user puts in a name into an EditText. This text is then used in a loop to see if there are any matches in the parsed JSON data. If there is a match the match will be added to an ArrayList. This array list is then adapted to a listview.
private void handleJsonNameResponse() {
if (mNameArray == null) {
// TODO: handle error
} else {
try {
ArrayList<HashMap<String, String>> namePosts = new ArrayList<HashMap<String, String>>();
HashMap<String , String> namesAndCreatedHash = new HashMap<String, String>();
for (int i = 0; i < mNameArray.length(); i++) {
JSONObject namePost = mNameArray.getJSONObject(i);
String name = namePost.getString(KEY_CONTENT);
name = Html.fromHtml(name).toString();
String created = namePost.getString(KEY_CREATED_AT);
created = Html.fromHtml(created).toString();
if ( name == mName ) {
namesAndCreatedHash.put(KEY_CONTENT, name);
namesAndCreatedHash.put(KEY_CREATED_AT, created);
namePosts.add(namesAndCreatedHash);
}
}
String[] keys = { KEY_CONTENT , KEY_CREATED_AT};
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(NameListActivity.this , namePosts, android.R.layout.simple_list_item_2,
keys ,ids);
setListAdapter(adapter);
}catch(JSONException e){
e.printStackTrace();
}
}
}
I don't see what i'm doing wrong but i keep getting this error Caused by: java.lang.NegativeArraySizeException: -1
here is the full code
public class NameListActivity extends ListActivity {
private String mName;
public static final String TAG = NameListActivity.class.getSimpleName();
private JSONArray mNameArray;
private final String KEY_CONTENT = "content";
private final String KEY_CREATED_AT = "created_at";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_list);
Intent intent = getIntent();
mName = intent.getStringExtra("name");
if (networkIsON()) {
GetNameData getNameData = new GetNameData();
getNameData.execute();
} else {
}
}
private void handleJsonNameResponse() {
if (mNameArray == null) {
// TODO: handle error
} else {
try {
ArrayList<HashMap<String, String>> namePosts = new ArrayList<HashMap<String, String>>();
HashMap<String , String> namesAndCreatedHash = new HashMap<String, String>();
for (int i = 0; i < mNameArray.length(); i++) {
JSONObject namePost = mNameArray.getJSONObject(i);
String name = namePost.getString(KEY_CONTENT);
name = Html.fromHtml(name).toString();
String created = namePost.getString(KEY_CREATED_AT);
created = Html.fromHtml(created).toString();
if ( name == mName ) {
namesAndCreatedHash.put(KEY_CONTENT, name);
namesAndCreatedHash.put(KEY_CREATED_AT, created);
namePosts.add(namesAndCreatedHash);
}
}
String[] keys = { KEY_CONTENT , KEY_CREATED_AT};
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(NameListActivity.this , namePosts, android.R.layout.simple_list_item_2,
keys ,ids);
setListAdapter(adapter);
}catch(JSONException e){
e.printStackTrace();
}
}
}
private boolean networkIsON() {
boolean isOn = false;
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
isOn = true;
}
return isOn;
}
private class GetNameData extends AsyncTask< Object , Void , JSONArray> {
#Override
protected JSONArray doInBackground(Object... objects) {
int responseCode = -1;
JSONArray jsonResponse = null;
try {
URL nameUrl = new URL("https://fast-lowlands-9315.herokuapp.com/posts.json");
HttpURLConnection connection = (HttpURLConnection) nameUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
Log.v(TAG , "" + responseCode);
if (responseCode == 200 ) {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
jsonResponse = new JSONArray(responseData);
} else {
Log.i(TAG , "unsuccessful HTTP response code" + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONArray result) {
mNameArray = result;
handleJsonNameResponse();
}
}
}
this is the error i am getting in my logcat
02-08 09:38:15.190 27892-27979/com.androidy.listactivity E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.androidy.listactivity, PID: 27892
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NegativeArraySizeException: -1
at com.androidy.listactivity.NameListActivity$GetNameData.doInBackground(NameListActivity.java:142)
at com.androidy.listactivity.NameListActivity$GetNameData.doInBackground(NameListActivity.java:121)
in this snippet,
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
you are using the return value of content length, to allocate a byte array, and in your case it is returning -1, causing the exception. A possible fix:
StringBuilder builder = new StringBuilder();
byte[] array = new byte[8092];
int read = 0;
while ((read = inputStream.read(array)) != -1) {
builder.append(new String(array, 0, read));
}
jsonResponse = new JSONArray(builder.toString());
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();