How to get value in listview in android - java

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);

Related

RecyclerView Returning 'true' instead of JSON

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);
}

filtering listview results after selecting spinner value

I have 3 spinners in my project named standard, division and age. They contain values from json data. When I select a value from each individual spinner it shows all data of students in a listview respectivly (fetched from json).
I'm working with the following JSON data:
[
{
"name":"aarti",
"surname":"singh",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"seema",
"surname":"desai",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"tina",
"surname":"joshi",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"megha",
"surname":"kale",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"swati",
"surname":"marathe",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"rekha",
"surname":"surve",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"madhu",
"surname":"dalvi",
"age":"18",
"div":"B",
"standard":"6"
}
I am trying to do it like this way:
When I select standard 7 from the spinner it should display students information studying in 7th standard ("aarti", "seema", "megha", "rekha") and their other information too.
Then I am selecting value from division spinner say "A", it should take above result granted and accordingly display students from standard 7 and division "A". It should shows the result as ("aarti", "megha", "rekha") and their other informations too.
Finally when I am selecting value from age spinner say "17", it should take above result granted and accordingly display students from standard 7 and division "A" and age "17". Accordingly it shows "megha" and "rekha".
Can anyone please assist me
This is my MainActivity.java class:
public class MainActivity extends AppCompatActivity {
ArrayList<String> AllStandards = new ArrayList<>();
ArrayList<String> AllDivision = new ArrayList<>();
ArrayList<String> AllAge = new ArrayList<>();
JSONArray jsonArray;
Spinner spinner_std, spinner_div, spinner_age;
private ArrayList<StudInfo> studentVOList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<String> item_Std = getStandard("data.json");
final List<String> items_div = getDivision("data.json");
final List<String> items_age = getAge("data.json");
/*spinner for standard*/
spinner_std = (Spinner) findViewById(R.id.spinnerStandard);
ArrayAdapter<String> adapter_std = new ArrayAdapter<String>(this, R.layout.spinner_standard_layout, R.id.textViewStandard, item_Std);
adapter_std.getFilter().filter(txt);
spinner_std.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String standard = AllStandards.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String stand = jsonObject.getString("standard");
if (stand.equalsIgnoreCase(standard)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setStandard(stand);
studentVOList.add(studentVO);
}
}
// Log.d("TAG", "List With All Students in selected standard: " + studentVOList.size());
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_std.setAdapter(adapter_std);
/*spinner for division*/
spinner_div = (Spinner) findViewById(R.id.spinnerDiv);
ArrayAdapter<String> adapter_div = new ArrayAdapter<String>(this, R.layout.spinner_division_layout, R.id.textViewDivision, items_div);
adapter_div.getFilter().filter(txt);
spinner_div.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String division = AllDivision.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String div = jsonObject.getString("div");
// Collections.sort(AllDivision);
if (div.equalsIgnoreCase(division)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setDiv(div);
studentVOList.add(studentVO);
}
}
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_div.setAdapter(adapter_div);
/*spinner for age*/
spinner_age = (Spinner) findViewById(R.id.spinerAge);
ArrayAdapter<String> adapter_age = new ArrayAdapter<String>(this, R.layout.spinner_age_layout, R.id.textViewAge, items_age);
adapter_age.getFilter().filter(txt);
spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String age = AllAge.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String age_list = jsonObject.getString("age");
Collections.sort(AllAge);
if (age_list.equalsIgnoreCase(age)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setAge(age_list);
studentVOList.add(studentVO);
}
}
Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
Bundle b = new Bundle();
b.putSerializable("list", studentVOList);
intent.putExtra("bundle", b);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_age.setAdapter(adapter_age);
}//onCreate Method
private List<String> getStandard(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
// AllStandards.clear();
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("standard");
if (!AllStandards.contains(stand)) {
AllStandards.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllStandards;
}
private List<String> getDivision(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("div");
if (!AllDivision.contains(stand)) {
AllDivision.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllDivision;
}
private List<String> getAge(String fileName) {
jsonArray = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("age");
if (!AllAge.contains(stand)) {
AllAge.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllAge;
}
this is my ListAdapter.java class
public class ListAdapter extends ArrayAdapter<StudInfo> {
int vg;
ArrayList<StudInfo> list;
Context context;
public ListAdapter(Context context, int vg, int id, ArrayList<StudInfo> list) {
super(context, vg, id, list);
this.context = context;
this.vg = vg;
this.list = list;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(vg, parent, false);
TextView textViewName = (TextView) itemView.findViewById(R.id.txtName);
TextView textViewSurname = (TextView)itemView.findViewById(R.id.txtSurname);
TextView textViewAge = (TextView) itemView.findViewById(R.id.txtAge);
TextView textViewDiv = (TextView) itemView.findViewById(R.id.txtDiv);
TextView textViewStd = (TextView) itemView.findViewById(R.id.txtStandard);
textViewName.setText(list.get(position).getName());
textViewSurname.setText(list.get(position).getSurname());
textViewAge.setText(list.get(position).getAge());
textViewDiv.setText(list.get(position).getDiv());
textViewStd.setText(list.get(position).getStandard());
return itemView;
}
}
this is my StudentsInfo.java class
public class StudentsInfo extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.studentsinfo_layout);
Bundle b = getIntent().getBundleExtra("bundle");
ArrayList<StudInfo> studentVOList = (ArrayList<StudInfo>) b.getSerializable("list");
ListView listView = (ListView) findViewById(R.id.listViewShow);
ListAdapter listAdapter = new ListAdapter(this, R.layout.list_layout, R.id.txtName, studentVOList);
listView.setAdapter(listAdapter);
}
}
this is my StudInfo.java class,
import java.io.Serializable;
public class StudInfo implements Serializable
{
private String name;
private String surname;
private String age;
private String div;
private String standard;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getDiv() {
return div;
}
public void setDiv(String div) {
this.div = div;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
}
i tried googling to find out solution but the questions i found all are based on searching listview items using edittext.i didn't found ant similar post matching with my question which solve my problem.can anyone please help me to solve this??
1. Override getFilter method in your adapter class
2. Use adapter.getFilter().filter(txt) in your spinner selection
package com.hughesnet.adapters;
import com.hughesnet.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<StudInfo> {
int vg;
ArrayList<StudInfo> list;
Context context;
ItemFilter mFilter;
ArrayList<StudInfo> filteredData;
public ListAdapter (Context context, int vg, int id, ArrayList<StudInfo> list) {
super (context, vg, id, list);
this.context = context;
this.vg = vg;
this.list = list;
}
public View getView (int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate (vg, parent, false);
TextView textViewName = (TextView) itemView.findViewById (R.id.txtName);
TextView textViewSurname = (TextView) itemView.findViewById (R.id.txtSurname);
TextView textViewAge = (TextView) itemView.findViewById (R.id.txtAge);
TextView textViewDiv = (TextView) itemView.findViewById (R.id.txtDiv);
TextView textViewStd = (TextView) itemView.findViewById (R.id.txtStandard);
textViewName.setText (list.get (position).getName ());
textViewSurname.setText (list.get (position).getSurname ());
textViewAge.setText (list.get (position).getAge ());
textViewDiv.setText (list.get (position).getDiv ());
textViewStd.setText (list.get (position).getStandard ());
return itemView;
}
ItemFilter mFilter = new ItemFilter ();
public Filter getFilter () {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering (CharSequence constraint) {
String filterString = constraint.toString ().toLowerCase ();
FilterResults results = new FilterResults ();
int count = list.size ();
final ArrayList<StudInfo> nlist = new ArrayList<StudInfo> (count);
String filterableString;
for (int i = 0; i < count; i++) {
StudInfo info = list.get (i);
// Check for standard, division and age here
if (info.getAge().contains(filterString) || info.getStandard().contains(filterString ) || info.getDiv().contains(filterString )) {
nlist.add (filterableString);
}
}
results.values = nlist;
results.count = nlist.size ();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<StudInfo>) results.values;
notifyDataSetChanged();
}
}
}

How to parse list in android?

List have below declaration
private ArrayList<HashMap<String,String>> result=new ArrayList<HashMap<String, String>>();
Sample data:-
[{Minutes=25, Catagory=Morning, Hour=11, medName=hdodu, ImgPath=/storage/emulated/0/H/hdodu.jpg},
{Minutes=25, Catagory=Night, Hour=3, medName=hdodu, ImgPath=/storage/emulated/0/H/hdodu.jpg},
{Minutes=33, Catagory=Afternoon, Hour=16, medName=jsindj, ImgPath=/storage/emulated/0/H/jsindj.jpg}]
How do I print data of list using model class
Model.java
public class ListMedicine {
private String Medicine_name;
private String Reminder_hour;
private String Reminder_min;
private String Reminder_catagory;
private String Medicine_image_path;
public void setMedicine_name(String medicine_name)
{
this.Medicine_name=medicine_name;
}
public String getMedicine_name()
{
return Medicine_name;
}
public void setReminder_hour(String reminder_hour)
{
this.Reminder_hour=reminder_hour;
}
public String getReminder_hour()
{
return Reminder_hour;
}
public void setReminder_min(String reminder_min)
{
this.Reminder_min=reminder_min;
}
public String getReminder_min()
{
return Reminder_min;
}
public void setReminder_catagory(String reminder_catagory)
{
this.Reminder_catagory=reminder_catagory;
}
public String getReminder_catagory()
{
return Reminder_catagory;
}
public void setMedicine_image_path(String medicine_image_path)
{
this.Medicine_image_path=medicine_image_path;
}
public String getMedicine_image_path()
{
return Medicine_image_path;
}
}
MedicineAdaptor.java
Below is the code for adaptor class in which I am using recyclerView to list down the data.
public class MedicineAdaptor extends RecyclerView.Adapter<MedicineAdaptor.ViewHolder> {
List<ListMedicine> items;
DbHelper dbHelper;
Context context;
public MedicineAdaptor(Context context, List<ListMedicine> items)
{
super();
dbHelper=new DbHelper(context);
Log.i("In the MedicineAdaptor","Constructor");
this.context=context;
this.items=items;
}
#Override
public MedicineAdaptor.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i("Entering","onCreateViewHolder");
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.medicine,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MedicineAdaptor.ViewHolder holder, int position) {
Log.i("Entering","onBindViewHolder");
ListMedicine listMedicine=items.get(position);
Log.i("Medicine Name", listMedicine.getMedicine_name());
Log.i("Medicine Hour", listMedicine.getReminder_hour());
Log.i("Medicine Min",listMedicine.getReminder_min());
Log.i("Medicine Catagory", listMedicine.getReminder_catagory());
holder.MedicineName.setText(listMedicine.getMedicine_name());
holder.ReminderHour.setText(listMedicine.getReminder_hour());
holder.ReminderMin.setText(listMedicine.getReminder_min());
holder.ReminderCatagory.setText(listMedicine.getReminder_catagory());
}
#Override
public int getItemCount() {
Log.i("Size is", Integer.toString(items.size()));
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView MedicineName, ReminderHour,ReminderMin, ReminderCatagory;
public ImageView MedicineThumbnail;
public ViewHolder(View itemView) {
super(itemView);
MedicineName=(TextView) itemView.findViewById(R.id.medicine_name);
ReminderHour=(TextView) itemView.findViewById(R.id.reminder_hour);
ReminderMin=(TextView) itemView.findViewById(R.id.reminder_hour);
ReminderCatagory=(TextView) itemView.findViewById(R.id.medicine_catagory);
MedicineThumbnail=(ImageView) itemView.findViewById(R.id.medicine_icon);
}
}
}
Database Fetch Code:
public ArrayList<ListMedicine> fetchReminder(String date)
{
ArrayList<ListMedicine> array_list=new ArrayList<ListMedicine>();
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.rawQuery("select * from reminders",null);
c.moveToFirst();
try {
while(c.isAfterLast() == false){
Log.i("Inside the fetch query","yes");
ListMedicine listMedicine=new ListMedicine();
listMedicine.setMedicine_name(c.getString(c.getColumnIndex("medName")));
array_list.add(listMedicine);
c.moveToNext();
}
}catch (Exception e)
{
e.printStackTrace();
}
return array_list;
}
Code of the calling Activity
private void showData() {
ArrayList<ListMedicine> list=new ArrayList<ListMedicine>();
Log.i("Show Data function","Yes");
try {
JSONArray arr = new JSONArray(result);
Log.i("Length is ",Integer.toString(arr.length()));
for(int i=0;i<arr.length(); i++){
ListMedicine bean = new ListMedicine();
bean.setMedicine_name(bean.getMedicine_name());
// at last add this into your list
Log.i("Bean ans", bean.toString());
list.add(bean);
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter=new MedicineAdaptor(this,list);
reminderList.setAdapter(adapter);
}
private void getData(String fetchDate) {
//ArrayList<String> result=new ArrayList<String>();
result=db.fetchReminder(fetchDate);
Log.i("Result",result.toString());
}
For me I am using Gson:
YourModel obj = gson.fromJson(yourStringJson, YourModel.class);
You can read more about Gson here:
https://sites.google.com/site/gson/gson-user-guide
Probably, you could use Gson, Jackson, Moshi etc...
They could be parsing a Java model.
GitHub Links - Gson , Jackson , Moshi
Change your
ArrayList<HashMap<String,String>> result=new ArrayList<HashMap<String, String>>();
into
ArrayList<ListMedicine> result=new ArrayList<ListMedicine>();
Do it like this
try {
JSONArray arr = new JSONArray(result);
for(int i=0;i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
ListMedicine bean = new ListMedicine();
bean.setMedicine_name(obj.getString("medName"));
.
.
.
// at last add this into your list
result.add(bean);
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this out..
try {
for(int i=0;i<list.size(); i++){
ListMedicine bean = new ListMedicine();
bean.setMedicine_name(list.get(i).getString("medName"));
.
.
.
// at last add this into your list
result.add(bean);
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How do I fetch null from arraylist in android

I have a JSON like this
{
"questions": [{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
},
{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
}
]
}
I have added values of lets suppose "Answer_Video_Link" into Arraylist for e.g arraylistAnswerLink so the output will be like[null,null,....so on]
As setting this arraylist in a BaseAdapter,the functionality is want to achieve is:
if(arraylistAnswerLink.get(position).contains(null)){
button.setVisibilty(View.Visible)}
else{
button.setVisibilty(View.Gone)
}
This my json parsing code
jsonInnerArray = jsonInnerObject.getJSONArray("questions");
for (int j = 0; j <= jsonInnerArray.length(); j++) {
jsonArrayObject = jsonInnerArray.getJSONObject(j);
Question_Video_Title = jsonArrayObject.getString("Question_Video_Title");
question_video_playingTime = jsonArrayObject.getString("question_video_playingTime");
String Designation1 = jsonArrayObject.getString("Designation");
full_name = jsonArrayObject.getString("User_name"); Question_Video_Link = jsonArrayObject.getString("Question_Video_Link");
Answer_Video_Link = jsonArrayObject.getString("Answer_Video_Link");
QuestionID = jsonArrayObject.getString("QuestionID");
video_thumbnail=jsonArrayObject.getString("video_thumbnail"); }
am having error of array index out of bound while fetching null at a particular position of the list.
Please check my code
public class UnRepliedFragment_ extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
View rootview;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
// ArrayList<Integer> arrayListImage;
ArrayList<Integer> arrayListVideos;
File mediaFile, vPath;
String song_dur_str, st, vst, vst1, orginalName;
String timestamp, advisorID, token;
int VIDEO_CAPTURE = 1000;
ProgressDialog dlg;
SharedPreferences preferences;
ArrayList<String> arrayListName, videoName, singleVideoName, questionLink, arrquestion_video_playingTime, answerLinkEmpty;
String FirstName, durationofVideo, User_name, Question_Video_Title, Question_Video_Link, shorted, cmpsort, question_video_playingTime, path, QuestionID;
int advisor, pos;
private List<Modals> feedsList;
Uri mediaPath;
PutObjectRequest por;
String url = "https://s3-us-west-1.amazonaws.com/talentedge1";
private static AmazonS3Client sS3Client;
Uri fileUri;
static Object Answer_Video_Link;
ArrayList<Object> answerLink;
Object item;
JSONObject jsonObject,innerObject;
JSONArray innerArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_unreplied, container, false);
dlg = new ProgressDialog(getActivity());
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
token = preferences.getString(AppConstant.TOKEN, "");
advisorID = preferences.getString(AppConstant.USERID, "");
arrayListVideos = new ArrayList<>();
feedsList = new ArrayList<>();
arrayListName = new ArrayList<>();
videoName = new ArrayList<>();
questionLink = new ArrayList<>();
arrquestion_video_playingTime = new ArrayList<>();
answerLink = new ArrayList<>();
singleVideoName = new ArrayList<>();
/*
API hit
*/
new Proadvice().execute();
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.recycler_view_unreplied);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
return rootview;
}
/*
Adapter class
*/
class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
ArrayList<String> videoName;
ArrayList<String> questionLink;
ArrayList<String> arrquestion_video_playingTime;
ArrayList<Object> answerLink;
public MyRecyclerViewAdapter(ArrayList<String> videoName, ArrayList<String> questionLink, ArrayList<Object> answerLink, ArrayList<String> arrquestion_video_playingTime) {
this.videoName = videoName;
this.questionLink = questionLink;
this.answerLink = answerLink;
this.arrquestion_video_playingTime = arrquestion_video_playingTime;
}
#Override
public MyRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.unreplied_list_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(MyRecyclerViewAdapter.ViewHolder holder, int position) {
holder.txt_it_author.setText(arrayListName.get(position));
holder.textView.setText(arrquestion_video_playingTime.get(position));
holder.txt_it_Title.setText(videoName.get(position));
for (Object value : answerLink) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
#Override
public int getItemCount() {
return videoName.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView, txt_it_author, txt_it_Title, share;
RippleView relativeLayout;
LinearLayout imageButtonAnswer;
FrameLayout frameLayout;
public ViewHolder(View itemView) {
super(itemView);
relativeLayout = (RippleView) itemView.findViewById(R.id.relative_video_it);
relativeLayout.setOnClickListener(this);
imageView = (ImageView) itemView.findViewById(R.id.img_it_Video);
textView = (TextView) itemView.findViewById(R.id.txt_it_duration);
txt_it_author = (TextView) itemView.findViewById(R.id.txt_it_author);
txt_it_Title = (TextView) itemView.findViewById(R.id.txt_it_Title);
imageButtonAnswer = (LinearLayout) itemView.findViewById(R.id.img_answers);
frameLayout = (FrameLayout) itemView.findViewById(R.id.relative_play_img);
imageButtonAnswer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
int id = v.getId();
switch (id) {
case R.id.relative_play_img:
Intent i = new Intent(getActivity(), Video_ViewAct.class);
i.putExtra("position", "" + position);
i.putExtra("Question_Video_Link", questionLink.get(position));
// i.putExtra("Answer_Video_Link", answerLink.get(position));
startActivity(i);
break;
}
}
}
}
class Proadvice extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return doInLoginProadvice();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dlg.setMessage("Loading.....");
dlg.setCancelable(false);
dlg.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dlg.dismiss();
if (result.contains("true")) {
updateUIProadvice(result);
}
}
}
private void updateUIProadvice(String result) {
try {
jsonObject = new JSONObject(result);
String message = jsonObject.getString("message");
innerObject = jsonObject.getJSONObject("Object");
innerArray = innerObject.getJSONArray("details");
// Log.e("arr", " " + arr);
for (int i = 0; i <= innerArray.length(); i++) {
JSONObject obj = innerArray.getJSONObject(i);
String advisorID = obj.getString("AdvisorID");
FirstName = obj.getString("FirstName");
String LastName = obj.getString("LastName");
String Email = obj.getString("Email");
String Password = obj.getString("Password");
String Designation = obj.getString("Designation");
String Company = obj.getString("Company");
String Location = obj.getString("Location");
String Description = obj.getString("Description");
String Profile_Pic_Small = obj.getString("Profile_Pic_Small");
String Profile_Pic_Original = obj.getString("Profile_Pic_Original");
String No_Questions = obj.getString("No_Questions");
String No_Answers = obj.getString("No_Answers");
String No_Up_Votes = obj.getString("No_Up_Votes");
String No_Followers = obj.getString("No_Followers");
String IsActive = obj.getString("IsActive");
String Created = obj.getString("Created");
String Modified = obj.getString("Modified");
JSONArray arr1 = innerObject.getJSONArray("questions");
for (int j = 0; j <= arr1.length(); j++) {
JSONObject obj1 = arr1.getJSONObject(j);
Question_Video_Title = obj1.getString("Question_Video_Title");
question_video_playingTime = obj1.getString("question_video_playingTime");
String Designation1 = obj1.getString("Designation");
User_name = obj1.getString("User_name");
Question_Video_Link = obj1.getString("Question_Video_Link");
shorted = Question_Video_Title.replace("=", " ");
cmpsort = shorted.replace("-", " ");
Answer_Video_Link = obj1.get("Answer_Video_Link");
QuestionID = obj1.getString("QuestionID");
videoName.add((cmpsort));
questionLink.add(Question_Video_Link);
answerLink.add(Answer_Video_Link);
arrayListName.add(User_name);
arrquestion_video_playingTime.add(question_video_playingTime);
mAdapter = new MyRecyclerViewAdapter(videoName, questionLink, answerLink, arrquestion_video_playingTime);
mRecyclerView.setAdapter(mAdapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String doInLoginProadvice() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConstant.getAdvivisorDetail);
httppost.addHeader("APIKEY", "123ABC890567");
httppost.addHeader("Token", token);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("AdvisorID", advisorID));
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
}
Here is the Simple Way to Parse JSON array and easily get Null as well as a value pair . Important Thing Do not use variable name as a capital letter it must be start with lower case.
please find programme and you can modify it according to Your Requirement
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class UnRepliedFragment_ {
//Define this as a global varraible
static Object Advisor_User_ID;
static Object Creator_User_ID;
static Object Question_Video_Title;
static Object playing_time;
static Object Created;
static Object Modified;
static Object question_video_playingTime;
static Object Answer_Video_Title;
static Object Answer_Video_Link;
static Object answer_video_playingtime;
static Object StatusName;
static Object QuestionID;
static ArrayList al;
public void onBindViewHolder() {
for (Object value : al) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
private void updateUIProadvice(String result) {
//Since i have an limited JSON so Accroding to that i did parsing . Dont try with getString just try with Get();//method
try {
JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(result);
org.json.simple.JSONArray lang = (org.json.simple.JSONArray) jsonObject.get("questions");
for (int i = 0; i < lang.size(); i++) {
}
Iterator i = lang.iterator();
while (i.hasNext()) {
org.json.simple.JSONObject innerObj = (org.json.simple.JSONObject) i.next();
Creator_User_ID = innerObj.get("Creator_User_ID").toString();
Advisor_User_ID = innerObj.get("Advisor_User_ID");
Question_Video_Title = innerObj.get("Question_Video_Title");
playing_time = innerObj.get("playing_time");
Created = innerObj.get("Created");
Modified = innerObj.get("Modified");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
Answer_Video_Link = innerObj.get("Answer_Video_Link");
answer_video_playingtime = innerObj.get("answer_video_playingtime");
StatusName = innerObj.get("StatusName");
QuestionID = innerObj.get("QuestionID");
// Storing data into arrayList
al = new ArrayList();
al.add(Creator_User_ID);
al.add(Advisor_User_ID);
al.add(Question_Video_Title);
al.add(playing_time);
al.add(Created);
al.add(Modified);
al.add(question_video_playingTime);
al.add(Answer_Video_Link);
al.add(Answer_Video_Title);
al.add(answer_video_playingtime);
al.add(QuestionID);
al.add(StatusName);
// First Way to get element one by one
for (Object value : al) {
if (value != null) {
System.out.println("Not Null:" + value);
} else {
System.out.println("Null:" + value);
}
}
//or Second Way
Object valuenext=al.get(0); // Get First Index Value
System.out.println(valuenext);
}
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}

Android: Downloaded Images not showing in ListView

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.

Categories

Resources