fill a TextView of activity from any class - java

I have a class called AdapterFilaProducto.java , class show certain information in the list.
This is my class
public class AdapterFilaProducto extends BaseAdapter {
protected Activity activity;
protected ArrayList<ItemFilaProducto> items;
protected ItemFilaProducto item;
protected String tipo;
protected Mascaras msk = new Mascaras();
public ImageButton btnImDerecha ;
public ImageButton btnImIzquierda;
public TextView producto;
private Venta contex;
TextView precio;
private BaseDataAdapter db;
private TextView precioCantidad;
public AdapterFilaProducto(Activity activity, ArrayList<ItemFilaProducto> items,String tipo) {
this.activity = activity;
this.items = items;
this.tipo = tipo;
}
public AdapterFilaProducto(Activity activity,Venta contex, ArrayList<ItemFilaProducto> items,String tipo) {
this.activity = activity;
this.items = items;
this.tipo = tipo;
this.contex=contex;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return items.get(position).getId();
}
public String getItemProducto(int position) {
return items.get(position).getProducto();
}
public String getItemCantidad(int position) {
return items.get(position).getCantidad();
}
public String getItemPercio(int position) {
return items.get(position).getPrecio();
}
public EditText getItemEdit(int position) {
return items.get(position).getEditTxt();
}
public View getView(int position, View convertView, ViewGroup parent)
{
db = new BaseDataAdapter(activity);
View vi=convertView;
final ItemFilaProducto item = items.get(position);
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_producto, null);
}
btnImDerecha = (ImageButton) vi.findViewById(R.id.BtnDerechaVenta);
btnImIzquierda = (ImageButton) vi.findViewById(R.id.BtnIzquierdaVenta);
TextView producto = (TextView) vi.findViewById(R.id.txtProductoVenta);
item.precio = (TextView) vi.findViewById(R.id.txtCantidadVenta);
item.edtxt = (EditText) vi.findViewById(R.id.editTxtListVenta);
producto.setText(item.getProducto());
Log.i("Precio",item.montoPrecio);
if(item.cantidad.equalsIgnoreCase("0")){
item.precio .setText(item.Precio);
}else
item.precio .setText(item.montoPrecio);
item.edtxt.setText(""+item.cantidad);
btnImDerecha.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int i = Integer.parseInt(item.edtxt.getText().toString());
i=i+1;
item.edtxt.setText(""+i);
}
});
btnImIzquierda.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int i = Integer.parseInt(item.edtxt.getText().toString());
if(0<i){
i=i-1;
item.edtxt.setText(""+i);
}
}
});
item.edtxt.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
db.open();
Cursor cur = db.obtenerProductosTipo(tipo,item.getIdPro());
if(cur.moveToFirst()){
int precio = cur.getInt(3);
int cantidad = Integer.parseInt(item.edtxt.getText().toString());
int monto = precio*cantidad;
if(0 < monto){
item.setPrecio(msk.mascaraMontoTxt(String.valueOf(monto)));
item.precio .setText(item.getPrecio());
}
db.actualizarProductoMonto(item.getIdPro(),monto);
db.actualizarProductoCantidad(item.getIdPro(),cantidad);
}
cur.close();
int montoTotal = 0;
Cursor curAll = db.obtenerProductosTipo(tipo);
if(curAll.moveToFirst()){
do{
montoTotal = montoTotal + curAll.getInt(5);
Log.e("CANTIDAD", ""+curAll.getInt(5));
}while(curAll.moveToNext());
}
curAll.close();
try{
db.borrarTablaPar("MONTO");
}catch(Exception e){
}
Log.e("MONTO", ""+montoTotal);
DtoParametro dtoParametro = new DtoParametro();
dtoParametro.ID_PAR = "MONTO";
dtoParametro.VALOR = String.valueOf(montoTotal);
Log.i("MONTO",""+String.valueOf(montoTotal));
db.insertarParametro(dtoParametro);
db.close();
contex.mostrarMonto();
}
});
return vi;
}
}
And I need to do is to show in my main Activity is montoTotal. and display it in a total amount in the Textview for my Principal Activity .We tried several methods but none succeeded.
I would appreciate your help, thanks.

Its really hard to follow your code but you should either be able to make this an inner class of your PrincipalActivity and make montoTotal a member variable so that you can access it from where you need or create an instance of this class that retrieves the variable from a function

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

Search an data listview using edittext

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

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

Issues with a tagging system using Autocomplete android

I am trying to implement something similar to facebook's search system, where if a user starts typing in a name it brings autocomplete suggestions based on the letters typed, and with an additional option to search for more results. Each result is an object and not a string, and I have tried adding an extra result for search but every time I click on search or one of the objects a replace text occurs with the object as oppose to the name and I know it is a method of the autocomplete widget. Is there another way to go about it?
Here is my code:
private AutoCompleteTextView sx;
sx = (AutoCompleteTextView) findViewById(R.id.sx);
if(sadapter == null) {
sadapter = new Sadapter(PostActivity.this, usersFound);
sx.setAdapter(sadapter);
}
sx.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (sx.getText().toString().length() <= 3 && sadapter != null) {
usersFound.clear();
sadapter.notifyDataSetChanged();
}
if (sx.getText().toString().length() > 3) {
usersFound.clear();
sadapter.notifyDataSetChanged();
Log.d(Constants.DEBUG, "Changing text " + s);
sxname = s.toString();
testCreate();
sadapter.notifyDataSetChanged();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
sx.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DatabaseUser newAdd = usersFound.get(position);
if(position == searchServerIndex) {
sx.setText(sxname);
usersFound.clear();
sadapter.notifyDataSetChanged();
apiGetPossibleCandidates();
} else {
sx.setText("");
}
}
});
private void testCreate() {
DatabaseUser nuser1 = new DatabaseUser("userid", "pictureid", "Jon");
DatabaseUser nuser2 = new DatabaseUser("userid", "pictureid", "Jonny");
DatabaseUser nuser3 = new DatabaseUser("userid", "pictureid", "Jong");
DatabaseUser nuser4 = new DatabaseUser("userid", "pictureid", "Joan");
DatabaseUser searchServer = new DatabaseUser("SearchId", "pictureid", "Search " + sxname);
usersFound.add(nuser1);
usersFound.add(nuser2);
usersFound.add(nuser3);
usersFound.add(nuser4);
searchServerIndex = usersFound.size();
usersFound.add(searchServer);
if(sadapter != null) {
sadapter.notifyDataSetChanged();
}
}
This is the adapter:
public class Sadapter extends ArrayAdapter<DatabaseUser> {
private Context mContext;
private List<DatabaseUser> usersSearch;
private List<DatabaseUser> usersFiltered;
public Sadapter(Context context, List<DatabaseUser> usersAdded) {
super(context, 0, usersAdded);
mContext = context;
usersSearch = usersAdded;
}
#Override
public int getCount() {
return usersSearch.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.user_autosearch_item, null);
}
//helps for recycling
final ViewHolder holder = new ViewHolder();
holder.userTxt = (TextView) v.findViewById(R.id.userTxt);
v.setTag(holder);
String name = usersSearch.get(position).getName();
holder.userTxt.setText(name);
return v;
}
static class ViewHolder {
TextView userTxt;
}
}
you can override getItem() method in your adapater and return the object of DataBaseUser of particular position from the searchlist.. like
#Override public DatabaseUser getItem(int position) {
return usersSearch.get(position);
}
So from your onClick method you can call this method and it will give you DatabaseUser object from which you can retrive your text. I hope it helps you ..

How to use search function in my custom listview(fetching data from website and display in listview)

I have listview,its getting data from website and displaying in an Listview,I want to use search function,in my listview i am having title and content.I want to search using content alone thats enough.How to use search function for my listview.
It shows problem in this line List newListTwo=new List(); the error is Cannot instantiate the type List
Myactivity.java
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
String selection = myFilter.getText().toString().toLowerCase();
List<Application> newListTwo=new List<Application>();
int textlength = selection.trim().length();
System.err.println("selection" + textlength);
newListTwo.clear();
for (int i = 0; i < items.size(); i++)
{
// -------------- seach according to the content starts with -------------------------
if(items.get(i).getContent().toLowerCase().startsWith(selection))
{
System.err.println("Selection: " + selection);
newListTwo.add(items.get(i));
}
}
//---------------- Again Call your List View ------------------
adapter=new ApplicationAdapter(MainActivity.this, newListTwo);
setListAdapter(adapter);
}
private void setListAdapter(ApplicationAdapter adapter) {
// TODO Auto-generated method stub
}
});
//praycount.setOnClickListener(this);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
For my code how to use the search function,i have my applicaton.java and applicationadapter.java also
Applicationadapter.java
#SuppressLint("NewApi")
public class ApplicationAdapter extends ArrayAdapter<Application> implements
TextToSpeech.OnInitListener{
private List<Application> items;
private LayoutInflater inflator;
private MainActivity activity;
private ProgressDialog dialog;
public TextToSpeech tts;
public ImageButton btnaudioprayer;
public TextView text1;
ArrayAdapter<String> adapter;
public ApplicationAdapter(MainActivity context, List<Application> items){
super(context, R.layout.activity_row, items);
this.items = items;
inflator = LayoutInflater.from(getContext());
activity=context;
}
#Override
public int getCount(){
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
tts = new TextToSpeech(activity, ApplicationAdapter.this);
//View v = convertView;
if ( convertView == null ){
convertView = inflator.inflate(R.layout.activity_row, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text2);
holder.text1 = (TextView) convertView.findViewById(R.id.text1);
holder.count = (TextView) convertView.findViewById(R.id.count);
holder.pray = (Button) convertView.findViewById(R.id.pray);
holder.chk = (CheckBox) convertView.findViewById(R.id.checkbox);
holder.btnaudioprayer = (ImageButton) convertView.findViewById(R.id.btnaudioprayer);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view,
boolean isChecked) {
int getPosition = (Integer) view.getTag();
items.get(getPosition).setSelected(view.isChecked());
}
});
holder.pray.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int getPosition= (Integer)v.getTag();
StringBuffer sb1 = new StringBuffer();
sb1.append("ID :");
sb1.append(Html.fromHtml(""+items.get(getPosition).getId()));
sb1.append("\n");
activity.praydata(items.get(getPosition).getId());
//activity.showAlertView(sb1.toString().trim());
//activity.praydata(Integer.parseInt(sb1.toString().trim()));
}
});
holder.btnaudioprayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
View parent = (View)V.getParent();
ViewHolder vh = (ViewHolder)parent.getTag();
TextView tv = vh.text1;
speakOut(tv.getText().toString());
}
});
Application app = items.get(position);
holder.chk.setTag(position);
holder.pray.setTag(position);
holder.text2.setText(Html.fromHtml(app.getTitle()));
holder.text1.setText(Html.fromHtml(app.getContent()));
holder.count.setText(app.getCount()+"");
holder.chk.setChecked(app.isSelected());
return convertView;
}
static class ViewHolder {
public TextView text2;
public TextView text1;
public TextView count;
public CheckBox chk;
public Button pray;
public ImageButton btnaudioprayer;
private TextToSpeech tts;
}
//return convertView;
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Use addTextChangeListener to show list according to the content:-
searchContentEditText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
selection= searchContentEditText.getText().toString().toLowerCase();
List newListTwo=new ArrayList();
textlength = selection.trim().length();
System.err.println("selection" + textlength);
newListTwo.clear();
for (int i = 0; i < contactList.size(); i++)
{
// -------------- seach according to the content starts with -------------------------
if(firstList.get(i).getContent().toLowerCase().startsWith(selection))
{
System.err.println("Selection: " + selection);
newListTwo.add(firstList.get(i));
}
}
//---------------- Again Call your List View ------------------
adapter=new ContactListAdapter(MyActivity.this, newListTwo);
setListAdapter(adapter);
}
});
You need to implement your MyActivity.java class with TextWatcher.
public class MyActivity extends Activity implements TextWatcher {
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(this);
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Group[] group_array = null;
this.array_sort = new ArrayList<Group>();
try {
if(user != null) {
group_array = this.user.getUser_groups().getData();
}
int textlength = this.search_bar.getText().length();
for(int i=0; i<group_array.length; i++) {
if(textlength <= group_array[i].getGroup_name().length()) {
if(((String) group_array[i].getGroup_name().subSequence(0, textlength))
.equalsIgnoreCase(this.search_bar.getText().toString()))
{
this.array_sort.add(group_array[i]);
}
}
}
if(this.array_sort.size() > 0) {
Group[] groups = new Group[this.array_sort.size()];
FetchGroups.this.group_adapter = new GroupAdapter(FetchGroups.this,R.layout.row_fetch_groups,
android.R.layout.simple_list_item_1, this.array_sort.toArray(groups));
FetchGroups.this.groups_list.setAdapter(group_adapter);
}
} catch(Exception e) {
e.printStackTrace();
}
}

Categories

Resources