I used an AsyncTask to download Images from a URL and I wanted to display those images in a listview using a custom adapter. Everything else is downloading correctly, but the images just won't show in my listview. I tried different links, different methods (setImageDrawable & setImageBitmap) and nothing will work. Hopefully you guys can help me, I will post the relevant code parts.
`private int getEventsLength(String eventsUnformated) {
int count = 0;
int startPos = 0;
String find = "event {";
while (eventsUnformated.indexOf(find, startPos) != -1) {
startPos = eventsUnformated.indexOf(find, startPos) + find.length();
count++;
}
return count;
}
private Event[] getEvents(String eventsUnformated) {
ArrayList<Event> eventList = new ArrayList<Event>();
int startPos = 0;
int eventLength = getEventsLength(eventsUnformated);
for (int i = 0; i < eventLength; i++) {
ArrayList<String> weirdList = new ArrayList<String>();
while (weirdList.size() < 6) {
startPos = eventsUnformated.indexOf(':', startPos) + 1;
weirdList.add(eventsUnformated.substring(startPos, eventsUnformated.indexOf('\n', startPos)).trim());
}
Date eventDate = null;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
eventDate = dateFormat.parse(weirdList.get(2));
}
catch (ParseException ex) { }
try {
new DownloadImageTask().execute(new URL(weirdList.get(4)));
}
catch (MalformedURLException ex) { }
eventList.add(new Event(weirdList.get(0), weirdList.get(1), eventDate, eventImage, weirdList.get(3)));
}
return eventList.toArray(new Event[eventList.size()]);
}
private void populateEventListView() {
ArrayAdapter<Event> adapter = new EventListAdapter();
eventListView = (ListView) findViewById(R.id.listView2);
eventListView.setAdapter(adapter);
}
private class DownloadTask extends AsyncTask<Void, Void, Void> {
String downloadedEvents = "", downloadedChapters = "";
#Override
protected Void doInBackground(Void... params) {
try {
URL eventsUrl = new URL("myUrl/events.txt");
URL chaptersUrl = new URL("myUrl/chapters.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(eventsUrl.openStream()));
String temp = "";
String news = "";
while((temp = reader.readLine()) != null) {
news += temp + "\n";
}
reader.close();
downloadedEvents = news;
news = "";
temp = "";
reader = new BufferedReader(new InputStreamReader(chaptersUrl.openStream()));
while((temp = reader.readLine()) != null) {
news += temp + "\n";
}
reader.close();
downloadedChapters = news;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ViewFlipper newsFlipper = (ViewFlipper) findViewById(R.id.flipperNews);
Event[] Events = getEvents(downloadedEvents);
Chapter[] Chapters = getChapters(downloadedChapters);
TextView[] Labels = new TextView[Events.length];
for (int i = 0; i < Events.length; i++) {
eventList.add(Events[i]);
Labels[i] = makeNews(Events[i].getEventName());
newsFlipper.addView(Labels[i]);
}
for (int i = 0; i < Chapters.length; i++) {
chapterList.add(Chapters[i]);
}
super.onPostExecute(result);
}
}
private class EventListAdapter extends ArrayAdapter<Event> {
public EventListAdapter() {
super(MainActivity.this, R.layout.listview_event, eventList);
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View myView = convertView;
if (myView == null)
myView = getLayoutInflater().inflate(R.layout.listview_event, parent, false);
Event currentEvent = eventList.get(pos);
TextView eventName = (TextView) myView.findViewById(R.id.lblEventName);
eventName.setText(currentEvent.getEventName());
TextView eventHost = (TextView) myView.findViewById(R.id.lblHostName);
eventHost.setText(currentEvent.getHostChapter());
TextView eventDate = (TextView) myView.findViewById(R.id.lblEventDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy kk:mm");
eventDate.setText(dateFormat.format(currentEvent.getEventDate()));
TextView eventLocation = (TextView) myView.findViewById(R.id.lblEventLocation);
eventLocation.setText(currentEvent.getEventLocation());
ImageView badge = (ImageView) myView.findViewById(R.id.imgEvent);
badge.setImageDrawable(currentEvent.getEventImage());
return myView;
}
}
private class DownloadImageTask extends AsyncTask<URL,Void, Void> {
#Override
protected Void doInBackground(URL... imageUrls) {
try {
eventImage = Drawable.createFromStream(imageUrls[0].openConnection().getInputStream(), imageUrls[0].toString());
chapterImage = BitmapFactory.decodeStream(imageUrls[0].openStream());
}
catch (MalformedURLException ex) { }
catch (IOException ioException) { }
return null;
}
}`
Change your DownloadImageTask to:
private class DownloadImageTask extends AsyncTask<ImageView,Void, Bitmap> {
private ImageView imageView;
#Override
protected Void doInBackground(ImageView imv) {
URL imageURL = (URL) imv.getTag();
imageView = imv;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)(imageURL.getContent()));
} catch (MalformedURLException e) {
// Invalid URL
} catch (IOException e) {
//Problem with connecting internet, or resource is not available
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap b){
imageView.setImageBitmap(bitmap);
}
}
And in your Adapter:
badge.setImageDrawable(placeHolderImage);
badge.setTag(currentEvent.getImageURL);
new DownloadImageTask().execute(badge);
And of course you have to add getImageURL to your Event class.
Related
Currently, I have to click on the screen to get the schedule information.
I think the calender and db are loaded at the same time, but the speed at which db is loaded is slow, so it doesn't appear on the calendar right away.
But when I enter the schedule screen, I want to have the schedule information from DB appear at the bottom.
Calendar Activity: Connect to the calendar adapter and load data from the DB. When I checked on the console, the DB information is immediately imported when you enter the schedule screen.
Calendar Adapter : Bind data to the created ViewHolder, color on date (BLUE)
`
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
// get data from DB
GetData task = new GetData();
task.execute(userID);
}
private void setMonthView() {
//년 월 텍스트뷰
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
//해당 월 날짜 가져오기
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
//레이아웃 설정, 열 7개
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
setEventAdapter();
}
// 이벤트 Adapter 제공
private void setEventAdapter() {
//ID 로 목록 찾고 리스트 호출
ArrayList<Event> dailyEvents = eventsForDate(CalendarUtils.selectedDate);
EventAdapter eventAdapter = new EventAdapter(this, this, dailyEvents);
eventListView.setAdapter(eventAdapter);
}
// 새로운 이벤트 생성
public void newEventAction(View view) {
startActivity(new Intent(CalendarActivity.this, EventEditActivity.class));
}
// 재개될 때마다 다시 로드되도록 EventAdapter 호출
//Activity가 사용자와 상호작용하기 바로 전에 호출됨
#Override
protected void onResume() {
super.onResume();
setEventAdapter();
eventsList.clear();
}
// 주어진 날짜에 대한 모든 이벤트 반환
public static ArrayList<Event> eventsForDate(LocalDate date) {
events = new ArrayList<>();
for (int k = 0; k < eventsList.size(); k++) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String selectDate1 = date.toString(); //현재누른날짜
String startDate1 = eventsList.get(k).getStartdate(); //시작날짜
String endDate1 = eventsList.get(k).getEnddate(); //종료날짜
Date selectDate = null;
try {
selectDate = dateFormat.parse(selectDate1);
Date startDate = dateFormat.parse(startDate1);
Date endDate = dateFormat.parse(endDate1);
int result1 = selectDate.compareTo(startDate); // curr > d1
int result2 = selectDate.compareTo(endDate);
// 조건이 맞을때
if ((result1 >= 0) && (result2 <= 0)) //선택한 날짜가 시작날짜랑 같거나 크고 & 앤드날짜보다 작거나 같으면
events.add(eventsList.get(k)); //items.get(k)가 events 어레이에 더해짐
} catch (ParseException e) {
e.printStackTrace();
}
}
return events;
}
// 주어진 날짜에 대한 ID 반환 - 수정인지 판단
public static int eventsForID(String passedID) {
for (int i = 0; i < eventsList.size(); i++) {
String ID = eventsList.get(i).getID();
if(ID != null && passedID != null) {
//각각 일치하면 0 리턴하므로 합계 0일경우 모두 일치한다.
if (passedID.compareTo(ID)== 0) {
Log.e("compare", "ok");
return 1;
}
}
}
return 0;
}
// DB에서 이벤트 가져오기
class GetData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String errorString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(CalendarActivity.this,
"Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Log.d(TAG, "response - " + result);
if (result != null) {
mJsonString = result;
showResult();
}
}
#Override
protected String doInBackground(String... params) {
String searchKeyword1 = params[0];
String serverURL = "http://"+IP_ADDRESS+"/event_query.php";
String postParameters = "userID=" + searchKeyword1;
Log.d(TAG, "userID_event : " + searchKeyword1);
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(postParameters.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "response code - " + responseStatusCode);
InputStream inputStream;
if (responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
} else {
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
return sb.toString().trim();
} catch (Exception e) {
Log.d(TAG, "getData: Error ", e);
errorString = e.toString();
return null;
}
}
// DB에서 array로 데이터 가져옴
public void showResult() {
try {
JSONObject jsonObject = new JSONObject(mJsonString);
JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
// eventsList에 저장하기 전 저장되어있던 List를 clear한 후 가져온다
eventsList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.length() != 0) {
JSONObject item = jsonArray.getJSONObject(i);
Log.d(TAG, "JSONObject : " + item);
// 해당 키워드로 DB에서 데이터를 가져온다(ID, title...)
ID = item.getString("ID");
title = item.getString("title");
startdate = item.getString("startdate");
enddate = item.getString("enddate");
alarmactive = item.getString("alarmactive");
// 가져온 데이터 eventsList에 저장
eventsList.add(new Event(ID, title, startdate, enddate, alarmactive));
Log.d(TAG, "eventsList : " + eventsList.toString());
}
}
} catch (JSONException e) {
Log.d(TAG, "showResult_member : ", e);
}
}
}
}
`
`
class CalendarAdapter extends RecyclerView.Adapter<CalendarViewHolder>
{
private final ArrayList<LocalDate> days;
private final OnItemListener onItemListener;
#NonNull
#Override
public CalendarViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.calendar_cell, parent, false);
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = (int) (parent.getHeight() * 0.199999999); //월별 달력
return new CalendarViewHolder(view, onItemListener, days);
}
// 생성된 ViewHolder 에 데이터 바인딩
#Override
public void onBindViewHolder(#NonNull CalendarViewHolder holder, int position)
{
//날짜 변수에 담기
final LocalDate date = days.get(position);
if (date == null)
//날짜가 null인 경우 홀더 날짜를 설정
holder.dayOfMonth.setText("");
else {
//그렇지 않으면 날짜 넣기
holder.dayOfMonth.setText(String.valueOf(date.getDayOfMonth()));
//선택한 날짜 회색으로 표시
if (date.equals(CalendarUtils.selectedDate)) {
holder.parentView.setBackgroundColor(Color.LTGRAY);
}
//주말 색상 지정(토요일: BLUE, 일요일: RED)
if ((position + 1) % 7 == 0) {
holder.dayOfMonth.setTextColor(Color.BLUE);
} else if (position == 0 || position % 7 == 0) {
holder.dayOfMonth.setTextColor(Color.RED);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
for (int i = 0; CalendarActivity.eventsList.size()>i ; i++) {
Event CalendarDate1 = CalendarActivity.eventsList.get(i);
Date curr = dateFormat.parse(date.toString());
// yyyy-MM-dd
Date d1 = dateFormat.parse(CalendarDate1.startdate);
Date d2 = dateFormat.parse(CalendarDate1.enddate);
int result1 = curr.compareTo(d1); // curr > d1
int result2 = curr.compareTo(d2);
// BLUE
if ((result1 >= 0) && (result2 <= 0))
holder.parentView.setBackgroundColor(Color.parseColor("#83BBF3"));
}
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
// 전체 데이터 개수 return
#Override
public int getItemCount()
{
return days.size();
}
public interface OnItemListener
{
//해당 변수 이름은 현재날짜로 변경됨
void onItemClick(int position, LocalDate date);
}
}
`
I've moved the GetData function to another activity.
Because the code to update the data is in the calendar activity, the data is imported when the calendar is first turned on, but it cannot be modified and deleted.
My RecyclerView is returning the Boolean value 'true' for some odd reason.
I can't seem to fix the issue
This is the output I am getting
It should display text from the JSON
JSON LINK - https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=c80ddd850a524fe5975cad881d6f4aba
I am accessing the 'articles' JSON array and I want to display the title
MainActivity code:
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
MyAdapter mViewAdapter;
List<News> news_list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ParseNewsJSON().execute();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
//mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mViewAdapter = new MyAdapter(new ArrayList<News>());
mRecyclerView.setAdapter(mViewAdapter);
}
public class ParseNewsJSON extends AsyncTask<String, Void, String> {
private final String JSON_URL = "https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=c80ddd850a524fe5975cad881d6f4aba";
String result = "";
ArrayList<String> article_heading = new ArrayList<>();
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(JSON_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
mViewAdapter = new MyAdapter(news_list);
mRecyclerView.setAdapter(mViewAdapter);
mViewAdapter.notifyDataSetChanged();
super.onPostExecute(s);
}
}
}
MyAdapter Code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<News> newsArticleList;
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
//description, genre;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textView_articleHeading);
// description = (TextView) itemView.findViewById(R.id.textView_description);
// image = (TextView) itemView.findViewById(R.id.rating);
}
}
public MyAdapter (List<News> newsArticleList){
this.newsArticleList = newsArticleList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
News news = newsArticleList.get(position);
holder.title.setText(news.getHeading());
}
#Override
public int getItemCount() {
return newsArticleList.size();
}
}
News.Java;
public class News {
private String heading;
//private String descrpiton;
private String img;
public String getHeading() {
return heading;
}
public void setHeading(String heading) {
this.heading = heading;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
Your problem is here
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
article_heading is an ArrayList, the method add returns a boolean to whether the list has changed due to your call or not.
You are not adding the title, you are adding the return of the ArrayList method, what you need is to change that line to that
String title = jsonArray.getJSONObject(i).optString("title");
article_heading.add(title);
news.setHeading(title);
change your onPostExecute as below
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
String headingFromJson = jsonArray.getJSONObject(i).getString("title");
article_heading.add(headingFromJson);
news.setHeading(headingFromJson);
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
mViewAdapter = new MyAdapter(news_list);
mRecyclerView.setAdapter(mViewAdapter);
mViewAdapter.notifyDataSetChanged();
super.onPostExecute(s);
}
You are setting the heading of the news in a wrong way.
You should be doing the following in your Aynctask:
news.setHeading(jsonArray.getJsonObject(i).getString("title"));
You are instead putting the title inside the arraylist using add method. And putting the result of the add method as the heading. Add method of arraylist returns a boolean value indicating if the addition to list was successful or not. Thus you keep getting true instead of the actual text
Try this:
In yout ParseNewsJSON class onpostexecute()
Change to :
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(jsonArray.getJSONObject(i).optString("title"));
news_list.add(news);
}
Instead of:
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
I want to show json data in listview.The json array is shown in
console.but i am not able to set the adapter value in listview.It
always return null value.
final ListView category_listview = (ListView)findViewById(R.id.category_dashboard_list);
category_detail = new Category_Dashboard_Adapter(getApplicationContext(), R.layout.category_row_list, cate_list);
category_listview.setAdapter(category_detail);
try {
jsono = new JSONObject(jsonvalue);
jarray = jsono.getJSONArray("jsonvalue");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
try
{
// object = jarray.getJSONObject(i);
Category_Detail_Model category_obj = new Category_Detail_Model();
category_obj.setCategory_Title(object.getString("bookmark_title"));
category_obj.setCategory_Description(object.getString("bookmark_title"));
category_obj.setCategory_Url(object.getString("bookmark_website"));
category_obj.setImage(object.getString("bookmark_preview_image"));
cate_list.add(category_obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
Here category_listview.setAdapter(category_detail); giving null value.
Here model file is
public class Category_Detail_Model{
private String category_title;
private String category_description;
private String category_url;
private String category_image;
public Category_Detail_Model() {
// TODO Auto-generated constructor stub
}
public Category_Detail_Model(String category_title, String category_description, String category_url, String category_image) {
super();
this.category_title = category_title;
this.category_description = category_description;
this.category_url =category_url;
this.category_image = category_image;
}
public String getCategory_Title() {
return category_title;
}
public void setCategory_Title(String category_title) {
this.category_title = category_title;
}
public String getCategory_Description() {
return category_description;
}
public void setCategory_Description(String category_description) {
this.category_description = category_description;
}
public String getCategory_Url() {
return category_url;
}
public void setCategory_Url(String category_url) {
this.category_url = category_url;
}
public String getCategory_Image() {
return category_image;
}
public void setImage(String category_image) {
this.category_image = category_image;
}
}
And here is Adapter class code
public class Category_Dashboard_Adapter extends ArrayAdapter<Category_Detail_Model> {
ArrayList<Category_Detail_Model> category_detail_list;
LayoutInflater vi;
int Resource;
ViewHolder holder;
Typeface font1 = Typeface.createFromAsset(getContext().getAssets(), "fonts/cabin.regular.ttf");
public Category_Dashboard_Adapter(Context context1, int resource1, ArrayList<Category_Detail_Model> objects1) {
super(context1, resource1, objects1);
vi = (LayoutInflater) context1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource1;
category_detail_list = objects1;
}
public View getView(int position1, View convertView1, ViewGroup parent1)
{
// convert view = design
View v = convertView1;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.category_imageview = (ImageView) v.findViewById(R.id.category_details_ivImage);
holder.category_title_holder = (TextView) v.findViewById(R.id.category_detail_title_view);
holder.category_desc_holder = (TextView) v.findViewById(R.id.category_detail_desc_view);
holder.category_url_holder = (TextView) v.findViewById(R.id.category_detail_url_view);
holder.category_title_holder.setTypeface(font1); holder.category_title_holder.setTextSize(16.0f);
holder.category_desc_holder.setTypeface(font1); holder.category_desc_holder.setTextSize(14.0f);
holder.category_url_holder.setTypeface(font1); holder.category_url_holder.setTextSize(10.0f);
// holder.txtCategory.setTypeface(font1); holder.txtCategory.setTextSize(10.0f);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new CategoryDownloadImageTask(holder.category_imageview).execute(category_detail_list.get(position1).getCategory_Image());
holder.category_title_holder.setText(category_detail_list.get(position1).getCategory_Title());
holder.category_desc_holder.setText(category_detail_list.get(position1).getCategory_Description());
holder.category_url_holder.setText(category_detail_list.get(position1).getCategory_Url());
return v;
}
static class ViewHolder {
public ImageView category_imageview;
public TextView category_title_holder;
public TextView category_desc_holder;
public TextView category_url_holder;
}
}
Bacause you set value for the adapter before load json so it give null values:
Try this:
final ListView category_listview = (ListView)findViewById(R.id.category_dashboard_list);
try {
jsono = new JSONObject(jsonvalue);
jarray = jsono.getJSONArray("jsonvalue");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
try
{
// object = jarray.getJSONObject(i);
Category_Detail_Model category_obj = new Category_Detail_Model();
category_obj.setCategory_Title(object.getString("bookmark_title"));
category_obj.setCategory_Description(object.getString("bookmark_title"));
category_obj.setCategory_Url(object.getString("bookmark_website"));
category_obj.setImage(object.getString("bookmark_preview_image"));
cate_list.add(category_obj);
category_detail = new Category_Dashboard_Adapter(getApplicationContext(), R.layout.category_row_list, cate_list);
category_listview.setAdapter(category_detail);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
Or maybe you forget to init your ArrayList before set json data to it. Remember to do this:
ArrayList<String> cate_list = new ArrayList<>();
before you set data for it.
You are parsing your json and adding data to your cate_list after setting the adapter. Add the code for setting data to ListView after you parse your json:
try {
jsono = new JSONObject(jsonvalue);
jarray = jsono.getJSONArray("jsonvalue");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
try
{
// object = jarray.getJSONObject(i);
Category_Detail_Model category_obj = new Category_Detail_Model();
category_obj.setCategory_Title(object.getString("bookmark_title"));
category_obj.setCategory_Description(object.getString("bookmark_title"));
category_obj.setCategory_Url(object.getString("bookmark_website"));
category_obj.setImage(object.getString("bookmark_preview_image"));
cate_list.add(category_obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
final ListView category_listview = (ListView)findViewById(R.id.category_dashboard_list);
category_detail = new Category_Dashboard_Adapter(getApplicationContext(), R.layout.category_row_list, cate_list);
category_listview.setAdapter(category_detail);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
For some reason in my application, when I try to call openFileOutput(), it throws a NullPointerException and I am not sure what is causing it. I have made sure that all the parameters of the method are not null, but for some reason my app still throws a NullPointerException. Any suggestions?
My MainActivity class
public class MainActivity extends AppCompatActivity {
private static final String TAG_NEWS_FRAGMENT = "news_fragment";
private static final String TAG_SPORTS_FRAGMENT = "sports_fragment";
Context context = MainActivity.this;
private final String[] CATEGORY_NAMES = {"news", "sports"};
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ProgressBar mProgressBar;
private CoordinatorLayout coordinatorLayout;
private PUNewsFragment mPUNewsFragement;
private PUSportsFragment mPUSportsFragement;
private List<NewspaperMetaObject> newsItems;
private List<List<NewspaperMetaObject>> categories;
private boolean doesFileExist;
private boolean isWebsiteOnline;
private FragmentManager fm;
private ProgressBar pb;
private boolean doRefresh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doRefresh = false;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
Toast.makeText(this, "Loading...", Toast.LENGTH_SHORT).show();
pb = (ProgressBar) findViewById(R.id.progressBar);
try {
isWebsiteOnline = new checkWebsiteStatus().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
doesFileExist = new File(context.getFilesDir() + "/news").exists();
new RetrieveNewspaperMeta().execute(CATEGORY_NAMES);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PUNewsFragment(), "News");
adapter.addFragment(new PUSportsFragment(), "Sports");
viewPager.setAdapter(adapter);
}
public void refresh(String[] str) {
doRefresh = true;
new RetrieveNewspaperMeta().execute(str);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private class RetrieveNewspaperMeta extends AsyncTask<String, Integer, Wrapper> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Wrapper doInBackground(String... params) {
Document doc = null;
categories = new ArrayList<>();
if (!doesFileExist && doRefresh) {
for (int i = 0; i < params.length; i++) {
newsItems = new ArrayList<>();
try {
Log.i("DEBUG", params[i]);
URL url = new URL("http://www.dailyprincetonian.com/category/" + params[i] + "/");
doc = Jsoup.connect(url.toString()).get();
Elements content = doc.select("article.tease-post");
System.out.println();
System.out.println(content);
int count = 0;
NewspaperMetaObject parser;
while (!content.eq(count).isEmpty()) {
parser = new NewspaperMetaObject(content.eq(count));
newsItems.add(parser);
count++;
}
categories.add(newsItems);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (NewspaperMetaObject o : newsItems) {
try {
Elements text = Jsoup.connect(o.getDoc().select("h3.h2 a").attr("href")).get().select("section.article-content").select("div.article-bd").select("p");
o.setArticleText(text.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new Wrapper(categories, params);
} else {
for (int i = 0; i < params.length; i++) {
newsItems = new ArrayList<>();
try {
FileInputStream fis = openFileInput(params[i]);
ObjectInputStream is = new ObjectInputStream(fis);
newsItems = (List<NewspaperMetaObject>) is.readObject();
is.close();
fis.close();
categories.add(newsItems);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return new Wrapper(categories, params);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(final Wrapper wrapper) {
super.onPostExecute(wrapper);
android.os.Handler mHandler = new android.os.Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (!doRefresh) {
PUNewsFragment.newsItems = categories.get(0);
PUSportsFragment.newsItems = categories.get(1);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
fm = getSupportFragmentManager();
mPUNewsFragement = (PUNewsFragment) fm.findFragmentByTag(TAG_NEWS_FRAGMENT);
mPUSportsFragement = (PUSportsFragment) fm.findFragmentByTag(TAG_SPORTS_FRAGMENT);
if (mPUNewsFragement == null && mPUSportsFragement == null) {
mPUNewsFragement = new PUNewsFragment();
mPUSportsFragement = new PUSportsFragment();
fm.beginTransaction().add(mPUNewsFragement, TAG_NEWS_FRAGMENT).commit();
fm.beginTransaction().add(mPUSportsFragement, TAG_SPORTS_FRAGMENT).commit();
}
} else {
for (int i = 0; i < wrapper.params.length; i++) {
switch (wrapper.params[i]) {
case "news":
PUNewsFragment.newsItems = categories.get(0);
PUNewsFragment.adapter.notifyDataSetChanged();
break;
case "sports":
PUSportsFragment.newsItems = categories.get(1);
PUSportsFragment.adapter.notifyDataSetChanged();
break;
}
}
}
if (pb != null) {
pb.setVisibility(View.GONE);
}
Log.i("DEBUG", "DONE!");
if (doRefresh) {
context = MainActivity.this;
for (int i = 0; i < wrapper.params.length; i++) {
try {
FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(newsItems);
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
doRefresh = false;
}
}, 1000);
}
}
private class checkWebsiteStatus extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.dailyprincetonian.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
urlConnection.disconnect();
return true;
} catch (IOException e) {
}
return false;
}
}
private class Wrapper {
List<List<NewspaperMetaObject>> categories;
String[] params;
public Wrapper(List<List<NewspaperMetaObject>> categories, String[] params){
this.categories = categories;
this.params = params;
}
}
}
Snippet of where the Exception is being thrown
if (doRefresh) {
context = MainActivity.this;
for (int i = 0; i < wrapper.params.length; i++) {
try {
FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(newsItems);
//os.flush();
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It looks like the wrapper variable is declared (therefore you can do a
for (int i = 0; i < wrapper.params.length; i++)
without any problem) but all items in the array may be null referenced, wich is the cause of the NPE.
I am using viewpager with gridview and downloading json data into it and implemented gridview scroll listener but whenever i start activity again the current viewpager fragment in which sroll listener implemented shows blank.
Here is my code, please see and tell me my mistake.
//My Activity Fragment
private static String url = "http://--------/------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
//My Json Execution
new LoadData().execute(url);
//Scroll listener when gridview reaches at end
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 10) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//Loading new datas in gridview
new LoadData()
.execute("http://-----/-----");
mLoading = true;
}
}
});
return rootView;
}
private class LoadData extends AsyncTask<String, Void, Void> {
#Override
protected void onPostExecute(Void result) {
//checking whether adapter is null or not
if (adap == null) {
adap = new Grid_View_Adatper(getActivity()
.getApplicationContext(), arrayList);
gridView.setAdapter(adap);
}
adap.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
}
Thanks in advance...