Search an data listview using edittext - java

I'm creating a Movie Catalog app using themoviedb API. How can I implement search using EditText?
I have a list view that contains the movie info.
App screenshot:
Now I want to use the EditText to find another movie, and the list view updated. How do I do that?
My loader:
public class MyAsyncTaskLoader extends AsyncTaskLoader<ArrayList<MovieItem>> {
public ArrayList<MovieItem> mData;
public boolean hasResult = false;
public MyAsyncTaskLoader(final Context context) {
super(context);
onContentChanged();
Log.d("INIT ASYNCLOADER","1");
}
#Override
protected void onStartLoading() {
Log.d("Content Changed","1");
if (takeContentChanged())
forceLoad();
else if (hasResult)
deliverResult(mData);
}
#Override
public void deliverResult(final ArrayList<MovieItem> data) {
mData = data;
hasResult = true;
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
if (hasResult) {
onReleaseResources(mData);
mData = null;
hasResult = false;
}
}
public static String Search = "Avengers";
public static String API_KEY = "f00e74c69ff0512cf9e5bf128569f6b5";
#Override
public ArrayList<MovieItem> loadInBackground() {
Log.d("LOAD BG","1");
SyncHttpClient client = new SyncHttpClient();
final ArrayList<MovieItem> movieItemses = new ArrayList<>();
final String url = "https://api.themoviedb.org/3/search/movie?api_key="+API_KEY+"&language=en-US&query="+Search;
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
setUseSynchronousMode(true);
}
#Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
try {
String result = new String(responseBody);
JSONObject responseObject = new JSONObject(result);
JSONArray list = responseObject.getJSONArray("results");
for (int i = 0 ; i < list.length() ; i++){
JSONObject movie = list.getJSONObject(i);
MovieItem movieItems = new MovieItem(movie);
movieItemses.add(movieItems);
}
Log.d("REQUEST SUCCESS","1");
}catch (Exception e){
e.printStackTrace();
Log.d("REQUEST FAILED","1");
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
for (int i = 0 ; i< movieItemses.size() ; i++){
Log.d("Title",movieItemses.get(i).getTitle());
}
Log.d("BEFORE RETURN","1");
return movieItemses;
}
protected void onReleaseResources(ArrayList<MovieItem> data) {
//nothing to do.
}
public ArrayList<MovieItem> getResult() {
return mData;
}
}
My adapter:
public class MovieAdapter extends BaseAdapter {
private ArrayList<MovieItem> mData = new ArrayList<>();
private LayoutInflater mInflater;
private Context context;
Activity activity;
private String urlConfig ;
public MovieAdapter(Context context) {
this.context = context;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(ArrayList<MovieItem> items){
mData = items;
notifyDataSetChanged();
}
public void clearData(){
mData.clear();
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public MovieItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_row_film, null);
holder.textViewuJudul= (TextView)convertView.findViewById(R.id.tv_judul);
holder.textViewDescription = (TextView)convertView.findViewById(R.id.tv_deskripsi);
holder.textViewRate = (TextView)convertView.findViewById(R.id.tv_rate);
holder.imgPoster = (ImageView) convertView.findViewById(R.id.img_poster);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewuJudul.setText(mData.get(position).getTitle());
holder.textViewDescription.setText(mData.get(position).getDescription());
holder.textViewRate .setText(mData.get(position).getRate());
Picasso.with(context).load(mData.get(position).getImgurl()).into(holder.imgPoster);
return convertView;
}
private class ViewHolder {
public TextView textViewuJudul;
public TextView textViewDescription;
public TextView textViewRate;
public ImageView imgPoster;
}}
The item:
public class MovieItem {
public static String POSTER_BASE_URL = "http://image.tmdb.org/t/p/";
private int id;
private String title;
private String description;
private String rate;
private String imgurl;
public MovieItem(JSONObject object){
try {
String title = object.getString("title");
String description = object.getString("overview");
double movieRatet = object.getDouble("vote_average");
String movieRate = new DecimalFormat("#.#").format(movieRatet);
String releaseDate = object.getString("release_date");
String posterUrl = object.getString("poster_path");
posterUrl = POSTER_BASE_URL + "w185" + posterUrl;
description = description.length() > 64 ? description.substring(0,64)+"...":description;
Log.d("movie poster", posterUrl);
Log.d("movie title ", title);
Log.d("movie description ", description);
Log.d("movie release ", releaseDate);
this.title = title;
this.description = description;
this.rate = releaseDate;
this.imgurl = posterUrl;
}catch (Exception e){
e.printStackTrace();
}
}
My MainActivity:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<MovieItem>>
,View.OnClickListener{
ListView listView;
MovieAdapter adapter;
MyAsyncTaskLoader myAsyncTaskLoader;
private TextView edt_cari;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_cari = (TextView) findViewById(R.id.edt_cari);
adapter = new MovieAdapter(this);
adapter.notifyDataSetChanged();
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<ArrayList<MovieItem>> onCreateLoader(int id, Bundle args) {
Log.d("Create Loader", "1");
return new MyAsyncTaskLoader(this);
}
#Override
public void onLoadFinished(Loader<ArrayList<MovieItem>> loader, ArrayList<MovieItem> data) {
Log.d("Load Finish","1");
adapter.setData(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<MovieItem>> loader) {
Log.d("Load Reset","1");
adapter.setData(null);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_cari){
SearchMovieTask searchMovie = new SearchMovieTask();
searchMovie.execute(edt_cari.getText().toString().trim());
}
}
private class SearchMovieTask extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}}

Replace your MovieAdapter to this ...!
public class MovieAdapter extends BaseAdapter implements Filterable {
private ArrayList<MovieItem> mData = new ArrayList<>();
private ArrayList<MovieItem> mSearchData = new ArrayList<>();
private ArrayList<MovieItem> categoryListOne = new ArrayList<>();
private LayoutInflater mInflater;
private Context context;
Activity activity;
ItemFilter mFilter = new ItemFilter();
private String urlConfig;
public MovieAdapter(Context context) {
this.context = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(ArrayList<MovieItem> items) {
mData = items;
mSearchData = items;
notifyDataSetChanged();
}
public void clearData() {
mData.clear();
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public MovieItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_row_film, null);
holder.textViewuJudul = (TextView) convertView.findViewById(R.id.tv_judul);
holder.textViewDescription = (TextView) convertView.findViewById(R.id.tv_deskripsi);
holder.textViewRate = (TextView) convertView.findViewById(R.id.tv_rate);
holder.imgPoster = (ImageView) convertView.findViewById(R.id.img_poster);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewuJudul.setText(mData.get(position).getTitle());
holder.textViewDescription.setText(mData.get(position).getDescription());
holder.textViewRate.setText(mData.get(position).getRate());
Picasso.with(context).load(mData.get(position).getImgurl()).into(holder.imgPoster);
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
public class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase().replace(" ", "");
Log.v("DataAdapter", "constratinst : " + constraint);
FilterResults result = new FilterResults();
if (constraint.toString().length() > 0) {
ArrayList<Sticker> filteredItems =
new ArrayList<>();
for (int i = 0, l = mData.size(); i < l; i++) {
// ArrayList<HashMap<String, String>> p =
// originalList.get(i);
String p = mData.get(i).getName().toLowerCase().replace(" ", "");
if (p.toLowerCase().startsWith(String.valueOf(constraint)))
filteredItems.add(mData.get(i));
// if (p.toLowerCase().contains(constraint))
// filteredItems.add(categoryListSearch.get(i));
}
Log.v("DataAdapter", "not blank");
result.count = filteredItems.size();
result.values = filteredItems;
} else {
synchronized (this) {
result.count = categoryListOne.size();
result.values = categoryListOne;
// result.values = dataList;
// result.count = dataList.size();
}
}
return result;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// users = (List<GraphUser>) results.values;
//filteredData = (ArrayList<String>) results.values;
mData = (ArrayList<MovieItem>) results.values;
notifyDataSetChanged();
// for (int i = 0, l = mData.size(); i < l; i++)
// mSearchData.get(i);
//add(productList.get(i));
notifyDataSetInvalidated();
}
}
private class ViewHolder {
public TextView textViewuJudul;
public TextView textViewDescription;
public TextView textViewRate;
public ImageView imgPoster;
}
}
And your activity set EditText Listener to this..!
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
adapter.getFilter().filter(charSequence.toString());
}
});
i hope it's helpful to you ..!

Implement addTextChangedListener() on your search EditText and as the text changes filter your list data and update MovieAdapter with filtered data.
check this post on how to update custom list adapter

Related

I want to display an image from drawable and combine it with data from json-api into recylerview

I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}

JSONArray data won't show on Fragment

I'm having problems with showing JSONArray data on the Fragment. I am verified my links, Strings etc. But on the Debug console my request showing correct. I am suspecting JSONArray request but i can't find any errors.
Please, help!
D/Request::: 010-8470-0486
010-8472-0964
010-8474-2372
D/Request::: 010-8475-0089
D/Request::: 010-8475-7585
010-8478-0007
D/Request::: 010-8478-0573
010-8479-0311
010-8479-9234
D/Request::: 010-8481-2030
This is my Fragment
public class FragmentDB extends Fragment {
private View v;
private RecyclerView recyclerView;
private String url = "http://www.example.com/api.php";
private List<ModelDB> modelDBList;
public FragmentDB() {
}
#SuppressWarnings("UnnecessaryLocalVariable")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Objects.requireNonNull(getActivity()).checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
return v;
} else {
Intent i10 = new Intent(getActivity(), PermissionActivity.class);
startActivity(i10);
Objects.requireNonNull(getActivity()).finish();
}
v = inflater.inflate(R.layout.frag_db, container, false);
recyclerView = v.findViewById(R.id.rv_db);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager = linearLayoutManager;
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
modelDBList = new ArrayList<>();
DbRvAdapter adapter = new DbRvAdapter(getContext(), modelDBList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setHasFixedSize(true);
Objects.requireNonNull(getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getDBLogs();
return v;
}
#SuppressWarnings({"LogNotTimber", "deprecation"})
private void getDBLogs() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with the response
try {
for ( int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
ModelDB dblist = new ModelDB();
dblist.setPhone_number(obj.getString("phone_number"));
dblist.setInfo1(obj.getString("info1"));
modelDBList.add(dblist);
Log.d("Request:: ", obj.getString("phone_number"));
}
} catch(JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.e("Volley", error.toString());
}
});
RequestQueue rq = Volley.newRequestQueue(Objects.requireNonNull(getActivity()).getApplicationContext());
rq.add(jsonArrayRequest);
}
}
and ModelDB class
public class ModelDB {
public String phone_number;
public String info1;
public ModelDB() {
}
public ModelDB(String phone_number, String info1) {
this.phone_number = phone_number;
this.info1 = info1;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getInfo1() {
return info1;
}
public void setInfo1(String info1) {
this.info1 = info1;
}
}
and adapter class
public class DbRvAdapter extends RecyclerView.Adapter<DbRvAdapter.ViewHolder> {
public static final String KEY_DBPHONENUMBER = "phone_number";
public static final String KEY_DBINFO = "info1";
private Context context;
private List<ModelDB> list;
public DbRvAdapter(Context context, List<ModelDB> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_db, parent, false);
return new ViewHolder(v);
}
#SuppressWarnings("RecyclerView")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final ModelDB modelDB = list.get(position);
holder.textDBP.setText(modelDB.getPhone_number());
holder.textInfo1.setText(String.valueOf(modelDB.getInfo1()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ModelDB modelDB1 = list.get(position);
Intent skipIntent = new Intent(v.getContext(), NumberActivity.class);
skipIntent.putExtra(KEY_DBINFO, modelDB1.getInfo1());
skipIntent.putExtra(KEY_DBPHONENUMBER, modelDB1.getPhone_number());
v.getContext().startActivity(skipIntent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textDBP, textInfo1;
public RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
textDBP = itemView.findViewById(R.id.tv_number);
textInfo1 = itemView.findViewById(R.id.tv_dbinfo);
}
}
}
Sorry for my bad English.
notify you adapter after the for loop body and declare the adapter globally
for ( int i = 0; i < response.length(); i++) {
............
modelDBList.add(dblist);
}
if(dblist != null and dblist.size() > 0){
adapter.notifyDataSetChanged();
}
It looks like you didn't update list of modelDB's inside adapter after the parsing of a network call result.

onPostExecute ArrayList

I write this code for main activity of recycleview with it's adapter and fetching data on it from json data so my question is about the onPostExecute()
I've used before a string so I used .append with it and everything works, now I used an arraylist for the first time so whats the problem with my function
Main Activity:
public class MainActivity extends AppCompatActivity {
private static final ArrayList<MovieItem> NUM_MOVIES = ;
RecyclerViewAdapter mAdapter;
RecyclerView mMoviesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMoviesList = (RecyclerView) findViewById(R.id.rv_movies);
GridLayoutManager LayoutManager = new GridLayoutManager(this, 2);
mMoviesList.setLayoutManager(LayoutManager);
mMoviesList.setHasFixedSize(true);
mAdapter = new RecyclerViewAdapter(NUM_MOVIES);
mMoviesList.setAdapter(mAdapter);
loadMoviesData();
}
private void loadMoviesData() {
new FetchMoviesTask().execute();
}
public class FetchMoviesTask extends AsyncTask<String, Void, ArrayList<MovieItem>> {
#Override
protected ArrayList<MovieItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String movie = params[0];
URL moviesRequestUrl = NetworkUtils.buildUrl(movie);
try {
String jsonMovieResponse = NetworkUtils.getResponseFromHttpUrl(moviesRequestUrl);
ArrayList<MovieItem> simpleJsonMovieData = OpenMovieJsonUtils.getSimpleMovieStringsFromJson(MainActivity.this, jsonMovieResponse);
return simpleJsonMovieData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(ArrayList<MovieItem> movieData) {
if (movieData != null) {
for (MovieItem movie : movieData) {
mMoviesList.append((movie) + "\n\n\n");
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.sort, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.most_popular) {
loadMoviesData();
return true;
}
if (id == R.id.top_rated) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
ArrayList<MovieItem> mMoviesItems;
private Context context;
public RecyclerViewAdapter(ArrayList<MovieItem> MoviesItems) {
mMoviesItems = MoviesItems;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
context = viewGroup.getContext();
int layoutIdForListItem = R.layout.movie_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
RecyclerViewHolder viewHolder = new RecyclerViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.MoviePopularity.setText(String.valueOf(mMoviesItems.get(position).getPopularity()));
Picasso.with(this.context).load(mMoviesItems.get(position).getPhoto()).into(holder.MoviePoster);
holder.MovieName.setText(mMoviesItems.get(position).getName());
}
#Override
public int getItemCount() {
return mMoviesItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView MoviePopularity;
ImageView MoviePoster;
TextView MovieName;
public RecyclerViewHolder(View itemView) {
super(itemView);
MoviePopularity = (TextView)itemView.findViewById(R.id.movie_popularity);
MoviePoster = (ImageView)itemView.findViewById(R.id.iv_item_movie);
MovieName = (TextView)itemView.findViewById(R.id.movie_name);
}
}
}
also about the private static final ArrayList<MovieItem> NUM_MOVIES = ;
when I use int I just used any number but now with arraylist what should I do
This is because you're trying to use a method that did not exist for the class.
In your source code, you define mMoviesList as RecyclerView:
RecyclerView mMoviesList;
Then you try the following:
protected void onPostExecute(ArrayList<MovieItem> movieData) {
if (movieData != null) {
for (MovieItem movie : movieData) {
mMoviesList.append((movie) + "\n\n\n");
}
}
}
There is no append method in RecyclerView

My listview is not displaying its content

Here is the code for MainActivity
How to view listview products please suggest me as soon as possible
public class ProductList extends AppCompatActivity {
public static ArrayList<ItemProductList> values1=new ArrayList<ItemProductList>();
ListView list_productlist;
Context context = this;
public ItenProductAdapter mAdapter;
String category,name1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
list_productlist = (ListView) findViewById(R.id.list_productlist);
category=getIntent().getStringExtra("category");
name1=getIntent().getStringExtra("name");
loadJSON();
mAdapter= new ItenProductAdapter(context,values1);
list_productlist.setAdapter(mAdapter);
}
private void loadJSON() {
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
"http://arshinfosystems.co.in/demo/AoneRubber/productlist.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObject = new JSONObject(response);
JSONArray jsonArray = jObject.getJSONArray("cart");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jbjct = jsonArray.getJSONObject(i);
ItemProductList itemListModel = new ItemProductList();
itemListModel.thickness1 = jbjct.getString("thickness");
itemListModel.id1 = jbjct.getString("id");
itemListModel.price1 = jbjct.getString("price");
itemListModel.category1 = jbjct.getString("category");
itemListModel.name1=jbjct.getString("name");
itemListModel.sr_no=jbjct.getString("sr_no");
values1.add(itemListModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductList.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("category", category);
params.put("name", name1);
return params;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjReq);
}
}
Here is the code for Adapter
How to view listview products please suggest me as soon as possible please guys
public class ItenProductAdapter extends BaseAdapter {
public static ArrayList<ItemProductList> list1;
String idValues = "";
Context context;
public static Integer total;
Bitmap mIcon11 = null;
ViewHolder holder;
public ItenProductAdapter(Context context, ArrayList<ItemProductList> list) {
super();
this.list1 = list;
this.context = context;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
static class ViewHolder {
TextView txt_sr_no;
TextView txt_thickness;
TextView txt_rates;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder=new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.product_list_item, null);
holder.txt_sr_no= (TextView) convertView.findViewById(R.id.txt_sr_no);
holder.txt_thickness= (TextView) convertView.findViewById(R.id.txt_thickness);
holder.txt_rates= (TextView) convertView.findViewById(R.id.txt_rates);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_sr_no.setText(list1.get(position).sr_no+")");
holder.txt_thickness.setText(""+ list1.get(position).thickness1);
holder.txt_rates.setText("RS "+list1.get(position).price1);
return convertView;
}
}
In your code method getCount() returns 0. Change it to
public int getCount() {
return list.size();
}
BTW its better to extend ArrayAdapter.
Your getCount function of your adapter always returns that is has no items
Change this
#Override
public int getCount() {
return 0;
}
to something like this
#Override
public int getCount() {
if (list1 != null) {
return list1.size();
}
return 0;
}
Try This
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
list_productlist = (ListView) findViewById(R.id.list_productlist);
category=getIntent().getStringExtra("category");
name1=getIntent().getStringExtra("name");
loadJSON();
}
Then the onResponse
#Override
public void onResponse(String response) {
try {
JSONObject jObject = new JSONObject(response);
JSONArray jsonArray = jObject.getJSONArray("cart");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jbjct = jsonArray.getJSONObject(i);
ItemProductList itemListModel = new ItemProductList();
itemListModel.thickness1 = jbjct.getString("thickness");
itemListModel.id1 = jbjct.getString("id");
itemListModel.price1 = jbjct.getString("price");
itemListModel.category1 = jbjct.getString("category");
itemListModel.name1=jbjct.getString("name");
itemListModel.sr_no=jbjct.getString("sr_no");
values1.add(itemListModel);
}
//Check if list is empty or not
if(values1.size()>0){
mAdapter= new ItenProductAdapter(context,values1);
list_productlist.setAdapter(mAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try this
#Override
public void onResponse(String response) {
try {
JSONObject jObject = new JSONObject(response);
JSONArray jsonArray = jObject.getJSONArray("cart");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jbjct = jsonArray.getJSONObject(i);
ItemProductList itemListModel = new ItemProductList();
itemListModel.thickness1 = jbjct.getString("thickness");
itemListModel.id1 = jbjct.getString("id");
itemListModel.price1 = jbjct.getString("price");
itemListModel.category1 = jbjct.getString("category");
itemListModel.name1=jbjct.getString("name");
itemListModel.sr_no=jbjct.getString("sr_no");
values1.add(itemListModel);
}
mAdapter.setList(values1);
mAdapter.notifyDataSetChanged();
}
Adapter Class
public class ItenProductAdapter extends BaseAdapter {
public static ArrayList<ItemProductList> list1;
String idValues = "";
Context context;
public static Integer total;
Bitmap mIcon11 = null;
ViewHolder holder;
public ItenProductAdapter(Context context, ArrayList<ItemProductList> list) {
super();
this.list1 = list;
this.context = context;
}
public void setList(ArrayList<ItemProductList> list){
this.list1 = list;
}
#Override
public int getCount() {
return list1.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
static class ViewHolder {
TextView txt_sr_no;
TextView txt_thickness;
TextView txt_rates;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder=new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.product_list_item, null);
holder.txt_sr_no= (TextView) convertView.findViewById(R.id.txt_sr_no);
holder.txt_thickness= (TextView) convertView.findViewById(R.id.txt_thickness);
holder.txt_rates= (TextView) convertView.findViewById(R.id.txt_rates);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_sr_no.setText(list1.get(position).sr_no+")");
holder.txt_thickness.setText(""+ list1.get(position).thickness1);
holder.txt_rates.setText("RS "+list1.get(position).price1);
return convertView;
}
}

How To make RecyclerView handle onclicklistener [duplicate]

This question already has answers here:
RecyclerView onClick
(49 answers)
Closed 7 years ago.
Has anyone using RecyclerView found a way to set an onClickListener to items in the RecyclerView?
this my code:
Pasal_Bab.java
public class Pasal_Bab extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerViewEmptySupport rv;
private List<PasalBabModel> mPBH;
private PasalBabAdapter adapter;
private static ArrayList<PasalBabModel> people;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_pasal, container, false);
rv = (RecyclerViewEmptySupport) view.findViewById(R.id.rv_pasal);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
rv.setLayoutManager(layoutManager);
rv.setEmptyView(view.findViewById(R.id.empty));
rv.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
String[] locales = Locale.getISOCountries();
mPBH = new ArrayList<>();
for (String countryCode : locales) {
Locale obj = new Locale("Pasalxyz", countryCode);
mPBH.add(new PasalBabModel(obj.getDisplayCountry(), obj.getISO3Country()));
}
adapter = new PasalBabAdapter(mPBH);
rv.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
adapter.setFilter(mPBH);
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<PasalBabModel> filteredModelList = filter(mPBH, newText);
adapter.animateTo(filteredModelList);
adapter.setFilter(filteredModelList);
rv.scrollToPosition(0);
return false;
}
private List<PasalBabModel> filter(List<PasalBabModel> models, String query) {
query = query.toLowerCase();
final List<PasalBabModel> filteredModelList = new ArrayList<>();
for (PasalBabModel model : models) {
final String text = model.getpasalbab_p().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
PasalBabAdapter.java
public class PasalBabAdapter extends RecyclerView.Adapter<PasalBabVH> {
private List<PasalBabModel> mPasalBabModel;
public PasalBabAdapter(List<PasalBabModel> mPasalBabModel) {
this.mPasalBabModel = mPasalBabModel;
}
#Override
public void onBindViewHolder(PasalBabVH PasalBabVH, int i) {
final PasalBabModel model = mPasalBabModel.get(i);
PasalBabVH.bind(model);
}
#Override
public PasalBabVH onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.pasalbab_row, viewGroup, false);
return new PasalBabVH(view);
}
public void setFilter(List<PasalBabModel> PasalBabModels) {
mPasalBabModel = new ArrayList<>();
mPasalBabModel.addAll(PasalBabModels);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mPasalBabModel.size();
}
public void animateTo(List<PasalBabModel> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<PasalBabModel> newModels) {
for (int i = mPasalBabModel.size() - 1; i >= 0; i--) {
final PasalBabModel model = mPasalBabModel.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<PasalBabModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final PasalBabModel model = newModels.get(i);
if (!mPasalBabModel.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<PasalBabModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final PasalBabModel model = newModels.get(toPosition);
final int fromPosition = mPasalBabModel.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public PasalBabModel removeItem(int position) {
final PasalBabModel model = mPasalBabModel.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, PasalBabModel model) {
mPasalBabModel.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final PasalBabModel model = mPasalBabModel.remove(fromPosition);
mPasalBabModel.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
}
PasalBabVH.java
public class PasalBabVH extends RecyclerView.ViewHolder {
public TextView p_TextView;
public TextView b_TextView;
public PasalBabVH(View itemView) {
super(itemView);
p_TextView = (TextView) itemView.findViewById(R.id.uud_pasal);
b_TextView = (TextView) itemView.findViewById(R.id.uud_bab);
}
public void bind(PasalBabModel mx) {
p_TextView.setText(mx.getpasalbab_p());
b_TextView.setText(mx.getpasalbab_b());
}
}
PasalBabModel.java
public class PasalBabModel {
String pasalbab_p;
String pasalbab_b;
public PasalBabModel(String pasalbab_p, String pasalbab_b) {
this.pasalbab_p = pasalbab_p;
this.pasalbab_b = pasalbab_b;
}
public String getpasalbab_p() {
return pasalbab_p;
}
public String getpasalbab_b() {
return pasalbab_b;
}
}
please helpme...i'm a beginner :)
Create the adapter like so:
public class CustomAdapter extends RecyclerView.Adapter<Custom.ViewHolder> {
private List<SomeObject> mDataSet;
public OnItemClickListener mItemClickListener;
private Context mContext;
public CustomAdapter(Context context, List<SomeObject> myDataset, OnItemClickListener mItemClickListener) {
this.mDataSet = myDataset;
this.mItemClickListener = mItemClickListener;
this.mContext = context;
}
public void updateData(List<SomeObject> mDataSet) {
this.mDataSet = mDataSet;
notifyDataSetChanged();
}
public void removeItem(int position) {
mDataSet.remove(position);
notifyItemRemoved(position);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final SomeObject obj = mDataSet.get(position);
holder.name.setText(obj.getName());
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView name;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.naam);
v.setOnClickListener(this);
v.setOnLongClickListener(this);
}
#Override
public void onClick(View v) {
// If not long clicked, pass last variable as false.
mItemClickListener.onItemClick(v, getLayoutPosition(), false, mDataSet);
}
#Override
public boolean onLongClick(View v) {
// If long clicked, passed last variable as true.
mItemClickListener.onItemClick(v, getLayoutPosition(), true, mDataSet);
return true;
}
}
public interface OnItemClickListener {
void onItemClick(View view, int position, boolean isLongClick, List<SomeObject> mFilteredList);
}
}
And set the adapter like this:
mAdapter = new CustomAdapter(getActivity(), dataSet, new CustomAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position, boolean isLongClick, List<SomeObject> mDataSet) {
if (isLongClick) {
//Long click
SomeObject obj = mDataSet.get(position);
} else {
//Normal click
SomeObject obj = mDataSet.get(position);
}
}
});
Use interfaces to handle onClicks.
Put this in the adapter:
public interface OnItemClickListener {
void onClickItem(View view, int position);
}
public void SetOnItemClickListener(OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
and then in view holder do this:
public class PasalBabVH extends RecyclerView.ViewHolder {
public TextView p_TextView;
public TextView b_TextView;
public PasalBabVH(View itemView) {
super(itemView);
p_TextView = (TextView) itemView.findViewById(R.id.uud_pasal);
b_TextView = (TextView) itemView.findViewById(R.id.uud_bab);
p_TextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
}
}
});
b_TextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
}
}
});
}
public void bind(PasalBabModel mx) {
p_TextView.setText(mx.getpasalbab_p());
b_TextView.setText(mx.getpasalbab_b());
}
}
In fragment do this:
adapter.SetOnItemClickListener(new PasalBabAdapter.OnItemClickListener() {
#Override
public void onClickItem(View view, int position) {
}});

Categories

Resources