How to use notifyDataSetChanged with a fragment, AsyncTask,RecyclerView and GSON - android

I'm trying to work on a weather app and I have tried to resolve the issue of using the RecyclerView with my ArrayList. However I am getting the error of no adapter attached. I have tried to attach a Listener but that isn't working so I am trying to use the notifyDataSetChanged method but I am confused as to how to use it. I've tried to put it in the post execute but I get another error. Can some help me figure out how to use it?
Here is my Fragment:
public class WeatherAppFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
RecyclerView mRecyclerView;
String mStatusView;
private List<ForecastWeatherList> weatherList = new ArrayList<>();
private RecyclerViewAdapter mAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public WeatherAppFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment WeatherAppFragment.
*/
// TODO: Rename and change types and number of parameters
public static WeatherAppFragment newInstance(String param1, String param2) {
WeatherAppFragment fragment = new WeatherAppFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather_app, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
mRecyclerView.setAdapter(mAdapter);
new WeatherAppFragment.GetWeatherAync().execute(getActivity());
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
queryTextListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
Log.i("onQueryTextChange", newText);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
Log.i("onQueryTextSubmit", query);
mStatusView = query;
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
}
super.onCreateOptionsMenu(menu, inflater);
}
public class GetWeatherAync extends AsyncTask<Context, Void, ArrayList<ForecastWeatherList>> {
private String TAG = GetWeatherAync.class.getSimpleName();
public String api_key = "&APPID=ce7da0eaca788fc6342028eae6f3dd5c";
private Context context;
private final String serviceUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + "Baltimore" + api_key;
#Override
protected ArrayList<ForecastWeatherList> doInBackground(Context...params) {
context = params[0];
try {
Log.e(TAG, "I'm in background");
URL url = new URL(serviceUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(4000);
connection.setReadTimeout(4000);
connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
ForecastWeatherListWrapper weatherWrapper = new Gson().fromJson(bufferedReader, ForecastWeatherListWrapper.class);
return (ArrayList<ForecastWeatherList>) weatherWrapper.getforecastWeatherLists();
} catch (Exception e) {}
return null;
}
#Override
protected void onPostExecute(ArrayList<ForecastWeatherList> result ) {
super.onPostExecute(result);
if (result != null) {
Log.e(TAG, "populate UI recycler view with gson converted data");
RecyclerViewAdapter weatherRecyclerViewAdapter = new RecyclerViewAdapter(result,context);
mRecyclerView.setAdapter(weatherRecyclerViewAdapter);
mAdapter.notifyDataSetChanged();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
// Not implemented here
return false;
default:
break;
}
searchView.setOnQueryTextListener(queryTextListener);
return super.onOptionsItemSelected(item);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Here is my RecyclerViewAdapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ForecastRecycler> {
ArrayList<ForecastWeatherList> mForecastWeatherDataList;
private Context context;
public static class ForecastRecycler extends RecyclerView.ViewHolder{
public TextView currentTemp;
public TextView currentHumidity;
public TextView currentDescription;
public ImageView currentIcon;
public ForecastRecycler (View view) {
super (view);
currentTemp = (TextView) view.findViewById(R.id.current_temperature);
currentHumidity = (TextView) view.findViewById(R.id.current_humidity);
currentDescription = (TextView) view.findViewById(R.id.current_weather_description);
currentIcon = (ImageView) view.findViewById(R.id.current_weather_icon);
}
}
public RecyclerViewAdapter(List<ForecastWeatherList> mForecastWeatherDataList, Context context) {
this.mForecastWeatherDataList = (ArrayList<ForecastWeatherList>) mForecastWeatherDataList;
this.context = context;
}
#Override
public ForecastRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ForecastRecycler currentRecycler = new ForecastRecycler(view);
return currentRecycler;
}
#Override
public void onBindViewHolder( ForecastRecycler holder, int position) {
final ForecastWeatherList currentRecycler = mForecastWeatherDataList.get(position);
holder.currentTemp.setText((currentRecycler.getMain().getTempKf()));
holder.currentHumidity.setText(currentRecycler.getMain().getHumidity());
holder.currentDescription.setText(currentRecycler.getWeather().getDescription());
Picasso.with(holder.currentIcon.getContext()).load(currentRecycler.getWeather().getIcon());
}
#Override
public int getItemCount() {
return mForecastWeatherDataList.size();
}
}

notifyDataSetChanged() is used after setting-adding RecyclerView's Adapter data.
Try adding: notifyDataSetChanged() after
mRecyclerView.setAdapter(mAdapter);
Or whereever you update-add data to the Adapter. Or, you can try with this:
mAdapter.notifyDataSetChanged()
In onPostExecute.

it seems you forgot to update the adapter with your results...at onPostExecute :
update mForecastWeatherDataList then call notifyDataSetChanged()

Related

E/RecyclerView: No adapter attached; skipping layout using fragments and GSON

I've tried to look for a solution but I have not been able to find one with my specific situation. I'm using a recyclerview with GSON and I'm getting the message of skipping layout. My code looks correct but I know I should set an empty adapter in the onCreateView section. I'm not sure how to exactly do that. Any help will be appreciated. My fragment activity is below.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather_app, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
new GetWeatherAync().execute(getActivity());
return view;
}
private class GetWeatherAync extends AsyncTask<Context, Void,
List<ForecastWeatherList>> {
private String TAG = GetWeatherAync.class.getSimpleName();
private Context mContext;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<ForecastWeatherList> doInBackground(Context...params) {
mContext = params[0];
return getWeatherFromServer();
}
#Override
protected void onPostExecute(List<ForecastWeatherList> result) {
super.onPostExecute(result);
if (result != null) {
Log.e(TAG, "populate UI recycler view with gson converted data");
RecyclerViewAdapter weatherRecyclerViewAdapter = new RecyclerViewAdapter(result, mContext);
mRecyclerView.setAdapter(weatherRecyclerViewAdapter);
}
}
}
public List<ForecastWeatherList> getWeatherFromServer(){
String serviceUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + searchView + api_key;
URL url = null;
try {
url = new URL(serviceUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(4000);
connection.setReadTimeout(4000);
connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//pass buffered reader to convert json to javaobject using gson
return convertJsonToObject(bufferedReader);
}catch (Exception e){
}
return null;
}
public List<ForecastWeatherList> convertJsonToObject(BufferedReader bufferedReader){
final Gson gson = new Gson();
//pass root element type to fromJson method along with input stream
ForecastWeatherListWrapper weatherWrapper = gson.fromJson(bufferedReader,ForecastWeatherListWrapper.class);
List<ForecastWeatherList> weatherlst = weatherWrapper.getforecastWeatherLists();
return weatherlst;
}
EDIT:
So I've implemented the following changes:
Listener Interface.
import com.ksburneytwo.weathertest.ForecastWeather.ForecastWeatherList;
import java.util.List;
public interface Listener {
void afterSearch(List<ForecastWeatherList> result);
}
Fragment:
public static WeatherAppFragment newInstance(String param1, String param2) {
WeatherAppFragment fragment = new WeatherAppFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather_app, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
new GetWeatherAync().execute(getActivity());
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
queryTextListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
Log.i("onQueryTextChange", newText);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
Log.i("onQueryTextSubmit", query);
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void afterSearch(List<ForecastWeatherList> result) {
mRecyclerView.setAdapter(new RecyclerViewAdapter(result, mRecyclerView.getContext()));
}
private static class GetWeatherAync extends AsyncTask<Context, Void, List<ForecastWeatherList>> {
private String TAG = GetWeatherAync.class.getSimpleName();
private final String serviceUrl;
private Context mContext;
private Listener listener;
GetWeatherAync(Listener listener,String searchView, String api_key) {
this.listener = listener;
this.serviceUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + searchView + api_key;
}
#Override
protected List<ForecastWeatherList> doInBackground(Context...params) {
try {
URL url = new URL(serviceUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(4000);
connection.setReadTimeout(4000);
connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
ForecastWeatherListWrapper weatherWrapper = new Gson().fromJson(bufferedReader, ForecastWeatherListWrapper.class);
return weatherWrapper.getforecastWeatherLists();
} catch (Exception e) {}
return null;
}
#Override
protected void onPostExecute(List<ForecastWeatherList> result) {
super.onPostExecute(result);
if (result != null) {
Log.e(TAG, "populate UI recycler view with gson converted data");
listener.afterSearch(result);
}
}
}
Here is the recyclerview adapter.
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.ForecastRecycler> {
List<ForecastWeatherList> mForecastWeatherDataList;
public static class ForecastRecycler extends RecyclerView.ViewHolder{
public TextView currentTemp;
public TextView currentHumidity;
public TextView currentDescription;
public ImageView currentIcon;
public ForecastRecycler (View view) {
super (view);
currentTemp = (TextView) view.findViewById(R.id.current_temperature);
currentHumidity = (TextView) view.findViewById(R.id.current_humidity);
currentDescription = (TextView) view.findViewById(R.id.current_weather_description);
currentIcon = (ImageView) view.findViewById(R.id.current_weather_icon);
}
}
public RecyclerViewAdapter(List<ForecastWeatherList> mForecastWeatherDataList, Context mContext) {
this.mForecastWeatherDataList = mForecastWeatherDataList;
}
#Override
public ForecastRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ForecastRecycler currentRecycler = new ForecastRecycler(view);
return currentRecycler;
}
#Override
public void onBindViewHolder( ForecastRecycler holder, int position) {
final ForecastWeatherList currentRecycler = mForecastWeatherDataList.get(position);
holder.currentTemp.setText((currentRecycler.getMain().getTempKf()));
holder.currentHumidity.setText(currentRecycler.getMain().getHumidity());
holder.currentDescription.setText(currentRecycler.getWeather().getDescription());
Picasso.with(holder.currentIcon.getContext()).load(currentRecycler.getWeather().getIcon());
}
#Override
public int getItemCount() {
return mForecastWeatherDataList.size();
}
}
Here are my current logs. I know its connecting to the server but I'm still getting no adapter attached error.
11371-11371/com.ksburneytwo.weathertest D/debugMode: The application is in onCreateView
11371-11396/com.ksburneytwo.weathertest D/debugMode: The application is in doInBackground
11371-11371/com.ksburneytwo.weathertest E/RecyclerView: No adapter attached; skipping layout
11371-11396/com.ksburneytwo.weathertest D/NetworkSecurityConfig: No Network Security Config specified, using platform default
11371-11396/com.ksburneytwo.weathertest D/debugMode: The application stopped after catch
Try notifyDataSetChanged() in adapter after initializing in onCreateView() method.
or use this approach:
Listener:
public interface Listener {
void afterSearch(List<ForecastWeatherList> result);
}
Fragment:
public class MyFragment extends Fragment implements Listener {
RecyclerView mRecyclerView;
List<ForecastWeatherList> items = new ArrayList<>();
RecyclerViewAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather_app, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
adapter = new RecyclerViewAdapter(items, mRecyclerView.getContext());
mRecyclerView.setAdapter(adapter);
new GetWeatherAync(this, searchView, api_key).execute();
return view;
}
public afterSearch(List<ForecastWeatherList> result) {
items = result;
adapter.notifyDataSetChanged();
}
}
AsyncTask:
private static class GetWeatherAync extends AsyncTask<Context, Void, List<ForecastWeatherList>> {
private String TAG = GetWeatherAync.class.getSimpleName();
private final String serviceUrl;
private Context mContext;
private Listener listener;
public GetWeatherAync(Listener listener, Object searchView, Object api_key) {
this.listener = listener;
this.serviceUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + searchView + api_key;
}
#Override
protected List<ForecastWeatherList> doInBackground(Context...params) {
try {
URL url = new URL(serviceUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(4000);
connection.setReadTimeout(4000);
connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
ForecastWeatherListWrapper weatherWrapper = new Gson().fromJson(bufferedReader, ForecastWeatherListWrapper.class);
return weatherWrapper.getforecastWeatherLists();
} catch (Exception e) {}
return null;
}
#Override
protected void onPostExecute(List<ForecastWeatherList> result) {
super.onPostExecute(result);
if (result != null) {
Log.e(TAG, "populate UI recycler view with gson converted data");
listener.afterSearch(result);
}
}
}

Getting the values of ListView selected item

I have this ListView adapter:
public class UpicksAdapter extends BaseAdapter
{
Context context;
List<Upick> upick_list;
public UpicksAdapter(List<Upick> listValue, Context context)
{
this.context = context;
this.upick_list = listValue;
}
#Override
public int getCount()
{
return this.upick_list.size();
}
#Override
public Object getItem(int position)
{
return this.upick_list.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listview_items, null);
viewItem.SubNameTextView = (TextView)convertView.findViewById(R.id.SubjectNameTextView);
viewItem.SubFullFormTextView = (TextView)convertView.findViewById(R.id.SubjectFullFormTextView);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.SubNameTextView.setText(upick_list.get(position).Subject_Name);
viewItem.SubFullFormTextView.setText(upick_list.get(position).Subject_Full_Form);
return convertView;
}
}
class ViewItem
{
TextView SubNameTextView;
TextView SubFullFormTextView;
}
The ListView is in a fragment.
I need to get data from the listview selected item. I have this listener:
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = UpicksListView.getItemAtPosition(position).toString();
Log.d("VALOR","VALOR "+item);
}
});
How can I get the values of the selected item?
EDIT:
Complete Fragment code:
public class MisUpicksFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private SessionManager session;
private ProgressDialog loading;
private EditText txtbusqueda;
private Button botonbuscar,botonrefrescar;
//movies
private static final String TAG = MainActivity.class.getSimpleName();
public List<Upick> upicks;
private RecyclerView recyclerView;
private GridLayoutManager gridLayout;
private UpicksAdapter adapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String user_id;
private Button btnNew;
ListView UpicksListView;
ProgressBar progressBar;
String HttpURL = "http://***/upicks_todos.php";
private OnFragmentInteractionListener mListener;
public MisUpicksFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MensajesFragment.
*/
// TODO: Rename and change types and number of parameters
public static MisUpicksFragment newInstance(String param1, String param2) {
MisUpicksFragment fragment = new MisUpicksFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_misupicks, container, false);
UpicksListView = (ListView) view.findViewById(R.id.UpicksListView);
progressBar = (ProgressBar) view.findViewById(R.id.ProgressBar1);
new ParseJSonDataClass(getActivity()).execute();
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = UpicksListView.getItemAtPosition(position).toString();
Log.d("VALOR","VALOR "+item);
}
});
return view;
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
List<Upick> upickFullFormList;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Upick upick;
upickFullFormList = new ArrayList<Upick>();
for (int i = 0; i < jsonArray.length(); i++) {
upick = new Upick();
jsonObject = jsonArray.getJSONObject(i);
upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");
upickFullFormList.add(upick);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
UpicksListView.setVisibility(View.VISIBLE);
if (upickFullFormList != null) {
UpicksAdapter adapter = new UpicksAdapter(upickFullFormList, context);
UpicksListView.setAdapter(adapter);
}
}
}
private void logoutUser() {
session.setLogin(false);
// Launching the login activity
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
//finish();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Change this code to setters.
upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");
eg:
upick.setSubjectname(jsonObject.getString("id_servicio"));
Then inside onclick you can take values using getters
String item = upicks.get(position).getSubjectname();
parent.getItemAtPosition(position) will return an Object (the model used in your adapter).To get some field from your Object don't call Object.toString(); it will return the object reference not the value that you're looking for. Use Object.yourField; instead.
The ArrayList.get() method is used to get the element of a specified
position within the list.
String str_ITEM= upicks.get(position).yourGETMETHOD();
in your callback listener you have adapter object just use that like below.
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = parent.getSelectedItem().toString();
Log.d("VALOR","VALOR "+item);
}
});

ArrayList.size() showing zero every time. Actually im trying to Filter the Data using the data stored on the ArrayList

ArrayList.size() showing zero every time. Actually im trying to Filter the Data using the data stored on the ArrayList
This is my HomeFragment.Java
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String TAG_check="check";
public RecyclerView recyclerView;
SearchView realsv;
private AlbumsAdapter adapter;
private ArrayList<Album> albumList;
private ArrayList<Album> test;
private Album album;
public ImageView imga;
public CollapsingToolbarLayout collapsingToolbar;
public AppBarLayout appBarLayout;
ProgressDialog pd;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
realsv=(SearchView)rootView.findViewById(R.id.realsv);
recyclerView = (RecyclerView) rootView.findViewById(R.id.rcv);
//test.addAll(albumList);
//test.clear();
realsv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.i("YES","FIRST STEP"+albumList.size());
newText=newText.toLowerCase();
for(Album al: albumList)
{
String title = al.getName().toLowerCase();
ArrayList<Album> test = new ArrayList<>();
Log.i("CHEK",title);
if(title.contains(newText)){
Log.i("CHEK ok",title+"ok");
test.add(al);
}
}
adapter.setFilter(test);
// adapter.getFilter().filter(newText);
return true;
}
});
initViews();
return rootView;
}
private void initViews(){
pd = new ProgressDialog(getActivity());
pd.setMessage("Fetching Data...");
pd.setCancelable(false);
pd.show();
albumList = new ArrayList<>();
adapter = new AlbumsAdapter(getActivity(), albumList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
loadJSON();
}
private void loadJSON(){
try{
Client Client = new Client();
//this is where it all changes
Hindi apiService = Client.getClient().create(Hindi.class);
Call<AlbumsResponse> call = apiService.getAlbums();
call.enqueue(new Callback<AlbumsResponse>() {
#Override
public void onResponse(Call<AlbumsResponse> call, Response<AlbumsResponse> response) {
ArrayList<Album> items = response.body().getAlbums();
recyclerView.setAdapter(new AlbumsAdapter(getActivity(), items));
recyclerView.smoothScrollToPosition(0);
pd.hide();
}
#Override
public void onFailure(Call<AlbumsResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
// Toast.makeText(MainActivity.this, "Error Fetching Data!", Toast.LENGTH_SHORT).show();
pd.hide();
}
});
}catch (Exception e){
Log.d("Error", e.getMessage());
// Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
This is My adapter Class for Recyclerview
public class AlbumsAdapter extends RecyclerView.Adapter<AlbumsAdapter.MyViewHolder>{
private Context mContext;
private ArrayList<Album> albumList;
//private List<Album> newList;
public AlbumsAdapter(Context mContext, ArrayList<Album> albuList) {
this.mContext = mContext;
this.albumList = albuList;
// this.newList=albuList;
}
#Override
public AlbumsAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.album_card, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final AlbumsAdapter.MyViewHolder viewHolder, int i) {
viewHolder.title.setText(albumList.get(i).getName());
viewHolder.count.setText(albumList.get(i).getLang());
//load album cover using picasso
Picasso.with(mContext)
.load(albumList.get(i).getThumbnail())
.placeholder(R.drawable.load)
.into(viewHolder.thumbnail);
}
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_album, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
public void setFilter(ArrayList<Album> nn){
albumList= new ArrayList<Album>();
for (Album al:nn){
albumList.add(al);
}
notifyDataSetChanged();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_add_favourite:
Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_play_next:
Toast.makeText(mContext, "Play next", Toast.LENGTH_SHORT).show();
return true;
default:
}
return false;
}
}
#Override
public int getItemCount() {
return albumList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
// overflow = (ImageView) view.findViewById(R.id.overflow);
//on item click
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION){
Album clickedDataItem = albumList.get(pos);
Intent intent = new Intent(mContext, Det.class);
intent.putExtra("name", albumList.get(pos).getName());
intent.putExtra("lang", albumList.get(pos).getLang());
intent.putExtra("thumbnail", albumList.get(pos).getThumbnail());
intent.putExtra("scrn",albumList.get(pos).getScrn());
intent.putExtra("ourl",albumList.get(pos).getOurl());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
// Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getName(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
`
This is Model Class Album.java
public class Album {
#SerializedName("name")
#Expose
private String name;
#SerializedName("lang")
#Expose
private String lang;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("scrn")
#Expose
private String scrn;
#SerializedName("ourl")
#Expose
private String ourl;
public Album() {
}
public Album(String name, String lang, String thumbnail, String scrn,
String ourl) {
this.name = name;
this.lang = lang;
this.thumbnail = thumbnail;
this.scrn=scrn;
this.ourl=ourl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getScrn() {
return scrn;
}
public void setScrn(String scrn) {
this.scrn = scrn;
}
public String getOurl() {
return ourl;
}
public void setOurl(String ourl) {
this.ourl = ourl;
}
}
This is the AlbumResponse.java
public class AlbumsResponse {
#SerializedName("Album")
#Expose
private ArrayList<Album> albums;
public ArrayList<Album> getAlbums(){
return albums;
}
public void setAlbums(ArrayList<Album>albums){
this.albums = albums;
}
}
Ok so in your LoadJson method, you populate a new array called items and then populate your adapter with it. So in your adapter your albumList gets populated which is fine. But then in your OnQueryTextChanged method you check for your query string in albumList array, which you have declared in your Home fragment but never initialized. So hence no filter results. assign your items to albumlist and it will work
In your loadJson() method, in onResponse you are creating a new ArrayList to get all albums and not setting that to your global variable albumList.
So you should do this,
ArrayList<Album> items = response.body().getAlbums();
albumList.addAll(items);

How to hide items from recyclerview as I search in a List<>

I am using a recyclerView to show a grid of movie posters. The posters are contained in a List<> along with their respective title and so on.
I implemented a searchView widget and I can successuflly get a List of matching results. But I can't hide the other ones.
As you understand I don't want to delete the irrelevant movies from the adapter or the user would not be able to see them again.
This is the code:
public class SearchUtils {
public static List<String> search(List<Show> list, String keyword){
List<String> results = new ArrayList<>();
for (Show curVal : list){
String curTitle = curVal.getTitle().toLowerCase().trim();
if (curTitle.contains(keyword)){
results.add(curTitle);
}else{
results = new ArrayList<>();
}
}
return results;
}
}
ListFragment.java
public class ListFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Show>> {
private static final String LOG_TAG = "ListFragment";
private static final String ARG_SCOPE = "com.dcs.shows.activity_to_launch";
private static final String BASE_URL = "http://api.themoviedb.org/3";
private TextView tv;
private ProgressBar pb;
private int scope;
private RecyclerView mRecyclerView;
private ShowAdapter mShowAdapter;
private SearchView mSearchView;
public static ListFragment newInstance(int target) {
Bundle args = new Bundle();
args.putInt(ARG_SCOPE, target);
ListFragment fragment = new ListFragment();
fragment.setArguments(args);
return fragment;
}
public ListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scope = getArguments().getInt(ARG_SCOPE);
setHasOptionsMenu(true);
Log.i(LOG_TAG, "onCreate#Scope is: " + scope);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
mShowAdapter = new ShowAdapter(new ArrayList<Show>());
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
GridLayoutManager glm = new GridLayoutManager(getActivity(), 4);
mRecyclerView.setLayoutManager(glm);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(8, getActivity()));
mRecyclerView.setAdapter(mShowAdapter);
mRecyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(glm) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
}
});
pb = (ProgressBar)rootView.findViewById(R.id.progress_view);
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
getLoaderManager().initLoader(1, null, this);
} else {
// display error
pb.setVisibility(View.GONE);
}
return rootView;
}
List<Show> searchList;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
mSearchView = (SearchView) myActionMenuItem.getActionView();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
if(!mSearchView.isIconified()) {
mSearchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(s != null || !s.isEmpty()) {
for(Show movie : mShowAdapter.getList()) {
if(movie.getTitle().toLowerCase().contains(s.toLowerCase())){
mShowAdapter.add(movie);
}
mShowAdapter.notifyDataSetChanged();
}
} else {
mShowAdapter.addItemsToList(searchList, false);
}
return false;
}
});
mSearchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewDetachedFromWindow(View arg0) {
// search was detached/closed
Log.v(LOG_TAG, "Restoring list: " + searchList + " size: " + searchList.size());
mShowAdapter.addItemsToList(searchList, false);
}
#Override
public void onViewAttachedToWindow(View arg0) {
// search was opened
searchList = mShowAdapter.getList();
}
});
}
private class ShowHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView;
public ShowHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.grid_item_image);
mTextView = (TextView) itemView.findViewById(R.id.grid_item_title);
}
}
private class ShowAdapter extends RecyclerView.Adapter<ShowHolder> {
private List<Show> mShows;
public ShowAdapter(List<Show> shows) {
mShows = shows;
}
public void add(Show show){
mShows.add(show);
notifyDataSetChanged();
}
public void addItemsToList(List<Show> newShows, boolean append){
if(append){
mShows.addAll(newShows);
}else {
mShows = newShows;
}
notifyDataSetChanged();
}
public void removeItemsFromList(int index){
mShows.remove(index);
notifyItemRemoved(index);
}
public List<Show> getList(){
return mShows;
}
#Override
public ShowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View rootView = inflater.inflate(R.layout.list_item_row, parent, false);
return new ShowHolder(rootView);
}
#Override
public void onBindViewHolder(ShowHolder holder, int position) {
Show currentShow = mShows.get(position);
holder.mTextView.setText(currentShow.getTitle());
Glide.with(getActivity()).load(currentShow.getImage()).into(holder.mImageView);
}
#Override
public int getItemCount() {
return mShows.size();
}
}
#Override
public Loader<List<Show>> onCreateLoader(int i, Bundle bundle) {
//start the loader with the appropriate uri
//for now it only supports movies+popular
//it will support movies+top, tv+popular, tv+top.
Uri baseUri = Uri.parse(BASE_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendPath("movie");
uriBuilder.appendPath("popular");
uriBuilder.appendQueryParameter("api_key", QueryUtils.API_KEY);
uriBuilder.appendQueryParameter("page", Integer.valueOf(1).toString());
Log.v(LOG_TAG, "onCreateLoader#URL built: " + uriBuilder.toString());
return new ShowLoader(getActivity(), uriBuilder.toString());
}
#Override
public void onLoadFinished(Loader<List<Show>> loader, List<Show> shows) {
// Clear the adapter of previous earthquake data
clearAdapter();
// If there is a valid list of Shows, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (shows != null && !shows.isEmpty()) {
mShowAdapter.addItemsToList(shows, false);
mShowAdapter.notifyDataSetChanged();
}
pb.setVisibility(View.GONE);
}
#Override
public void onLoaderReset(Loader<List<Show>> loader) {
// Loader reset, so we can clear out our existing data.
clearAdapter();
}
private void clearAdapter(){
List<Show> empty = new ArrayList<>();
mShowAdapter.addItemsToList(empty, false);
mShowAdapter.notifyDataSetChanged();
}
Thanks
You can use two lists, one with all the elements (original), and one with just queried elements (this one should use recyclerview adapter). When querying, just select from original list and add them to adapter list, then notify changes. Don't forget to clear adapter list before adding new entries.
Edit: you can try something like this on onQueryTextChange method. Adapt for your own wish.
if(s != null && !s.isEmpty()) {
for(String movie : originalList) {
if(movie.toLowerCase().contains(s.toLowerCase()){
adapter.add(movie);
}
notifyChanges();
}
}
} else { adapter.addAll(originalList); }

Filterable adapter not updates listview

I am trying to create search view with popup list with custom adapter. I have filterable interface and my adapter filters,but the filtered list shows incorrect items. Is it any thing I am missing in my code?
TeamsAdapter.java
public class TeamsAdapter extends BaseAdapter implements Filterable{
private ArrayList<Team> teamsArrayList;
private Context context;
private ArrayList<Team> filteredData;
TeamsFilter mFilter = new TeamsFilter();
public TeamsAdapter(Context context, ArrayList<Team> teamsArrayList) {
this.context = context;
this.teamsArrayList = teamsArrayList;
this.filteredData = teamsArrayList;
}
#Override
public int getCount() {
if(filteredData == null){
return 0;
}
return filteredData.size();
}
#Override
public Team getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return filteredData.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null){
viewHolder = new ViewHolder();
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.team_list_item, parent, false);
viewHolder.teamNameTextView = (TextView) convertView.findViewById(R.id.team_name_textview);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.teamNameTextView.setText(teamsArrayList.get(position).getTeamName());
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
private static class ViewHolder {
private TextView teamNameTextView;
}
private class TeamsFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String filterString = charSequence.toString().toLowerCase();
ArrayList<Team> newList = new ArrayList<>();
FilterResults filterResults = new FilterResults();
if(teamsArrayList == null || teamsArrayList.size() <= 0){
filterResults.values = teamsArrayList;
filterResults.count = teamsArrayList.size();
}
int originalListCount = teamsArrayList.size();
for (int i = 0; i < originalListCount; i++) {
if(teamsArrayList.get(i).getTeamName().contains(filterString)){
newList.add(new Team(teamsArrayList.get(i).getId(),teamsArrayList.get(i).getTeamName()));
}
}
filterResults.values = newList;
filterResults.count = newList.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filteredData = (ArrayList<Team>) filterResults.values;
notifyDataSetChanged();
}
}
}
SpinnerFragment.java
public class SpinnerFragment extends Fragment {
/*private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;*/
private OnFragmentInteractionListener mListener;
private View rootView;
private SearchView teamsSearchView;
private PopupWindow popupMessage;
private ArrayAdapter<String> adapter;
public SpinnerFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment SpinnerFragment.
*/
public static SpinnerFragment newInstance(String param1, String param2) {
SpinnerFragment fragment = new SpinnerFragment();
/*Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);*/
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_spinner, container, false);
TextView textView = new TextView(getActivity());
textView.setText("Testing");
View popup_layout = inflater.inflate(R.layout.popup_layout,container,false);
ListView teamsListView = (ListView) popup_layout.findViewById(R.id.teams_list_view);
ArrayList<Team> teamsArrayList = new ArrayList<Team>();
teamsArrayList.add(new Team(1,"Sharks"));
teamsArrayList.add(new Team(2,"Android"));
teamsArrayList.add(new Team(3,"Google"));
teamsArrayList.add(new Team(4,"Yahoo"));
teamsArrayList.add(new Team(5,"Facebook"));
teamsArrayList.add(new Team(6,"Twitter"));
teamsArrayList.add(new Team(7,"Apple"));
teamsArrayList.add(new Team(8,"Amazon"));
teamsArrayList.add(new Team(9,"Udacity"));
teamsArrayList.add(new Team(10,"Bosch"));
//adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line,sortList);
final TeamsAdapter teamsAdapter = new TeamsAdapter(getActivity(), teamsArrayList);
teamsListView.setAdapter(teamsAdapter);
popupMessage = new PopupWindow(popup_layout, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
//popupMessage.setContentView(textView);
teamsSearchView = (SearchView) rootView.findViewById(R.id.teams_search_view);
teamsSearchView.setQueryHint("Select Team/s");
teamsSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
Toast.makeText(getActivity(), String.valueOf(hasFocus),
Toast.LENGTH_SHORT).show();
}
});
teamsSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(getActivity(), query,
Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
Toast.makeText(getActivity(), "newText=>"+newText,
Toast.LENGTH_SHORT).show();
if(newText.isEmpty()){
popupMessage.dismiss();
return false;
}
//popupMessage.dismiss();
if(!popupMessage.isShowing()){
popupMessage.showAsDropDown(teamsSearchView);
}
teamsAdapter.getFilter().filter(newText);
/*teamsAdapter.getFilter().filter(newText, new Filter.FilterListener() {
#Override
public void onFilterComplete(int i) {
teamsAdapter.notifyDataSetChanged();
}
});*/
return true;
}
});
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction();
}
}
Simply call the adapter's Filter object and pass an empty string *.getFilter().filter("") to force a filter after every operation
Deeply explained here
To Solve this issue:
Use following code in Adapter getView(),
viewHolder.teamNameTextView.setText(getItem(position).getTeamName());
instead of
viewHolder.teamNameTextView.setText(teamsArrayList.get(position).getTeamName());
Also,
if(teamsArrayList.get(i).getTeamName().toLowerCase().contains(filterString))
instead of,
if(teamsArrayList.get(i).getTeamName().contains(filterString))

Categories

Resources