in listview notifyDataSetChanged() methode has error - android

this is my main class where i am setting the adapter and calling the notifydatasetchanged() method the aim is to show the history of user in listview and refresh as the data is changed,but having error as stated earlier
public class HistoryActivity extends AppCompatActivity {
// Log tag
private static final String TAG = HistoryActivity.class.getSimpleName();
private static final String url ="http://192.168.0.102/android_login_api/historyfetch.php";
private ProgressDialog pDialog;
private List<HistoryItems> historyList = new ArrayList<HistoryItems>();
private ListView listView;
private CustomListAdapter adapter;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, historyList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
String user_email = user.get("email");
gethistory(user_email);
}
private void gethistory(final String email)
{
StringRequest stringRequest= new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,response.toString());
hideDialog();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<response.length();i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
HistoryItems historyItems = new HistoryItems();
historyItems.setName(obj.getString("user_email"));
historyItems.setLat_from(obj.getDouble("latitude_from"));
historyItems.setLon_from(obj.getDouble("longitude_from"));
historyItems.setLat_to(obj.getDouble("latitude_to"));
historyItems.setLon_to(obj.getDouble("longitude"));
historyItems.setDate(obj.getString("created_at"));
historyList.add(historyItems);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter;
})
{
protected Map<String,String>getParams(){
Map<String, String> params=new HashMap<>();
params.put("user_email",email);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
this is my custom adapter:-
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<HistoryItems> historyItems;
public CustomListAdapter(Activity activity, List<HistoryItems> historyItems) {
this.activity = activity;
this.historyItems = historyItems;
}
#Override
public int getCount() {
return historyItems.size();
}
#Override
public Object getItem(int location) {
return historyItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
TextView user_email = (TextView) convertView.findViewById(R.id.tv_user_email);
TextView lat_from = (TextView) convertView.findViewById(R.id.tv_lat_from);
TextView lon_from = (TextView) convertView.findViewById(R.id.tv_lon_from);
TextView lat_to = (TextView) convertView.findViewById(R.id.tv_lat_to);
TextView lon_to = (TextView) convertView.findViewById(R.id.tv_lon_to);
TextView date = (TextView) convertView.findViewById(R.id.tv_date);
// getting billionaires data for the row
HistoryItems m = historyItems.get(position);
// name
user_email.setText(m.getUser_email());
//
lat_from.setText(String.valueOf(m.getLat_from()));
lon_from.setText(String.valueOf(m.getLon_from()));
lat_to.setText(String.valueOf(m.getLat_to()));
lon_to.setText(String.valueOf(m.getLon_to()));
date.setText(String.valueOf(m.getDate()));
return convertView;
}
}
i am not getting where i made mistake
any help will be helpful....

hey man i didn't see any notifydatasetchanged() in your code i just see adapter;
Solution ==> adapter.notifydatasetchanged(); should be put after catch not outside the method

you have to give notifyDataSetChanged() for your adapter...
like this
for(int i=0;i<response.length();i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
HistoryItems historyItems = new HistoryItems();
.
.
.
.
historyList.add(historyItems);
}
adapter.notifyDataSetChanged();
Hope, It will help you :)

every time u add new item adapter will add new item in the listview.
for(int i=0;i<response.length();i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
HistoryItems historyItems = new HistoryItems();
historyItems.setName(obj.getString("user_email"));
historyItems.setLat_from(obj.getDouble("latitude_from"));
historyItems.setLon_from(obj.getDouble("longitude_from"));
historyItems.setLat_to(obj.getDouble("latitude_to"));
historyItems.setLon_to(obj.getDouble("longitude"));
historyItems.setDate(obj.getString("created_at"));
historyList.add(historyItems);
adapter.notifyDataSetChanged();
}

Related

I want to get 2 api url from json to bind them into one listview in android

I want to get 2 api url from json to bind them into one listview in android. One api read data detail and another read image so both of them into the same listview to show detail information.
Here is my first api to get text detail
public class NationalNewsFragment extends Fragment
{
SwipeRefreshLayout swipeRefreshLayout;
private ProgressDialog progressDialog;
ListView listView;
ImageView frontbanner;
//NEWS API
RequestQueue queue;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,
String>>();
static final String KEY_TITLE = "Title";
static final String KEY_INFO1 = "info1";
static final String KEY_C_DATE = "C_date";
static final String KEY_News_ID = "News_ID";
static final String KEY_C_BY = "C_by";
static final String KEY_C_VIEWS = "C_views";
//FrontBanner API
RequestQueue requestQueue;
static final String FRONT_BANNER = "Adv";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_national_news, container,
false);
listView = (ListView)view.findViewById(R.id.list_source);
swipeRefreshLayout =
(SwipeRefreshLayout)view.findViewById(R.id.refresh_layout);
//NEWS API
queue = Volley.newRequestQueue(getContext());
requestQueue = Volley.newRequestQueue(getContext());
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
String url = "my api url here";
JsonArrayRequest jsonArrayRequest = new
JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response)
{
for (int i = 0; i < response.length(); i++)
{
try
{
JSONObject news = response.getJSONObject(i);
HashMap<String, String> map = new
HashMap<String, String>();
map.put(KEY_TITLE,
news.optString(KEY_TITLE).toString());
map.put(KEY_INFO1,
news.optString(KEY_INFO1).toString());
map.put(KEY_C_DATE,
news.optString(KEY_C_DATE).toString());
map.put(KEY_News_ID,
news.optString(KEY_News_ID).toString());
map.put(KEY_C_BY,
news.optString(KEY_C_BY).toString());
map.put(KEY_C_VIEWS,
news.optString(KEY_C_VIEWS).toString());
//System.out.println(news.optString(KEY_TITLE).toString());
dataList.add(map);
ListNewsAdapter adapter = new
ListNewsAdapter(getActivity(), dataList);
listView.setAdapter(adapter);
} catch (JSONException e)
{
e.printStackTrace();
}
}
progressDialog.cancel();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getActivity(),
FreshNewsDetailActivity.class);
i.putExtra("News_ID", dataList.get(position).get(KEY_News_ID));
startActivity(i);
//Toast.makeText(MainActivity.this,
dataList.get(position).get(KEY_News_ID), Toast.LENGTH_SHORT).show();
}
});
//Refresh layout
swipeRefreshLayout.setOnRefreshListener(new
SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
String url = "my api url here";
JsonArrayRequest jsonArrayRequest = new
JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response)
{
for (int i = 0; i < response.length(); i++)
{
try
{
JSONObject news =
response.getJSONObject(i);
HashMap<String, String> map = new
HashMap<String, String>();
map.put(KEY_TITLE,
news.optString(KEY_TITLE).toString());
map.put(KEY_INFO1,
news.optString(KEY_INFO1).toString());
map.put(KEY_C_DATE,
news.optString(KEY_C_DATE).toString());
map.put(KEY_News_ID,
news.optString(KEY_News_ID).toString());
//System.out.println(news.optString(KEY_TITLE).toString());
dataList.add(map);
ListNewsAdapter adapter = new
ListNewsAdapter(getActivity(), dataList);
listView.setAdapter(adapter);
} catch (JSONException e)
{
e.printStackTrace();
}
}
progressDialog.cancel();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getActivity(),
FreshNewsDetailActivity.class);
i.putExtra("News_ID",
dataList.get(position).get(KEY_News_ID));
startActivity(i);
//Toast.makeText(MainActivity.this,
dataList.get(position).get(KEY_News_ID), Toast.LENGTH_SHORT).show();
}
});
}
});
return view;
}
}
Here is my dataAdapter code. Should I use one adapter? If so how to combine two datasource into the same dataAdapter. Or should I should use 2 dataAdapter and how to bind two dataAdapter into the same ListView in Android ?
class ListNewsAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
public ListNewsAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ListNewsViewHolder holder = null;
if (convertView == null)
{
holder = new ListNewsViewHolder();
convertView =
LayoutInflater.from(activity).inflate(R.layout.source_layout, parent,
false);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.c_by = (TextView) convertView.findViewById(R.id.c_by);
holder.c_views = (TextView) convertView.findViewById(R.id.c_views);
holder.c_date = (TextView) convertView.findViewById(R.id.c_date);
convertView.setTag(holder);
}
else
{
holder = (ListNewsViewHolder) convertView.getTag();
}
holder.title.setId(position);
holder.c_by.setId(position);
holder.c_views.setId(position);
holder.c_date.setId(position);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
try
{
holder.c_by.setText("ដោយ
"+song.get(NationalNewsFragment.KEY_C_BY));
holder.c_views.setText("/
"+song.get(NationalNewsFragment.KEY_C_VIEWS)+" views");
String sourceString = "<p align=\\\"justify\\\"><b><font
color=#000000>" + song.get(NationalNewsFragment.KEY_TITLE) + "</font></b> "
+ song.get(NationalNewsFragment.KEY_INFO1)+"</p>";
holder.title.setText(Html.fromHtml(sourceString));
holder.c_date.setText("ថ្ងៃទី ៖
"+song.get(NationalNewsFragment.KEY_C_DATE));
}
catch(Exception e) {}
return convertView;
}
}
class ListNewsViewHolder
{
TextView title, info1, c_date, c_by, c_views;
}
Should use one adapter. With complex data source (ex: need to fetch from multiple APIs) you should do some research about Reactive Programming. If apply Reactive Java + Android, you can do it by a few lines of code.
From the files, u have shared I got to know that you are using ClassCallApi to fetch both APIs. If so,
Create a new model class
public class CombinedApi {
private ArrayList<HashMap<String, String>> dataListOne;
private ArrayList<HashMap<String, String>> dataListTwo;
public ArrayList<HashMap<String, String>> getDataListOne() {
return dataListOne;
}
public void setDataListOne(ArrayList<HashMap<String, String>> dataListOne) {
this.dataListOne = dataListOne;
}
public ArrayList<HashMap<String, String>> getDataListTwo() {
return dataListTwo;
}
public void setDataListTwo(ArrayList<HashMap<String, String>> dataListTwo) {
this.dataListTwo = dataListTwo;
}
}
Make some changes to your ClassCallApi
ArrayList<CombinedApi> dataList = new ArrayList();
ArrayList<HashMap<String, String>> dataListOne = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> dataListTwo = new ArrayList<HashMap<String, String>>();
Once you complete the FIRST API CALL save data to dataListOne and once after you completed SECOND API CALL succesfully add that data to dataListTwo
dataListOne.add(map); //Data from api call one
dataListTwo.add(map); //Data from api call two
Please do use your logic to feed the above arrays.
Once u have both data. Create a simple function inside ClassCallApi to feed adapter
private void feedAdapter() {
for (int i = 0; i < dataListOne.size(); i++) {
CombinedApi mCombinedApi = new CombinedApi();
mCombinedApi.setDataListOne(dataListOne.get(i));
mCombinedApi.setDataListTwo(dataListTwo.get(i)); //Here i am assuming that both ArrayList have same size
dataList.add(mCombinedApi);
}
ListNewsAdapter adapter = new ListNewsAdapter(getActivity(), dataList);
listView.setAdapter(adapter);
}
A small change in Adapter as well.
private ArrayList<CombinedApi> data;
public ListNewsAdapter(Activity a, ArrayList<CombinedApi> d) {
activity = a;
data=d;
}
All set :)
To get song
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
instead use
song = data.get(position).getDataListOne();
or
song = data.get(position).getDataListTwo();

list doubles when back pressed in fragment

This is my Fragment in navigation view, it is opened as default when I clicked an item in navigation view and return back to this fragment the items in lists are doubled for example in list it has apple when i press back it shows two apples
public class AllProductsActivity extends Fragment {
private static final String TAG = MainActivity.class.getSimpleName();
private String category_id;
// Movies json url
private String url ;
private ProgressDialog pDialog;
private List<Movie> movieList=new ArrayList<Movie>() ;
private ListView listView;
private CustomListAdapter adapter;
public AllProductsActivity() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle=getArguments();
category_id = bundle.getString("IDS");
View rootView = inflater.inflate(R.layout.category_layout, container, false);
listView = (ListView) rootView.findViewById(R.id.categories_list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
category_id = bundle.getString("IDS");
VerifyURL();
return rootView;
}
private void VerifyURL() {
if (category_id.equals("no_product")) {
url = "http://192.168.43.149/Newfolder/gap.php";
DownloadJSON();
}else{
url = "http://192.168.43.149/Newfolder/gap.php?category_id=" + category_id;
DownloadJSON();
}
}
private void DownloadJSON(){
pDialog=new
ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("name"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(obj.getString("price"));
movie.setYear(obj.getString("description"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
} }}
This is my Adapter class where it opens a Activity i want to open a Fragment I already changed get Fragment manager to the get child Fragment manager but it does not work
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
HashMap<String, String> m = new HashMap<String, String>();
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount()
{
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.all_products, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.PI1);
ImageButton AddcarT=(ImageButton) convertView.findViewById(R.id.product_add_cart);
TextView title = (TextView) convertView.findViewById(R.id.PN1);
TextView rating = (TextView) convertView.findViewById(R.id.PD1);
TextView genre = (TextView) convertView.findViewById(R.id.PD2);
// getting movie data for the row
final Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
rating.setText("Rating: " + String.valueOf(m.getRating()));
// genre
genre.setText(m.getYear());
// release year
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
Movie m = movieItems.get(position);
Intent intent = new Intent(activity, ProductsViewActivity.class);
// Pass all data rank
intent.putExtra("rank", m.getTitle());
intent.putExtra("flag", m.getThumbnailUrl());
activity.startActivity(intent);
}
});
AddcarT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
Movie m = movieItems.get(position);
Toast.makeText(activity, m.getTitle(), Toast.LENGTH_LONG).show();
// Pass all data rank
}
});
return convertView;}
}
If you're not calling your api multiple times to use pagination, call movieList.clear() or movieList = new ArrayList<>(); before adding data into it.
So your code will be:-
// Checking of movieList is not null
if(movieList != null) {
movieList.clear();
} else {
movieList = new ArrayList<>();
}
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("name"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(obj.getString("price"));
movie.setYear(obj.getString("description"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
In onCreateView() method, clear your list.
movieList.clear();
use this:
if (adapter==null) {
prod = new ArrayList<>();
adapter = new ProductsAdapter(prod, getActivity());
if (Constants.isNetworkAvailable(getActivity())){
recyclerView.setLayoutManager(GlayoutManager);
recyclerView.setAdapter(adapter);
}else {
Constants.showToast(getActivity(),"No Internet!!");
recyclerView.setLayoutManager(GlayoutManager);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}else{
recyclerView.setLayoutManager(GlayoutManager);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Simply clear the list before adding data into ArrayList. It means when you click on the back press it will clear first and then insert data into the list. So you always get an updated list.
list.clear()

ListView repeating same JSON items on every Button click

I have a ListView on my main Activity and a button to fetch the JSON.
If I repeat the Button click, the same JSON elements is added to the ListView.
How can I clear the ListView if I click the Button again ?
CustomListAdapter
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Vehicle> vehicleItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Vehicle> vehicleItems) {
this.activity = activity;
this.vehicleItems = vehicleItems;
}
#Override
public int getCount() {
return vehicleItems.size();
}
#Override
public Object getItem(int location) {
return vehicleItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView rating = (TextView) convertView.findViewById(R.id.rating);
TextView genre = (TextView) convertView.findViewById(R.id.genre);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Vehicle m = vehicleItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
rating.setText("Rating: " + String.valueOf(m.getRating()));
// genre
String genreStr = "";
for (String str : m.getGenre()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,
genreStr.length() - 2) : genreStr;
genre.setText(genreStr);
// release year
year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
SearchActivity
public class SearchActivity extends Activity implements View.OnClickListener {
// Log tag
private static final String TAG = SearchActivity.class.getSimpleName();
// Vehicles json url
private static final String url = "https://api.myjson.com/bins/3u7ty";
private SweetAlertDialog pDialog;
private List<Vehicle> vehicleList = new ArrayList<Vehicle>();
private ListView listView;
private CustomListAdapter adapter;
private Button buttonGet2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
buttonGet2 = (Button) findViewById(R.id.buttonGet2);
buttonGet2.setOnClickListener(this);
}
private void getData() {
listView=(ListView) findViewById(R.id.list2);
adapter=new CustomListAdapter(this,vehicleList);
listView.setAdapter(adapter);
final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Loading");
pDialog.setCancelable(true);
// Showing progress dialog before making http request
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest vehicleReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.dismissWithAnimation();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Vehicle vehicle = new Vehicle();
vehicle.setTitle(obj.getString("title"));
vehicle.setThumbnailUrl(obj.getString("image"));
vehicle.setRating(((Number) obj.get("rating"))
.doubleValue());
vehicle.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
vehicle.setGenre(genre);
// adding vehicle to vehicles array
vehicleList.add(vehicle);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.dismissWithAnimation();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(vehicleReq);
}
#Override
public void onClick(View v) {
getData();
}
}
You are adding the content of Json object to your vehicleList again and again. The vehicleList still holds the old values. Then you catch the values from the Json object again and add it again to the vehicleList. To get rid of this, clear the list:
private void getData() {
vehicleList.clear();
listView=(ListView) findViewById(R.id.list2);
adapter=new CustomListAdapter(this,vehicleList);
//rest of your code
}
Along with clearing the data, just make that method only responsible for getting the data, not repeating initializing the adapter and list.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
buttonGet2 = (Button) findViewById(R.id.buttonGet2);
buttonGet2.setOnClickListener(this);
// Moved these lines
listView = (ListView) findViewById(R.id.list2);
adapter = new CustomListAdapter(this,vehicleList);
listView.setAdapter(adapter);
}
private void getData() {
vehicleList.clear(); // Added this
final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Loading");
pDialog.setCancelable(true);

Unable to view the content in listview

I am using a list view in fragment which loads data using json in that i cannot able to view the list view.In the sched it shows the constructor is never used i don't know where i have done wrong in the code.The server part works fine.
Fragment:
public class SchedulessFragment extends Fragment{
private static final String TAG = MatAct.class.getSimpleName();
private static final String url = "http://nammakovai2015-001-site1.1tempurl.com/iplspin/schedules.php";
ProgressDialog pDialog;
List<Sched> movieList = new ArrayList<Sched>();
ListView listview;
CustomListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.schedule_frag, container, false);
adapter = new CustomListAdapter(getActivity(), movieList);
listview = (ListView) v.findViewById(R.id.listView1);
listview.setAdapter(adapter);
// TextView tv = (TextView) v.findViewById(R.id.tvfrag);
// tv.setText(getArguments().getString("msg"));
// tv.setText("Hello");
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Sched m = new Sched();
m.setTeama(obj.getString("teama"));
m.setTeamb(obj.getString("teamb"));
m.setTdate(obj.getString("tdate"));
m.setTtime(obj.getString("ttime"));
m.setThumbnailUrl(obj.getString("thumbnailUrl"));
m.setTeambthumbnailUrl(obj.getString("teambthumbnailUrl"));
m.setVenue(obj.getString("venue"));
// adding movie to movies array
movieList.add(m);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public static SchedulessFragment newInstance(String text) {
SchedulessFragment f = new SchedulessFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}}
ListAdapter:
public class CustomListAdapter extends BaseAdapter{
private Activity activity;
private LayoutInflater inflater;
List<Sched> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Sched> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.listitem_ros, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.pict);
NetworkImageView teambthumbnail=(NetworkImageView) convertView.findViewById(R.id.pict1);
TextView teama = (TextView) convertView.findViewById(R.id.scheduleteama_name);
TextView teamb = (TextView) convertView.findViewById(R.id.schduleteamb_name);
TextView tdate = (TextView) convertView.findViewById(R.id.datess);
TextView ttime = (TextView) convertView.findViewById(R.id.timess);
TextView venue=(TextView)convertView.findViewById(R.id.schedulevenue);
// getting movie data for the row
Sched m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
teambthumbnail.setImageUrl(m.getTeambthumbnailUrl(),imageLoader);
// title
teama.setText(m.getTeama());
teamb.setText(m.getTeamb());
tdate.setText(m.getTdate());
ttime.setText(m.getTtime());
venue.setText(m.getVenue());
return convertView;
}}
Sched:
public class Sched {
private String teama,teamb,tdate,ttime,thumbnailUrl,teambthumbnailUrl,venue;
public Sched(){}
public Sched(String teama, String teamb, String tdate, String ttime, String thumbnailUrl, String teambthumbnailurl, String venue)
{
this.teama=teama;
this.teamb=teamb;
this.tdate=tdate;
this.ttime=ttime;
this.thumbnailUrl=thumbnailUrl;
this.teambthumbnailUrl=teambthumbnailurl;
this.venue=venue;
}
public String getTeama(){
return teama;
}
public void setTeama(String teama){
this.teama=teama;
}
public String getTeamb(){
return teamb;
}
public void setTeamb(String teamb){
this.teamb=teamb;
}
public String getTdate(){
return tdate;
}
public void setTdate(String tdate){
this.tdate=tdate;
}
public String getTtime(){
return ttime;
}
public void setTtime(String ttime){
this.ttime=ttime;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getTeambthumbnailUrl() {
return teambthumbnailUrl;
}
public void setTeambthumbnailUrl(String teambthumbnailUrl){
this.teambthumbnailUrl=teambthumbnailUrl;
}
public String getVenue(){
return venue;
}
public void setVenue(String venue){
this.venue=venue;
}}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
>
</ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/tvfrag"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="219dp" />
Your problem is that you are creating the adapter before the movieList has been populated. Move these two lines:
adapter = new CustomListAdapter(getActivity(), movieList);
listview.setAdapter(adapter);
after the for loop in which you're adding the Movies to the list:
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Sched m = new Sched();
m.setTeama(obj.getString("teama"));
m.setTeamb(obj.getString("teamb"));
m.setTdate(obj.getString("tdate"));
m.setTtime(obj.getString("ttime"));
m.setThumbnailUrl(obj.getString("thumbnailUrl"));
m.setTeambthumbnailUrl(obj.getString("teambthumbnailUrl"));
m.setVenue(obj.getString("venue"));
// adding movie to movies array
movieList.add(m);
} catch (JSONException e) {
e.printStackTrace();
}
//PUT THOSE TWO LINES HERE
Assuming your Request is good and it returns a non-empty JSONArray, this should work.

Append new elements from custom adapter to ListView

I've got a ListView with a 'show next results' button. The list is filled by a custom adapter extending BaseAdapter. Using it as shown below, only the new results are shown.
How can I append the new results to the list?
ListView listView = (ListView)findViewById(android.R.id.list);
// Show next results button
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = getIntent();
i.putExtra("firstIndex", mFirstIndex + NRES_PER_PAGE);
i.putExtra("itemCount", NRES_PER_PAGE);
startActivity(i);
}
});
mItems = json.getJSONArray("data");
setListAdapter(new ItemAdapter(ItemList.this, mType, mItems));
FIX
ListActivity
public class ItemList extends MenuListActivity{
ItemAdapter mItemAdapter;
Integer mFirstIndex = 0;
JSONArray mItems = new JSONArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
// Set data adapter
mItemAdapter = new ItemAdapter(ItemList.this, mType, mItems);
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
setListAdapter(mItemAdapter);
new GetItemInfoList().execute();
}
private class GetItemInfoList extends AsyncTask<Void, Void, JSONObject> {
protected JSONObject doInBackground(Void... params) {
// Set POST data to send to web service
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add(new BasicNameValuePair("firstindex", Integer.toString(mFirstIndex)));
postData.add(new BasicNameValuePair("itemscount", Integer.toString(ITEM_COUNT)));
JSONObject json = RestJsonClient.getJSONObject(URL_ITEMINFOLIST, postData);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
// Get data from json object and set to list adapter
JSONArray jsonArray = json.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++)
mItems.put(jsonArray.get(i));
mItemAdapter.notifyDataSetChanged();
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
} catch (JSONException e) {
}
}
}
}
Adapter
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private JSONArray mItems;
private ImageLoader mImageLoader;
private int mCategory;
public ItemAdapter(Context context, int category, JSONArray items) {
mContext = context;
mInflater = LayoutInflater.from(context);
mItems = items;
mCategory = category;
this.mImageLoader = new ImageLoader(context, true);
}
public int getCount() {
return mItems.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_row, null);
holder = new ViewHolder();
holder.listitem_pic = (ImageView) convertView.findViewById(R.id.listitem_pic);
holder.listitem_desc = (TextView) convertView.findViewById(R.id.listitem_desc);
holder.listitem_title = (TextView) convertView.findViewById(R.id.listitem_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
JSONObject item = mItems.getJSONObject(position);
String listitem_pic = item.getString("picture");
holder.listitem_pic.setTag(listitem_pic);
mImageLoader.DisplayImage(listitem_pic, (Activity)mContext, holder.listitem_pic);
holder.listitem_title.setText(item.getString("title"));
holder.listitem_desc.setText(item.getString("desc"));
}
catch (JSONException e) {
}
return convertView;
}
static class ViewHolder {
TextView listitem_title;
ImageView listitem_pic;
TextView listitem_desc;
}
}
It depends on your implementation of ItemAdapter, I'd recommend holding a reference to ItemAdapter, then updating the data set behind it and then calling notifyDataSetChanged() on it. something like:
ItemAdapter ia = new ItemAdapter(ItemList.this, mType, mItems);
setListAdapter(ia);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mItems.append(newItems);
ia.notifyDataSetChanged();
}
});
It is tricky without knowing what data you are using or whether you have the entire data set available at the start.

Categories

Resources