Getting the data from web API in AutoCompleteTextView with custom Adapter - android

I have manage to create a custom adapter and read data from web API but the suggestions are not displayed in the dropdown. I followed the tutorial at
http://makovkastar.github.io/blog/2014/04/12/android-autocompletetextview-with-suggestions-from-a-web-service/
Here is my custom AutoCompleteTextView
public class AutoCompleteDelay extends AutoCompleteTextView {
private static final int MESSAGE_TEXT_CHANGED = 100;
private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750;
private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY;
private ProgressBar mLoadingIndicator;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
AutoCompleteDelay.super.performFiltering((CharSequence) msg.obj, msg.arg1);
}
};
public AutoCompleteDelay(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setLoadingIndicator(ProgressBar progressBar) {
mLoadingIndicator = progressBar;
}
public void setAutoCompleteDelay(int autoCompleteDelay) {
mAutoCompleteDelay = autoCompleteDelay;
}
#Override
protected void performFiltering(CharSequence text, int keyCode) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.VISIBLE);
}
mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay);
}
#Override
public void onFilterComplete(int count) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.GONE);
}
super.onFilterComplete(count);
}
}
This is my custom Adapter
public class SearchAdapter extends BaseAdapter implements Filterable {
private static final int MAX_RESULTS = 10;
private Context mContext;
private List<User> resultList = new ArrayList<User>();
public SearchAdapter(Context context) {
mContext = context;
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public User getItem(int index) {
return resultList.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_results, parent, false);
}
((TextView) convertView.findViewById(R.id.user_name)).setText(getItem(position).getName());
((TextView) convertView.findViewById(R.id.user_phone)).setText(getItem(position).getPhone());
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<User> users = findUsers(mContext, constraint.toString());
// Assign the data to the FilterResults
filterResults.values = users;
filterResults.count = users.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultList = (List<User>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}};
return filter;
}
/**
* Returns a search result for the given book title.
*/
private List<User> findUsers(Context context, String query) {
// GoogleBooksProtocol is a wrapper for the Google Books API
SearchUser request = new SearchUser(context);
return request.sendRequest(query);
}
}
This is xml file for Adapter View
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="18dp"
android:textIsSelectable="false"
android:layout_marginBottom="4dp"
android:textColor="#color/abc_background_cache_hint_selector_material_dark" />
<TextView
android:id="#+id/user_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0000000000"
android:textSize="16dp"
android:textIsSelectable="false"
android:layout_marginBottom="4dp"
android:textColor="#color/switch_thumb_disabled_material_dark" />
</LinearLayout>
This is the xml file where I am using 'AutoCompleteTextView`
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/error_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User already exists"
android:visibility="gone"
android:textStyle="bold"
android:textColor="#color/design_textinput_error_color_light"
android:singleLine="true"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.krazz.futsaladmin.classes.AutoCompleteDelay
android:id="#+id/query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionNext"
android:inputType="textAutoComplete"></com.example.krazz.futsaladmin.classes.AutoCompleteDelay>
</android.support.design.widget.TextInputLayout>
<ProgressBar
android:id="#+id/pb_loading_indicator"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>
This is the method that returns ArrayList<User>
public ArrayList<User> sendRequest(final String query) {
RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();
//mErrorText.setVisibility(View.GONE);
String url = String.format(AppConfig.URL_SEARCH_USERS, query, AppConfig.APP_KEY, 4);
debug.L(url);
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
debug.L(response.toString());
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("results");
if(jsonArray != null){
for(int i=0; i<jsonArray.length(); i++){
JSONObject currentUser = jsonArray.getJSONObject(i);
int id = currentUser.getInt("id");
String name = currentUser.getString("name");
String phone = currentUser.getString("phone");
User users = new User(id, name, phone);
searchArrayList.add(users);
}
}
else{
/*mErrorText.setText("Users not found.");
mErrorText.setVisibility(View.VISIBLE);*/
debug.L("users not found");
}
} catch (JSONException e) {
/*mErrorText.setText(e.getMessage());
mErrorText.setVisibility(View.VISIBLE);*/
debug.L(e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/*mErrorText.setText(R.string.error_try_again);
mErrorText.setVisibility(View.VISIBLE);*/
debug.L(error.toString());
}
});
requestQueue.add(strReq);
return searchArrayList;
}
And finally here is where I am using my AutoCompleteTextView
mQueryInputView = (AutoCompleteDelay) view.findViewById(R.id.query);
mErrorText = (TextView) view.findViewById(R.id.error_text);
mQueryInputView.setThreshold(THRESHOLD);
mQueryInputView.setAdapter(new SearchAdapter(mContext));
mQueryInputView.setLoadingIndicator((ProgressBar) view.findViewById(R.id.pb_loading_indicator));
mQueryInputView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
User book = (User) adapterView.getItemAtPosition(position);
mQueryInputView.setText(book.getPhone());
}
});
There is no error or anything but my dropdown suggestion list is not showing even though API returns the values. What am I doing wrong?

The problem is that you are returning an empty ArrayList !!!
When you add a request to the Volley Que, it wall fulfill your request in another thread and return you the data whenever the server respond. so it would take time.
But you return the array list exactly after adding the request to the Que
requestQueue.add(strReq);
return searchArrayList;
What you should do is:
if(jsonArray != null){
for(int i=0; i<jsonArray.length(); i++){
...
searchArrayList.add(users);
}
// RENEW YOUR ADAPTER HERE OR ASSIGN IT AGAIN TO THE EDITTEXT
mAdapter.notifydataSetChanged();
}
Also try changing the constructor of your SearchAdapter. Once i had a similar problem with a fragment adapter:
private List<User> resultList = new ArrayList<User>();
public SearchAdapter(Context context,List<User> data) {
mContext = context;
resultList = data;
}

Related

I need to open a Pdf file when card view button clicked and each card has its own pdf against

Here is my Orderofday.java where i am getting data from URL and in String proceeding_file i get pdf link. i have shown the data present on every card but could not achieve to open a pdf link on card button clicked.
public class Orderofday extends AppCompatActivity {
private static final String TAG = Orderofday.class.getSimpleName();
private RecyclerView recyclerView;
private OrderList mAdapter;
ProgressDialog progess;
List<OrdersModel> myList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orderofday);
progess = new ProgressDialog(Orderofday.this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new OrderList(myList, Orderofday.this);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
getResult();
}
public void getResult() {
String url = "http://senate.gov.pk/ne/getdata/order_of_day_json.php";
//detect internet and show the data
if (isNetworkStatusAvialable(getApplicationContext())) {
progess.setMessage("Loading data....");
progess.show();
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject mainList = new JSONObject(response);
JSONArray result = mainList.getJSONArray("data");
if (result.length() > 0) {
for (int i = 0; i < result.length(); i++) {
mainList = result.getJSONObject(i);
OrdersModel model = new OrdersModel();
model.title_en = mainList.getString("title_en");
model.YearID = mainList.getString("YearID");
model.session_title_en = mainList.getString("session_title_en");
model.sitting_date = mainList.getString("sitting_date");
model.proceeding_file = mainList.getString("proceeding_file");
myList.add(model);
}
mAdapter.notifyDataSetChanged();
progess.dismiss();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
progess.dismiss();
}
});
Log.d("params", strReq.getUrl() + " and " + strReq.getBodyContentType() + " abd " + strReq.getBodyContentType());
// Adding String request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, TAG);
} else {
Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show();
}
}
//check internet connection
public static boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if (netInfos != null) {
return netInfos.isConnected();
}
}
return false;
}
}
Here is my OrderList.java class where i am setting the text from OderModel.java
public class OrderList extends RecyclerView.Adapter<OrderList.MyViewHolder> {
List<OrdersModel> list;
Context c;
public OrderList(List<OrdersModel> list, Context c) {
this.list = list;
this.c = c;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.orders_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
OrdersModel movie = list.get(position);
holder.name.setText(movie.gettitle_en());
holder.type.setText(movie.getYearID());
holder.session_title.setText((movie.getsession_title_en()));
holder.sitting_date.setText(movie.getsitting_date());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, type , session_title , sitting_date , proceeding_file;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
type = view.findViewById(R.id.type);
session_title = view.findViewById(R.id.session_title);
sitting_date = view.findViewById(R.id.sitting_date);
}
}
}
And here is my OrderModel.java where i made getters and setter
public class OrdersModel {
String title_en;
String YearID;
String session_title_en;
String sitting_date;
String proceeding_file;
public String gettitle_en() {
return title_en;
}
public void settitle_en(String title_en) {
this.title_en = title_en;
}
public String getYearID() {
return YearID;
}
public void setYearID(String YearID) {
this.YearID = YearID;
}
public String getsession_title_en() {
return session_title_en;
}
public void setsession_title_en(String session_title_en) {
this.session_title_en = session_title_en;
}
public String getsitting_date() {
return sitting_date;
}
public void setsitting_date(String session) {
this.sitting_date = sitting_date;
}
public String getproceeding_file() {
return proceeding_file;
}
public void setproceeding_file(String date) {
this.proceeding_file = proceeding_file;
}
String file;
}
Now i need to open a pdf against every card view clicked i got url of pdf in procedding_file (String) but couldn't get it. Kindly help me out to achieve this and here is xml.
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_margin="#dimen/_5sdp"
android:layout_height="wrap_content"
android:padding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
android:textStyle="bold"
android:textSize="20sp"
android:layout_margin="5dp"
android:text="Title_ID"
android:textColor="#android:color/black" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/type"
android:layout_below="#id/name"
android:layout_margin="5dp"
android:textSize="15sp"
android:text="YearID"
android:textColor="#android:color/black" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/session_title"
android:layout_below="#id/type"
android:layout_margin="5dp"
android:textSize="15sp"
android:text="Session Title"
android:textColor="#android:color/black" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sitting_date"
android:layout_below="#id/session_title"
android:layout_margin="5dp"
android:textSize="15sp"
android:text="Date "
android:textColor="#android:color/black" />
<Button
android:id="#+id/view_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sitting_date"
android:layout_alignParentRight="true"
android:text="Click to View Pdf"
android:textColor="#000000"
android:textSize="#dimen/_10sdp">
</Button>
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Above answer is correct. However a better solution and the rightest one is to create an interface for the clicklistenet and implement it in tour activity
Initialize viewButton in ViewHolder.
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, type , session_title , sitting_date , proceeding_file;
public Button viewButton;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
type = view.findViewById(R.id.type);
session_title = view.findViewById(R.id.session_title);
sitting_date = view.findViewById(R.id.sitting_date);
viewButton = view.findViewById(R.id.view_button);
}
}
Then set onClickListener on viewButton and openPdf
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
OrdersModel movie = list.get(position);
holder.name.setText(movie.gettitle_en());
holder.type.setText(movie.getYearID());
holder.session_title.setText((movie.getsession_title_en()));
holder.sitting_date.setText(movie.getsitting_date());
holder.viewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openPdf(movie.getproceeding_file())
}
});
}
Suggestion: You should move your PdfViewer in another activity and redirect user to that activity when click viewButton.
initialise view_pdf button in MyViewHolder class. like others.
parse proceeding file like others ~ movie.getproceeding_file()
under the onBindViewHolder put below snippet of code:
holder.proceeding_file.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pdf_url = movie.getproceeding_file();
// do not forget to concate preceding url of the pdf
Webview webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(pdf_url);
}
});

when i click recylerview text to go another activity then that activity won't open and gave some binding error

did not start activity and give data binding error
useradapter
public class useradapter extends RecyclerView.Adapter<useradapter.CustomView> {
String nn = "m";
List<allusermodel> list1;
private Context context;
private LayoutInflater layoutInflater;
public useradapter(Context context, List<allusermodel> list1) {
Log.e("reached1", nn);
this.context = context;
this.list1 = list1;
}
#Override
public useradapter.CustomView onCreateViewHolder(final ViewGroup parent, final int viewType) {
Log.e("reached2", nn);
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
final Entrys newsBinding = Entrys.inflate(layoutInflater, parent, false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView(newsBinding);
}
#Override
public void onBindViewHolder(useradapter.CustomView holder,int position) {
Log.e("reached3", nn);
// News news = newsList.get(position);
// holder.desc.setText(news.getDesc());
allusermodel newsModel1 = list1.get(position);
// Log.e("list", String.valueOf(list1));
Log.e("nameeeee",newsModel1.getAll_user());
// Log.e("position", String.valueOf(position));
//Log.e("names",newsModel1.getAll_user());
holder.bind(newsModel1);
}
#Override
public int getItemCount() {
return list1.size();
}
public class CustomView extends RecyclerView.ViewHolder {
private Entrys newsBinding;
// public TextView title;
//TextView title, desc;
public CustomView(Entrys newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
Log.e("reached4", nn);
// title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
newsBinding.setRecyclerclick(new Presenters2() {
#Override
public void onclickListener() {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
allusermodel clickedDataItem = list1.get(pos);
Intent intent = new Intent(context, messagelist.class);
intent.putExtra("clickid", clickedDataItem.getId());
context.startActivity(intent);
}
}
});
}
public void bind(allusermodel newsModel1)
{
Log.e("reached5", String.valueOf(newsModel1));
//String j = newsModel1.getAll_user();
// Log.e("bind",nn);
this.newsBinding.setAlluserentry(newsModel1);
}
public Entrys getNewsBinding() {
Log.e("reached6", nn);
return newsBinding;
}
}
}
messagelist
public class messagelist extends AppCompatActivity {
private RecyclerView recyclerView;
private ActivityMainBinding activityMainBinding1;
private Postmessagemodel postmessagemodel;
private messageadapter customAdapter;
private messagelist_datamanager dataManger;
private postmessage_datamanager postmessage_datamanager;
private List<messagemodel> newsList;
String tokens;
String sendmsg;
private int toid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_messagelist);
toid=getIntent().getExtras().getInt("clickid");
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
tokens = pref.getString("sherdtoken", "");
Log.e("token", tokens);
activityMainBinding1 = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
postmessagemodel = new Postmessagemodel();
postmessage_datamanager = new postmessage_datamanager(this);
//activityMainBinding1.setPostmsg(postmessagemodel);
/* activityMainBinding1.setPostbtn(new Post() {
#Override
public void onclick() {
postmessage();
}
});*/
sendmsg = postmessagemodel.getMSG();
dataManger = new messagelist_datamanager(this);
recyclerView = (RecyclerView) findViewById(R.id.recycle1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
newsList = new ArrayList<>();
customAdapter = new messageadapter(this, newsList);
recyclerView.setAdapter(customAdapter);
getmessage();
postmessage();
}
public void getmessage()
{
dataManger.sendVolleyRequest2(tokens,toid,messagelist.this, new messagelist_datavalue() {
#Override
public void setJsonDataResponse(JSONArray response) {
messagemodel userModel = new messagemodel();
newsList = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
// Log.e("final", String.valueOf(i));
userModel.setFromUserId(jsonObject.getInt("fromUserId"));
userModel.setMessage(jsonObject.getString("message"));
userModel.setToUserId(jsonObject.getInt("toUserId"));
newsList.add(userModel);
}
} catch (JSONException jsonDataResponse) {
Log.e("error", String.valueOf(jsonDataResponse));
}
customAdapter.notifyDataSetChanged();
}
#Override
public void setVolleyError(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
}
});
}
private void postmessage() {
postmessage_datamanager.sendVolleyRequest3(sendmsg,toid,tokens,messagelist.this,new postmessage_datavalue() {
#Override
public void setJsonDataResponse(JSONObject response) {
try {
Log.e("success",sendmsg);
} catch (Exception e) {
Log.e("error", e.toString());
}
}
#Override
public void setVolleyError(VolleyError volleyError) {
}
});
}
}
messagelist.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout">
<data>
<variable
name="postmsg"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.Postmessagemodel"/>
<variable
name="postbtn"
type="com.example.mayurpancholi.chat_mvvm.interfaces.Post"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mayurpancholi.chat_mvvm.messagelist">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycle1"
android:scrollbars="vertical"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="80dp">
</android.support.v7.widget.RecyclerView>
<EditText
android:id="#+id/post_text"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="13dp"
android:text="#={postmsg.MSG}"
android:layout_marginLeft="9dp"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="#+id/post_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/post_text"
android:layout_alignParentEnd="true"
android:layout_marginBottom="7dp"
android:layout_marginRight="5dp"
android:background="#color/colorPrimary"
android:onClick="#{()->postbtn.onclick()}"
android:text="post" />
</RelativeLayout>
</layout>
innerlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data class ="MessageBinding">
<variable
name="message_list"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.messagemodel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/main_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="10dp"
android:text="#{message_list.message}"
android:textSize="17dp" />
</LinearLayout>
</layout>
messagelistadapter
public class messageadapter extends RecyclerView.Adapter<messageadapter.CustomView1> {
List<messagemodel> list;
private Context context;
private LayoutInflater layoutInflater;
public messageadapter(Context context,List<messagemodel> list)
{
this.context =context;
this.list = list;
}
public messageadapter() {
}
#Override
public messageadapter.CustomView1 onCreateViewHolder(ViewGroup parent, int viewType) {
if(layoutInflater == null)
{
layoutInflater = LayoutInflater.from(parent.getContext());
}
final MessageBinding newsBinding = MessageBinding.inflate(layoutInflater,parent,false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView1(newsBinding);
}
#Override
public void onBindViewHolder(messageadapter.CustomView1 holder, int position) {
messagemodel newsModel = list.get(position);
holder.bind(newsModel);
}
#Override
public int getItemCount() {
return list.size();
}
public class CustomView1 extends RecyclerView.ViewHolder {
private MessageBinding newsBinding;
// TextView title, desc;
public CustomView1(MessageBinding newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
//title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
}
public void bind(messagemodel newsModel1)
{
// this.newsBinding.setMessage_list(newsModel1);
}
public MessageBinding getNewsBinding()
{
return newsBinding;
}
}
}
when i click the recyclerview text it open messagelist but messagelist won't open and give error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mayurpancholi.chat_mvvm, PID: 21181
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mayurpancholi.chat_mvvm/com.example.mayurpancholi.chat_mvvm.messagelist}: java.lang.ClassCastException: com.example.mayurpancholi.chat_mvvm.databinding.ActivityMessagelistBinding cannot be cast to com.example.mayurpancholi.chat_mvvm.databinding.ActivityMainBinding
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
I think the error is self explanatory. As per your flow I can see you want to bind the messagelist actity layout with the Data binding of of MainActity class for which you might have layout as "activity_main.xml". For, As your messagelist activity binding layout name is "activity_messagelist.xml" so the generated binding class name will be "ActivityMessagelistBinding". Therefore, as per the logic of databinding the layout will bind with ActivityMessagelistBinding instead of ActivityMainBinding. So as a conclusion, you change the statement
private ActivityMainBinding activityMainBinding1;
activityMainBinding1 = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
to
private ActivityMessagelistBinding activityMessagelistBinding;
activityMessagelistBinding = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
Hope it should work.

Add personal locations to Google Placeautocomplete list

Is there a way to pin an address to the top of a placeautocomplete search for an android app?
http://jsfiddle.net/v9rt3t2y/
This example is in JS/HTML, but I couldn't find anything for native android studio.
Anyway you can use customized AutoCompleteTextView like in this article. You should add your custom place name in protected void publishResults(CharSequence constraint, FilterResults results) just after filling places list from results.values; from Task<AutocompletePredictionBufferResponse>.
So, for custom place name "-> Custom place <-" with MainActivity.java like:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = MainActivity.class.getSimpleName();
private GoogleMap mGoogleMap;
private SupportMapFragment mMapSupportedFragment;
private AutoCompleteTextView mPlaceAutoCompleteTextView;
private PlacesAdapter mPlacesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlacesAdapter = new PlacesAdapter(this);
mPlaceAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.place_autocomplete);
mPlaceAutoCompleteTextView.setThreshold(1);
mPlaceAutoCompleteTextView.setAdapter(mPlacesAdapter);
mMapSupportedFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
mMapSupportedFragment.getMapAsync(MainActivity.this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
}
class PlacesAdapter extends ArrayAdapter {
Context context;
List<String> placesList = new ArrayList<>();
GeoDataClient geoDataClient;
PlacesAdapter.PlacesAutoCompleteFilter filter = new PlacesAdapter.PlacesAutoCompleteFilter();
public PlacesAdapter(Context context) {
super(context, android.R.layout.simple_dropdown_item_1line,
new ArrayList<Place>());
this.context = context;
geoDataClient = Places.getGeoDataClient(context, null);
}
#Override
public int getCount() {
return placesList.size();
}
#Override
public String getItem(int position) {
return placesList.get(position);
}
#Override
public Filter getFilter() {
return filter;
}
#Override
public View getView(int position, View view, #NonNull ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(parent.getContext())
.inflate(android.R.layout.simple_dropdown_item_1line,
parent, false);
}
TextView textOne = view.findViewById(android.R.id.text1);
textOne.setText(placesList.get(position));
return view;
}
class PlacesAutoCompleteFilter extends Filter {
private Object lock = new Object();
private Object lockTwo = new Object();
private boolean placeResults = false;
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
placeResults = false;
final List<String> predictedPlacesList = new ArrayList<>();
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
results.values = new ArrayList<Place>();
results.count = 0;
}
} else {
final String searchStrLowerCase = prefix.toString().toLowerCase();
Task<AutocompletePredictionBufferResponse> task
= getAutoCompletePlaces(searchStrLowerCase);
task.addOnCompleteListener(new OnCompleteListener<AutocompletePredictionBufferResponse>() {
#Override
public void onComplete(#NonNull Task<AutocompletePredictionBufferResponse> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Auto complete prediction successful");
AutocompletePredictionBufferResponse predictions = task.getResult();
for (AutocompletePrediction prediction : predictions) {
predictedPlacesList.add((prediction.getFullText(null)).toString());
}
predictions.release();
} else {
Log.d(TAG, "Auto complete prediction unsuccessful");
}
placeResults = true;
synchronized (lockTwo) {
lockTwo.notifyAll();
}
}
});
while (!placeResults) {
synchronized (lockTwo) {
try {
lockTwo.wait();
} catch (InterruptedException e) {
}
}
}
results.values = predictedPlacesList;
results.count = predictedPlacesList.size();
Log.d(TAG, "Autocomplete predictions size after wait" + results.count);
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.values != null) {
placesList = (ArrayList<String>) results.values;
} else {
placesList = null;
}
// add your custom place here:
placesList.add(0, "-> Custom place <-");
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
private Task<AutocompletePredictionBufferResponse> getAutoCompletePlaces(String query) {
AutocompleteFilter.Builder filterBuilder = new AutocompleteFilter.Builder();
Task<AutocompletePredictionBufferResponse> results =
geoDataClient.getAutocompletePredictions(query, null,
filterBuilder.build());
return results;
}
}
}
}
and activity_main.xml (NB! according to Usage Limits:
If your app uses the autocomplete service programmatically, your UI
must either display a 'Powered by Google' attribution, or appear
within a Google-branded map.
) like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="<YOUR_PACKAGE_NAME>.MainActivity">
<fragment class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<AutoCompleteTextView android:id="#+id/place_autocomplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/background_light"
android:layout_margin="16dp"
android:padding="8dp"
android:inputType="text"
android:imeOptions="actionNext"
android:textSize="16sp"
android:hint="Type place name here" />
</RelativeLayout>
when you enter letter "a" to text field you should get something like that:
And don't forget to activate Places SDK on Google Cloud Platform Console.

Infinitive RecyclerView doesn't work for me

I know that this question was asked many times before, but i'm confused why sometimes the data is loaded and sometimes data isn't loaded once i get to the end of list. Also when i go fast scrolling through the list, and the new data has been loaded, but immediately it returns me to the first item in list and remove all new loaded items from the next page from server. So that is the second problem and the third problem is that when i load items using SwipeRefreshLayout, i'm also not getting new items when i reach the end of the list.
I have implemented this in my project: https://gist.github.com/ssinss/e06f12ef66c51252563e
list.setLayoutManager(manager);
list.setEmptyView(emptyView);
list.setItemAnimator(new DefaultItemAnimator());
list.setAdapter(mAdapter);
loadJokes(1);
list.addOnScrollListener(new EndlessRecyclerOnScrollListener(manager) {
#Override
public void onLoadMore(final int current_page) {
loadMoreJokes(current_page);
}
});
Here is the method where i'm loading more items from server:
private void loadMoreJokes(int current_page) {
StringRequest request = new StringRequest(Request.Method.GET, AppConfig.URL_GET_ALL_JOKES + current_page,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject object = new JSONObject(response);
boolean error = object.getBoolean("error");
JSONArray jokes = object.getJSONArray("jokes");
if (!error) {
for (int i = 0; i < jokes.length(); i++) {
JSONObject object1 = jokes.getJSONObject(i);
Joke joke = new Joke();
joke.setId(object1.optInt("id"));
joke.setLikes(object1.optInt("likes"));
joke.setComments(object1.optInt("comments"));
joke.setJoke(object1.optString("joke"));
joke.setCreatedAt(object1.optString("created_at"));
joke.setName(object1.optString("user_name"));
joke.setImagePath(object1.optString("image_path"));
joke.setFacebookUserId(object1.optString("facebook_user_id"));
joke.setCategory(object1.optString("category"));
mJokes.add(joke);
}
menu.showMenu(true);
}
// Notify adapter that data has changed
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(request);
}
And here is the method where i'm loading first visible items when someone launch the app:
private void loadJokes(int page) {
pDialog.setMessage("Loading..");
showDialog();
StringRequest request = new StringRequest(Request.Method.GET, AppConfig.URL_GET_ALL_JOKES + page,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mJokes.clear();
hideDialog();
try {
JSONObject object = new JSONObject(response);
boolean error = object.getBoolean("error");
JSONArray jokes = object.getJSONArray("jokes");
if (!error) {
for (int i = 0; i < jokes.length(); i++) {
JSONObject object1 = jokes.getJSONObject(i);
Joke joke = new Joke();
joke.setId(object1.optInt("id"));
joke.setLikes(object1.optInt("likes"));
joke.setComments(object1.optInt("comments"));
joke.setJoke(object1.optString("joke"));
joke.setCreatedAt(object1.optString("created_at"));
joke.setName(object1.optString("user_name"));
joke.setImagePath(object1.optString("image_path"));
joke.setFacebookUserId(object1.optString("facebook_user_id"));
joke.setCategory(object1.optString("category"));
mJokes.add(joke);
}
menu.showMenu(true);
}
// Notify adapter that data has changed
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
menu.showMenu(true);
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(request);
}
And this is onRefresh() method:
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
refreshItems();
}
}, 5000);
}
private void refreshItems() {
loadJokes(1);
mSwipeRefreshLayout.setRefreshing(false);
}
If i need to post more code, let me know. I really need to solve this problem as soon as i can. So again, the problems are the following:
When fast scrolling through the list, new items are being loaded, but immediately after that it returns me to the beginning of the list and when i go to the end of list again, load more doesn't respond.
After refreshing the list with SwipRefreshLayout, also scrolling doesn't respond at the end.
Note: The scrolling and loading new items is working only if i go slowly through the list and if i didn't swipe to refresh list.
EDIT:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_jokes, container, false);
mContext = getActivity();
mView = (CoordinatorLayout) view.findViewById(R.id.coordinatorLayout);
TextView tvEmptyText = (TextView) view.findViewById(R.id.tv_empty);
ImageView ivSignal = (ImageView) view.findViewById(R.id.iv_signal);
if (!ConnectionDetector.getInstance(getActivity()).isOnline() && mAdapter == null) {
tvEmptyText.setVisibility(View.VISIBLE);
ivSignal.setVisibility(View.VISIBLE);
showNoInternetSnackbar();
}
// INITIALIZE RECYCLER VIEW
EmptyRecyclerView list = (EmptyRecyclerView) view.findViewById(R.id.list);
mJokes = new ArrayList<>();
mAdapter = new RecyclerJokesAdapter(getActivity(), mJokes, JokesFragment.this, null);
// Progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
showDialog();
View emptyView = inflater.inflate(R.layout.layout_empty_view, container, false);
FloatingActionButton fab1 = (FloatingActionButton) view.findViewById(R.id.fab_funny);
FloatingActionButton fab2 = (FloatingActionButton) view.findViewById(R.id.fab_good_morning);
FloatingActionButton fab3 = (FloatingActionButton) view.findViewById(R.id.fab_good_night);
FloatingActionButton fab4 = (FloatingActionButton) view.findViewById(R.id.fab_all);
menu = (FloatingActionMenu) view.findViewById(R.id.menu_sort_jokes);
fab1.setOnClickListener(this);
fab2.setOnClickListener(this);
fab3.setOnClickListener(this);
fab4.setOnClickListener(this);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(
R.color.refresh_progress_1,
R.color.refresh_progress_2,
R.color.refresh_progress_3);
LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
list.setLayoutManager(manager);
list.setEmptyView(emptyView);
list.setItemAnimator(new DefaultItemAnimator());
list.setAdapter(mAdapter);
if (ConnectionDetector.getInstance(mContext).isOnline()) {
loadJokes(1);
} else {
showNoInternetSnackbar();
hideDialog();
}
list.addOnScrollListener(new EndlessRecyclerOnScrollListener(manager) {
#Override
public void onLoadMore(final int current_page) {
loadMoreJokes(current_page);
}
});
return view;
}
In onCreate method initialize your adapter, recyclerView and List
List<MyObject> myList = new ArrayList<>();
recyclerViewAdapter = new RecyclerViewAdapter(context, myList)
myRecyclerView.setAdapter(recyclerViewAdapter);
Now, whenever you load data. add the data to your myList and call notifyDataSetChange on your adpater
myList.add(data);
recyclerViewAdapter.notifyDataSetChange();
Use this wrapper class
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import java.util.List;
public abstract class RecyclerWrapperAdapter<E> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected Context context;
protected List<E> objects;
public void setContext(Context context) {
this.context = context;
}
public void setObjects(List<E> objects) {
this.objects = objects;
notifyDataSetChanged();
}
public void add(#NonNull E object) {
objects.add(object);
notifyDataSetChanged();
}
public void add(int position, #NonNull E object) {
if (position < objects.size() && position >= 0) {
objects.add(position, object);
notifyItemChanged(position);
notifyDataSetChanged();
} else if (position >= objects.size()) {
objects.add(object);
notifyDataSetChanged();
}
}
public void set(int position, #NonNull E object) {
if (position < objects.size() && position >= 0) {
objects.set(position, object);
notifyItemChanged(position);
} else if (position >= objects.size()) {
objects.add(object);
notifyDataSetChanged();
}
}
public void remove(#NonNull E object) {
objects.remove(object);
notifyDataSetChanged();
}
public void remove(int position) {
if (position >=0 && position < objects.size()) {
objects.remove(position);
notifyDataSetChanged();
}
}
public void removeAll() {
objects.clear();
notifyDataSetChanged();
}
public E getItem(int position) {
return objects.get(position);
}
#Override
public int getItemCount() {
return objects.size();
}
}
Well I have done this way:
MainActivity .java
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, onRecyclerViewListener {
private RecyclerView mRecyclerView;
private TextView tvEmptyView;
private LinearLayoutManager mLayoutManager;
private List<Object> studentList;
protected Handler handler;
private int count = 0;
private SwipeRefreshLayout swipeRefreshLayout;
private MyRecycleAdapter myRecycleAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.blue, R.color.purple, R.color.green, R.color.orange);
tvEmptyView = (TextView) findViewById(R.id.empty_view);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
studentList = new ArrayList<Object>();
handler = new Handler();
loadData();
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
myRecycleAdapter = new MyRecycleAdapter(mRecyclerView, studentList, R.layout.list_row, R.layout.progressbar_item, this);
myRecycleAdapter.setLoadMoreEnable(true);
myRecycleAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
count++;
if (count == 4) {
count = 0;
myRecycleAdapter.setLoadMoreEnable(false);
} else {
myRecycleAdapter.setLoadMoreEnable(true);
}
//add null , so the adapter will check view_type and show progress bar at bottom
studentList.add(null);
myRecycleAdapter.notifyItemInserted(studentList.size() - 1);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
studentList.remove(studentList.size() - 1);
myRecycleAdapter.notifyItemRemoved(studentList.size());
//add items one by one
int start = studentList.size();
int end = start + 20;
for (int i = start + 1; i <= end; i++) {
studentList.add(new Student("Student " + i, "AndroidStudent" + i + "#gmail.com"));
myRecycleAdapter.notifyItemInserted(studentList.size());
}
myRecycleAdapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
}, 1000);
}
});
ItemViewHolderNew.setRecyclerListener(this);
mRecyclerView.setAdapter(myRecycleAdapter);
if (studentList.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
tvEmptyView.setVisibility(View.VISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
tvEmptyView.setVisibility(View.GONE);
}
}
private void loadData() {
for (int i = 1; i <= 20; i++) {
studentList.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
},5000);
}
#Override
public void onBindView(View view, final ItemViewHolderNew itemViewHolder) {
itemViewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
itemViewHolder.tvEmailId = (TextView) view.findViewById(R.id.tvEmailId);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, Object object, ItemViewHolderNew itemViewHolder) {
Student studentObj = (Student)object;
itemViewHolder.tvName.setText(studentObj.getName());
itemViewHolder.tvEmailId.setText(studentObj.getEmailId());
itemViewHolder.student= studentObj;
}
#Override
public void setClickListener(View view, ItemViewHolderNew itemViewHolder) {
Toast.makeText(view.getContext(), "OnClick :" + itemViewHolder.student.getName() + " \n " + itemViewHolder.student.getEmailId(), Toast.LENGTH_SHORT).show();
}
public static class ItemViewHolderNew extends RecyclerView.ViewHolder{
public TextView tvName, tvEmailId;
public Student student;
private static onRecyclerViewListener mListener;
public static void setRecyclerListener(onRecyclerViewListener listener){
mListener = listener;
}
public ItemViewHolderNew(View itemView) {
super(itemView);
mListener.onBindView(itemView, this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setClick(v);
}
});
}
private void setClick(View v) {
mListener.setClickListener(v, this);
}
}
}
Add OnLoadMoreListener.java interface
public interface OnLoadMoreListener {
void onLoadMore();
}
Add Student.java as Model class
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String emailId;
public Student(String name, String emailId) {
this.name = name;
this.emailId = emailId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
<TextView
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="No Records Here !"
android:visibility="gone" />
</RelativeLayout>
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:padding="5dp"
android:background="?android:selectableItemBackground">
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="18sp" />
<TextView
android:id="#+id/tvEmailId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvName"
android:layout_margin="5dp"
android:text="Email Id"
android:textColor="#android:color/black"
android:textSize="12sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="18sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvName"
android:layout_margin="5dp"
android:text="Email Id"
android:textColor="#android:color/black"
android:textSize="12sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
progressbar_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content" />
</LinearLayout>
Working fine with Endless, swipe to refresh, load more RecyclerView.
Hope this would help you.
Volley RequestQueue uses a thread pool for network requests.
/** Number of network request dispatcher threads to start. */
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
Obviously, when you do fast scrolling through the list multiple requests are generated in quick succession.
There is a possibility that the responses are received asynchronously / out of sequence. Also, its possible that the "No more data" responses / error responses etc arrive before the responses with next page of data, which may lead to unexpected behaviour by your app.
Specially watch out for how this would effect your mJokes ArrayList member variable.

Pass arraylists from fragment to root activity

I am building a order receiving app for waiter in which half page is activity layout which contains listview and half is viewpager which contains json arraylist in fragment. I want to add the menu data from fragment when clicked on + button with number of quantity to be add on root activity's listview
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="140dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
app:layout_collapseMode="parallax"
android:background="#mipmap/bgactionbar">
<ImageView
android:id="#+id/logo"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginLeft="30dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:background="#mipmap/logoapp"
/>
<ImageView
android:id="#+id/triangle"
android:layout_width="280dp"
android:layout_height="100dp"
android:layout_toRightOf="#+id/logo"
android:background="#mipmap/caley"
/>
<RelativeLayout
android:id="#+id/searchLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/triangle"
android:background="#F3EEE8"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#android:drawable/ic_menu_search"
android:layout_toRightOf="#+id/search_menu"
/>
<EditText
android:id="#+id/search_menu"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="Search Menu..."
android:textColorHint="#color/tab_text"
android:textColor="#color/tab_text"
android:background="#android:color/transparent"
android:layout_alignParentLeft="true"
android:inputType="textVisiblePassword"/>
</RelativeLayout>
<ImageView
android:id="#+id/coffee"
android:layout_width="110dp"
android:layout_height="140dp"
android:layout_toRightOf="#+id/searchLayout"
android:background="#mipmap/coffee"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
android:background="#mipmap/background"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
</FrameLayout>
<RelativeLayout
android:id="#+id/content"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:background="#mipmap/background"
android:layout_below="#id/My_Container_1_ID">
<TextView
android:id="#+id/txtorder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Order"
android:textStyle="bold"
android:textColor="#color/tab_text"
android:textSize="20sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/orderlist"
android:layout_width="340dp"
android:layout_height="match_parent"
android:layout_above="#+id/submit_order"
android:layout_below="#+id/txtorder"
android:background="#mipmap/background"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<Button
android:id="#+id/submit_order"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/orderlist"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/orderlist"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="#EE6426"
android:textColor="#android:color/white"
android:text="Submit" />
</RelativeLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_below="#+id/My_Container_1_ID"
android:layout_toRightOf="#+id/content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
public class Menu extends AppCompatActivity implements Coffee.OnMenuInteractionListener {
// private ArrayList<MenuDataModel> allOrders;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ListView listView;
RecyclerView recyclerView;
RecyclerAdapter adapter;
// MenuTabAdapter adapter;
// ArrayList<MenuDataModel> allOrders;
private List<MenuDataModel> allOrders = new ArrayList<MenuDataModel>();
// private List<String> orderList = new ArrayList<>();
private String Quantity, Name;
EditText count, inputSearch;
TextView order;
String searchValue;
private ArrayList<String> stringArrayList;
CollapsingToolbarLayout collapsingToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
collapsingToolbar= (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
// collapsingToolbar.setTitle(getString(R.string.app_name));
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// listView = (ListView) findViewById(R.id.orderlist);
// adapter = new MenuTabAdapter(this, allOrders);
// listView.setAdapter(adapter);
TextView orddd = (TextView) findViewById(R.id.txtorder);
inputSearch = (EditText) findViewById(R.id.search_menu);
// inputSearch.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// collapsingToolbar.setVisibility(View.GONE);
//
// }
// });
// recyclerView = (RecyclerView) findViewById(R.id.orderlist);
// recyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(layoutManager);
//
// adapter = new RecyclerAdapter(this, allOrders);
// recyclerView.setAdapter(adapter);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Coffee(), "Coffee");
adapter.addFragment(new Coffee(), "BreakFast");
adapter.addFragment(new Coffee(), "Beverage");
viewPager.setAdapter(adapter);
}
#Override
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList) {
allOrders = menuList;
}
#Override
public void onMenuListItemClick(int position) {
//musicService.setSong(position);
MenuDataModel menuorder = allOrders.get(position);
// menuorder.setName(menuorder.getName());
// menuorder.setName(allOrders);
allOrders.add(menuorder);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class Coffee extends Fragment {
ListView listView;
MenusAdapter adapter;
// Movies json url
private static final String url = "url";
private ProgressDialog pDialog;
private List<MenuDataModel> menuList = new ArrayList<MenuDataModel>();
OnMenuInteractionListener menuItemClick;
private String searchData;
private EditText inputSearch;
// Activity activity;
//OnMenuInteractionListener mCallback;
public Coffee() {
// Required empty public constructor
}
public interface OnMenuInteractionListener {
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList);
public void onMenuListItemClick(int position);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
menuItemClick = (OnMenuInteractionListener) getActivity();
}
#Override
public void onDetach() {
super.onDetach();
menuItemClick = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// searchData = getArguments().getString("search");
inputSearch = (EditText) getActivity().findViewById(R.id.search_menu);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// When user changed the Text
//adapter.getFilter().filter(cs.toString());
if (count < before) {
// We're deleting char so we need to reset the adapter data
adapter.resetData();
}
Coffee.this.adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
View view = inflater.inflate(R.layout.fragment_coffee, container, false);
listView = (ListView) view.findViewById(R.id.list);
adapter = new MenusAdapter(getActivity(), menuList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showpDialog();
// Creating volley request obj
JsonObjectRequest bookingReq = new JsonObjectRequest(Request.Method.GET, "" + url + "?", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("bsd", response.toString());
// Parsing json
try {
JSONArray menu = response.getJSONArray("menus");
int length = menu.length();
for (int i = 0; i < menu.length(); i++) {
JSONObject obj = menu.getJSONObject(i);
MenuDataModel dm = new MenuDataModel();
// Log.d("vdata", String.valueOf(menu.length()));
dm.setID(obj.getString("id"));
dm.setName(obj.getString("name"));
dm.setThumbnailUrl(obj.getString("photo"));
Log.d("image", String.valueOf(obj.getString("photo")));
dm.setDescription(obj.getString("description"));
dm.setRate(obj.getString("price"));
dm.setStatus(obj.getString("status"));
// adding movie to movies array
menuList.add(dm);
// Log.d("nth", String.valueOf(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#SuppressWarnings("deprecation")
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("b", "Error: " + error.getMessage());
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bookingReq);
return view;
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.setMessage("Please wait...");
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
public class MenusAdapter extends BaseAdapter implements Filterable {
private static final String TAG = MenusAdapter.class.getSimpleName();
List<MenuDataModel> MenuItems;
List<MenuDataModel> mSearchValues;
private android.widget.Filter menufilter;
Coffee.OnMenuInteractionListener mCallback;
//private Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public MenusAdapter(Activity activity, List<MenuDataModel> MenuItems) {
//this.activity = activity;
this.MenuItems = MenuItems;
this.mSearchValues = MenuItems;
}
#Override
public int getCount() {
return MenuItems.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return MenuItems.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.menu_item, parent, false);
}
// if (imageLoader == null)
// imageLoader = AppController.getInstance().getImageLoader();
final ImageView increase = (ImageView) view.findViewById(R.id.icon_increase);
ImageView decrease = (ImageView) view.findViewById(R.id.icon_decrease);
final EditText count = (EditText) view.findViewById(R.id.count_menu);
NetworkImageView thumbnailUrl = (NetworkImageView) view.findViewById(R.id.menu_image);
TextView name = (TextView) view.findViewById(R.id.menu_items);
// TextView description = (TextView) view.findViewById(R.id.description);
// TextView rate = (TextView) view.findViewById(R.id.price);
final MenuDataModel data = MenuItems.get(index);
name.setText(String.valueOf(data.getName()));
thumbnailUrl.setImageUrl(data.getThumbnailUrl(), imageLoader);
thumbnailUrl.setDefaultImageResId(R.mipmap.logoapp);
thumbnailUrl.setErrorImageResId(R.mipmap.logoapp);
// description.setText(String.valueOf(data.getDescription()));
// title.setText(data.getTitle());
// rate.setText(String.valueOf(data.getRate()));
// final double dis = Double.valueOf(data.getRate());
final int[] quantity = {MenuItems.get(index).getAnInt()};
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
//Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
quantity[0]++;
count.setText(quantity[0] + "");
count.setTag(quantity[0] + "");
// mCallback.onFragmentSetOrders(all);
mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
// Coffee.OnMenuInteractionListener listener = (Coffee.OnMenuInteractionListener) activit;
// mCallback.onFragmentSetOrders(menu);
// Bundle bundle = new Bundle();
// bundle.putString("quantity", quantity[0] + "");
// bundle.putString("name", String.valueOf(data.getName()));
// q.putExtra("bookingid", dataModel.getbkid());
// parent.getContext().startActivity(q);
}
});
decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count.getTag();
count.setTag(quantity[0] + "");
quantity[0]--;
count.setText(quantity[0] + "");
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return view;
}
#Override
public Filter getFilter() {
if (menufilter == null)
menufilter = new MenuFilter();
return menufilter;
}
public void resetData() {
MenuItems = mSearchValues;
}
private class MenuFilter extends android.widget.Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = mSearchValues;
results.count = mSearchValues.size();
} else {
// We perform filtering operation
List<MenuDataModel> nDriverList = new ArrayList<MenuDataModel>();
for (MenuDataModel p : MenuItems) {
if (p.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
nDriverList.add(p);
}
results.values = nDriverList;
results.count = nDriverList.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
MenuItems = (List<MenuDataModel>) results.values;
notifyDataSetChanged();
}
}
}
;
}
i am getting null pointer exception on mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
Step 1: Create Interface
public interface ActivityCommunicator{
public void passDataToActivity(ArrayList<string> arrayList);
}
Step 2:Initialize interface object in fragment class
private ActivityCommunicator activityCommunicator;;
public void onAttach(Activity activity)
{
super.onAttach(activity);
context = getActivity();
activityCommunicator =(ActivityCommunicator)context;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
activityButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
activityCommunicator.passDataToActivity("Your Array List");
}
});
}
step 3: Access Your arraylist from fragment in your activity class.
public class MainActivity extends FragmentActivity implements ActivityCommunicator{
public static ArrayList<String> aList;
#Override
public void passDataToActivity(ArrayList<String> arrayList){
aList = arrayList;
}
}

Categories

Resources