I am getting NullPointerException in the activity where I am using adapter.notifyDataSetChanged();
Basically in the activity i am parsing the data and I am using the adapter of where the data needs to be setin the ListItems.
The code of the MainActivity -
public class SearchResultActivityOne extends AppCompatActivity {
private static final String url = "http://sikkimexpress.itstunner.com/api/newssearch/a";
private boolean enableBackNavigation;
String TAG = "";
private ProgressDialog pDialog;
private CustomListSearchAdapter adapter;
public static final String KEY_HEADURL = "news_url";
public static final String KEY_DETAILS = "news_details";
public static final String KEY_TITLE = "news_title";
String imageURL = "", title = "", description = "";
private List<Movie> movieList = new ArrayList<Movie>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
adapter.notifyDataSetChanged();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
if (enableBackNavigation) {
// toolbar.setNavigationIcon(R.drawable.ic_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
// pDialog = new ProgressDialog(SearchResultActivityOne.this);
// pDialog.setMessage("Loading...Please Wait...");
// pDialog.setCancelable(false);
// pDialog.show();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
movie.setDescription(homenews.getString("Description"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
}
} catch (JSONException exception){
exception.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(request);
}
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about_us:
Intent intent = new Intent(SearchResultActivityOne.this, AboutUs.class);
startActivity(intent);
return true;
case R.id.action_terms_of_use:
Intent intent_two = new Intent(SearchResultActivityOne.this, TermsUse.class);
startActivity(intent_two);
return true;
case R.id.action_privacy_policy:
Intent intent_three = new Intent(SearchResultActivityOne.this, PrivacyPolicy.class);
startActivity(intent_three);
return true;
case R.id.action_contact_us:
Intent intent_four = new Intent(SearchResultActivityOne.this, ContactUs.class);
startActivity(intent_four);
case R.id.action_search:
default:
return super.onOptionsItemSelected(item);
}
}
}
The CustomListViewAdapter
public class CustomListSearchAdapter extends BaseAdapter{
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListSearchAdapter(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(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 desciption = (TextView) convertView.findViewById(R.id.desciption);
Movie m = movieItems.get(position);
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
String text = Html.fromHtml(m.getTitle()).toString();
title.setText(text);
String text_two = Html.fromHtml(m.getDescription()).toString();
desciption.setText(text_two);
return convertView;
}
}
Your adapter object is not initialized yet so the notifyDatasetChanged() will raise a NullPointerException.
You'll need something along the lines of
adapter = new CustomListSearchAdapter(SearchResultActivityOne.this, movieList);
//Set the adapter to your ListView
Before you call adapter.notifyDatasetChanged() in your onCreate() method.
But I suspect you'll want to call notifyDatasetChanged() in the onResponse() when your movieList actually has items. Also, what is the point of having an adapter without a ListView?
I think you are missing some code. Initialize your ListView and adapter first. Something like this
ListView listView = (ListView) findById(R.id.list);
adapter = new CustomListSearchAdapter(SearchResultActivityOne.this, movieList);
listView.setAdapter(adapter);
You have to initialize your adapter:
adapter = new CustomListSearchAdapter();
Then set it on the list view
listview.setAdapter(adapter);
Update 1
In onCreate method:
ListView myListView = (ListView) findViewById(R.id.myListView);
CustomListSearchAdapter adapter = new CustomListSearchAdapter(... arguments ...);
myListView.setAdapter(adapter);
Then use this list view to set your adapter
Related
Am trying search from listview using custom adapter. i have search widget in toolbar menu and i can display widget. when i click on search icon, it expands, but when i start typing, search does not happen and list gets cleared. can someone plz trace this issue .
Here's my code from Main Activity:
public class VideoActivity extends BaseActivity {
ListView listView;
ArrayList<Video> videoArrayList;
public VideoListAdapter videoListAdapter;
String vid_id, vid_title, vid_type, vid_path, vid_img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
initializeToolbar();
listView = (ListView) findViewById(R.id.listview_video);
videoArrayList = new ArrayList<Video>();
videoListAdapter = new VideoListAdapter(VideoActivity.this, videoArrayList);
jsonParser = new JSONParser();
new VideoTask().execute();
public class VideoTask extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
jsonObject = jsonParser.makeHttpRequest2(Network_constants.video_list_page, "POST");
Log.e("json data", "" + jsonObject);
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
progressDialog.dismiss();
if (jsonObject != null) {
try {
jsonArray = jsonObject.getJSONArray("videos");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Log.d("jsonObject1", "" + jsonObject1);
Video video = new Video();
vid_id = jsonObject1.getString("video_id");
vid_title = jsonObject1.getString("video_channel_name");
vid_type = jsonObject1.getString("video_channel_link");
vid_path = jsonObject1.getString("video_channel_description");
vid_img = jsonObject1.getString("video_img_path");
video.set_vTitle(vid_title);
TextView t1 = (TextView) findViewById(R.id.video_title);
TextView t2 = (TextView) findViewById(R.id.video_type);
video.set_vArtist(vid_title);
video.set_vType(vid_type);
videoArrayList.add(video);
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(videoListAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView cnt = (TextView) view.findViewById(R.id.video_type);
String cn = cnt.getText().toString();
Intent i = new Intent(VideoActivity.this, Youtube.class);
i.putExtra("url", cn);
startActivity(i);
}
});
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.clear();
getMenuInflater().inflate(R.menu.main,menu);
MenuItem menuItem = menu.findItem(R.id.menu_search);
final SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(TextUtils.isEmpty(newText)){
LogHelper.e("Query Result","Filter is Empty");
}else{
videoListAdapter.filter(newText);
}
return true;
}
});
return true;
}
}
And this is my CustomAdapter class :
public class VideoListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
ImageView imageView;
private String mCurrentArtUrl;
private ArrayList<Video> video;
private ArrayList<Video> searchListView = null;
public VideoListAdapter(Activity a, ArrayList<Video> b){
this.activity = a;
this.video = b;
this.searchListView = new ArrayList<Video>();
this.searchListView.addAll(video);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return video.size();
}
#Override
public Object getItem(int position) {
return video.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.video_list_item, null);
final TextView v_title = (TextView)vi.findViewById(R.id.video_title);
final TextView v_type = (TextView)vi.findViewById(R.id.video_type);
final TextView v_artist = (TextView)vi.findViewById(R.id.video_artist);
imageView = (ImageView) vi.findViewById(R.id.video_image);
Video video1 = video.get(position);
v_title.setText(video1.get_vTitle());
v_type.setText(video1.get_vType());
v_artist.setText(video1.get_vArtist());
String img = video1.get_vImage();
String profile = Network_constants.image_url + img;
fetchImageAsync(profile);
return vi;
}
// Filter method
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
video.clear();
if(charText.length() == 0){
video.addAll(searchListView);
}else{
for(Video v : searchListView){
LogHelper.e("Query","Entered For Loop");
if(v.get_vTitle().contains(charText)){
video.add(v);
}else{
LogHelper.e("Query","Could not create list");
}
}
}
notifyDataSetChanged();
}
}
I think my code is not working with the for loop in the filter function i guess.
You should implements Filterable in your Adapter
I have code to show listview from my server, but when I update the data from server and refresh it in my app, the listview still getting the old data, and after several minutes when I open the app again, it updated the new data that I updated before.
My Main Fragment
public class DosenFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
}
I have tried to do something with itemList.clear(); and adapter.notifyDataSetChanged(); but nothing change.
My Main Adapter
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.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);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
I'm sorry for my bad english.
Please help.
try this , add this method in your adatper
public void updateList(List<Dosen> newlist) {
items.clear();
items.addAll(newlist);
this.notifyDataSetChanged();
}
and in callVolley() method , replace this
adapter.notifyDataSetChanged();
with
adapter.updateList();
Hope this helps
Use the below Code...
/* Within the RecyclerView.Adapter class */
// Clean all elements of the recycler
public void clear() {
items.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Dosen> newlist) {
items.addAll(newlist);
notifyDataSetChanged();
}
callvolly() method inside.
adapter.clear();
adapter.addAll(item);
public void onRefresh() {
callVolley();
}
please try this code i have changed something it will work fine
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
public void setData(List<Dosen> items){
this.items = items
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.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);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
public class DosenFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout)
v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
//itemList.clear();
//adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
itemList .clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj =
response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.setData(itemList );
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
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()
I have a ListView on my android app. When click a ListView item and go to a new activity and when i press back button i land on a empty ListView. I dont get any data. Even if i restart the app i dont get any data on the ListView. It works only the first time i run the app. Do i have to override the onStop method and reset my ListView adapter? how do i fix this?
ListView activity
public class ViewGuidesActivity extends AppCompatActivity {
private static final String TAG = ViewGuidesActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<Guide> guideList = new ArrayList<Guide>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_guides);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, guideList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_GET_GUIDE_LIST,
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);
Guide guide = new Guide();
guide.setNgno(obj.getString("ngno"));
guide.setEmail(obj.getString("email"));
guide.setName(obj.getString("name"));
// adding movie to movies array
guideList.add(guide);
} 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) {
Log.d(TAG, error.toString());
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Guide newGuide = guideList.get(position);
String email = newGuide.getEmail();
String ngno = newGuide.getNgno();
Intent i = new Intent(getApplicationContext(), GuideDetails.class);
i.putExtra("email", email);
i.putExtra("ngno", ngno);
startActivity(i);
}
});
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.getItem(1).setVisible(false);
menu.getItem(2).setVisible(false);
return true;
}
}
ListAdapter
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Guide> guideItems;
public CustomListAdapter(Activity activity, List<Guide> guideItems) {
this.activity = activity;
this.guideItems = guideItems;
}
#Override
public int getCount() {
return guideItems.size();
}
#Override
public Object getItem(int location) {
return guideItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customrow, parent, false);
TextView ngno = (TextView) convertView.findViewById(R.id.txt_ListNgno);
TextView name = (TextView) convertView.findViewById(R.id.txt_ListName);
TextView email = (TextView) convertView.findViewById(R.id.txt_ListEmail);
// getting guide data for the row
Guide g = guideItems.get(position);
//thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
ngno.setText(g.getNgno());
name.setText(g.getName());
email.setText(g.getEmail());
return convertView;
}
}
how do i fix this issue?
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.