RecyclerView Returning 'true' instead of JSON - java

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

Related

Cards will not populate with movie names from TMDB API

I am creating an app for a project where you can swipe through movie names and images, for now I am just trying to get the names working but my cards will not populate with the movie names. I had some trouble with the array adapter but I think it's working now and in the correct place. I am using a library from github for the cards and it's worked for other programs just can't get it work with this. Maybe it's because of the model class? just lost when there is no real errors. Item.xml is the design of the card with it's text and background and activity_main.xml is where I reference the library. hellotext is the textview in item.xml. Any help is appreicated!
public class MainActivity extends AppCompatActivity {
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
movieList.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
Api (same class)
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
// model.setId(jsonObject1.getString("vote_average"));
model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList = new ArrayList<>();
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Update***
I fixed the null problem BUT my cards now populate with my project name so I just see one card with com.project300.populateswipecards... any help?
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename = "";
Context context;
SwipeFlingAdapterView flingContainer;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
// Log.d("LIST", "removed object!");
// movieList.remove(0);
// arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
movieList = new ArrayList<>();
// model.setId(jsonObject1.getString("vote_average"));
// model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
At the end of your onPostExecute() method, I see this:
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
I think you're assuming that this will update the list of cards, since earlier in onCreate() you have written this:
flingContainer.setAdapter(arrayAdapter);
However, that is not how the new keyword and Java object references work. These two adapters are completely separate, and flingContainer doesn't "see" the adapter you create in your task.
The easiest way to solve this is likely to re-set the adapter after you create it.
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
Now the problem seems to be this for loop:
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList = new ArrayList<>();
// ...
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
You need to move the ArrayList creation and adapter logic outside of the loop.
movieList = new ArrayList<>();
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList.add(model);
}
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);

How to Populate 2 strings in Listview from webservice?

Am an newbie to android ...kindly help me guys...I have 2 strings in my sample webservice(Not in an array) and I want to populate it in the listview .I wrote code to populate with a single string.But I don't know how to populate with 2nd strings below to 1st string in listview.Any suggestion will be appreciated.
Here is my complete code
HTTPURLCONNECT
class HttpULRConnect {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2","test");
String line;
while ((line= reader.readLine())!=null) {
sb.append(line+"\n");
}
Log.d("test44", sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally{
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}}}
Here is my FETCH.java
public class Fetch extends Activity {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fetch);
new BackTask().execute(url);
}
public class BackTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content =HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ar = new JSONArray(s);
for (int i = 0; i < ar.length(); i++) {
JSONObject jsonobject = ar.getJSONObject(i);
Flowers flowers = new Flowers();
flowers.setName(jsonobject.getString("NAME"));
flowersList.add(flowers);
}
}
catch (JSONException e){
e.printStackTrace();
}
FlowerAdapter adapter = new FlowerAdapter(Fetch.this, R.layout.flower_lis_item, flowersList);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
}
}
static class Flowers {
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
private String NAME;
}
public static class FlowerAdapter extends ArrayAdapter<Flowers> {
private ArrayList<Flowers> items;
private Context mContext;
public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){
super(context,textViewResourceID,items);
mContext = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Flowers flowers = items.get(position);
if(v==null){
LayoutInflater inflater =(LayoutInflater) getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.flower_lis_item,null);
}
TextView title = (TextView)v.findViewById(R.id.textView3);
TextView text =(TextView)v.findViewById(R.id.textView2);
if (title != null) {
title.setText(flowers.getName());
text.setText(flowers.getName());
}
return v;
}
}
}

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