add integer values selected by checkbox - android

TestListModel.class
public class TestListModel {
private String testlist_id;
private String test_price;
private String test_name;
private boolean isSelected;
public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
this.testlist_id = testlist_id;
this.test_price = test_price;
this.test_name = test_name;
this.isSelected = isSelected;
}
public String getTestlist_id() {
return testlist_id;
}
public void setTestlist_id(String testlist_id) {
this.testlist_id = testlist_id;
}
public String getTest_price() {
return test_price;
}
public void setTest_price(String test_price) {
this.test_price = test_price;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
JsonResponse.java
public class JSONResponse {
private TestListModel[] result;
public TestListModel[] getResult() {
return result;
}
public void setResult(TestListModel[] result) {
this.result = result;
}
}
HealthActivity.java
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> data;
private RecyclerAdapter madapter;
private Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
submitButton=(Button) findViewById(R.id.submit_button);
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
initViews();
submitButton.setOnClickListener(this);
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice="";
int count = 0;
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
//AmountCartModel serialNumber = stList.get(i);
if (singleStudent.isSelected() == true) {
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
count++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
//in.putExtra("total_price",totalPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serialNumber", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/** show center Id in action bar
* */
#Override
protected void onResume() {
super.onResume();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
}
private void showcenterid(LoginModel userLoginData) {
centerId.setText(userLoginData.getResult().getGenCenterId());
centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
}
private void initViews() {
recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
//
.baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
HealthRecyclerAdapter.java
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
public RecyclerAdapter(ArrayList<TestListModel> android) {
this.android = android;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_list_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
holder.chkSelected.setTag(android.get(position));
holder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
TestListModel contact = (TestListModel) cb.getTag();
contact.setSelected(cb.isChecked());
android.get(position).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView test_name;
private TextView test_price;
public CheckBox chkSelected;
public TestListModel testLists;
public ViewHolder(View itemView) {
super(itemView);
test_name = (TextView)itemView.findViewById(R.id.test_name);
test_price = (TextView)itemView.findViewById(R.id.price_name);
chkSelected = (CheckBox) itemView.findViewById(R.id.check_box);
}
}
// method to access in activity after updating selection
public List<TestListModel> getTestList() {
return android;
}
AmountCartModel.java
public class AmountCartModel {
private String testName;
private String testPrice;
private Integer serialNumber;
private Integer totalPrice;
public AmountCartModel() {
this.testName = testName;
this.testPrice = testPrice;
this.serialNumber = serialNumber;
this.totalPrice = totalPrice;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestPrice() {
return testPrice;
}
public void setTestPrice(String testPrice) {
this.testPrice = testPrice;
}
public Integer getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(Integer serialNumber) {
this.serialNumber = serialNumber;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}
AmountCartActivity.java
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.total_price)
TextView totalPriceDisplay;
SharePreferenceManager<LoginModel> sharePreferenceManager;
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
Bundle extras ;
String testName="";
String testPrice="";
String totalPrice= "";
int counting = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("test_name");
testPrice = extras.getString("test_price");
totalPrice = String.valueOf(extras.getInt("total_price"));
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
mydataList.add(mydata);
//totalPriceDisplay.setText(totalPrice);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
RecyclerAdapter.java //RecyclerAdapter for AmountCart
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class));
finish();
}
}
This is my code.
Here I am taking HealthActivity and in this class by using recycler view I have displayed testList in recycler view. I am passing testList whichever I am selecting through checkbox to AmountCartActivity of recycler View, And, I am calculating total amount of the selected testList and I am getting the result and that result I am passing to the AmountCart Activity through bundle and I am getting correct result in bundle, but, when I am trying to display total amount in a textView its showing me nothing.
And, my second problem is,
I am trying to display serial number to to my AmountCartActivity of recycler view whichever I am selecting from previous HealthCartActivity using checkbox. And, I have implemented some code but I am not getting how to solve it. please help me.

For Issue#1
Data should be passed onto the Adapter through constructor. The issue could simply be adding another parameter to the constructor:
public MyAdapter(List<AmountCartModel> context, List<AmountCartModel> myDataList) {
this.context = context;
myDataList = this.myDataList;
}
Or,
To add selection support to a RecyclerView instance:
Determine which selection key type to use, then build a ItemKeyProvider.
Implement ItemDetailsLookup: it enables the selection library to access information about RecyclerView items given a MotionEvent.
Update item Views in RecyclerView to reflect that the user has selected or unselected it.
The selection library does not provide a default visual decoration for the selected items. You must provide this when you implement onBindViewHolder() like,
In onBindViewHolder(), call setActivated() (not setSelected()) on the View object with true or false (depending on if the item is selected).
Update the styling of the view to represent the activated status.
For Issue #2
Try using passing data through intents.
The easiest way to do this would be to pass the serial num to the activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), HealthServicesActivity.class);
intent.putExtra("EXTRA_SERIAL_NUM", serialNum);
startActivity(intent);
Access that intent on next activity
String sessionId= getIntent().getStringExtra("EXTRA_SERIAL_NUM");

Related

RecyclerView messes up when scrolling

I never asked any question before but hope you'll get my point.
I am making a chat app in which I am using a RecyclerView to show messages. The problem is when I scroll the RecyclerView some of the items disappear from the top and the whole items messes up when I try to add a message it doesn't even scroll to bottom nor added in the ListView.
Here is my RecyclerView:
<android.support.v7.widget.RecyclerView
android:id="#+id/conversation_recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:layout_above="#id/typingConversationLayout"
android:layout_below="#id/topLayout_conversation_activity"
android:layout_marginBottom="-5dp"
android:paddingBottom="7dp" />
Initializing and setting the RecycerView:
linearLayoutManager = new LinearLayoutManager(this);
adapter = new ConversationRecyclerViewAdapter();
conversationRecyclerView.setAdapter(adapter);
conversationRecyclerView.setLayoutManager(linearLayoutManager);
linearLayoutManager.setStackFromEnd(true);
conversationRecyclerView.setHasFixedSize(true);
conversationRecyclerView.setNestedScrollingEnabled(false);
Here is my Adapter class:
private class ConversationRecyclerViewAdapter
extends RecyclerView.Adapter<ConversationRecyclerViewAdapter.ConversationViewHolder> {
#NonNull
#Override
public ConversationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
Log.d(TAG, "onCreateViewHolder: Users Find started");
View conversationsView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.layout_message_received, parent, false);
return new ConversationViewHolder(conversationsView);
}
#Override
public void onBindViewHolder(#NonNull final ConversationViewHolder holderConversation, int i) {
Log.d(TAG, "onBindViewHolder: Users Find started at position is " + i);
final int position = holderConversation.getAdapterPosition();
if (mOwnUser_1.get(position)) {
holderConversation.receivedMsgLayout.setVisibility(View.GONE);
holderConversation.sentProfileImg.setImageResource(mUserProfileImg_2.get(position));
holderConversation.sentMsg.setText(mUserText_3.get(position));
} else {
holderConversation.sentMsgLayout.setVisibility(View.GONE);
holderConversation.receivedProfileImg.setImageResource(mUserProfileImg_2.get(position));
holderConversation.receivedMsg.setText(mUserText_3.get(position));
}
Log.d(TAG, "onBindViewHolder: completed at " + position);
}
#Override
public int getItemCount() {
return mOwnUser_1.size();
}
public class ConversationViewHolder extends RecyclerView.ViewHolder {
RelativeLayout receivedMsgLayout, sentMsgLayout;
EmojiTextView receivedMsg, sentMsg;
CircleImageView receivedProfileImg, sentProfileImg;
public ConversationViewHolder(#NonNull View v) {
super(v);
receivedMsgLayout = v.findViewById(R.id.received_message_layout);
sentMsgLayout = v.findViewById(R.id.sent_message_layout);
receivedMsg = v.findViewById(R.id.received_message_text);
sentMsg = v.findViewById(R.id.sent_message_text);
receivedProfileImg = v.findViewById(R.id.received_message_user__profile_image);
sentProfileImg = v.findViewById(R.id.sent_message_user__profile_image);
}
}
}
Here I am adding data to ListView and displaying to the RecyclerView:
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = editText.getText().toString().trim();
if (TextUtils.isEmpty(msg)) {
editText.setError("Please add a message");
editText.requestFocus();
} else {
Log.d(TAG, "onClick: send Btn ADDED TEXT.. ");
mOwnUser_1.add(user);
mUserProfileImg_2.add(image);
mUserText_3.add(message);
editText.setText("");
editText.requestFocus();
adapter.notifyItemInserted(mOwnUser_1.size());
conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);
}
}
});
I don't know what i am doing wrong but it does not seem to work as i wanted.
Update Code:
The three listviews:
private ArrayList<Boolean> mOwnUser_1 = new ArrayList<>();
private ArrayList<Integer> mUserProfileImg_2 = new ArrayList<>();
private ArrayList<String> mUserText_3 = new ArrayList<>();
And the way of adding data to adapter:
mOwnUser_1.add(true);
mUserProfileImg_2.add(R.drawable.boy);
mUserText_3.add(edittext.getText().toString().trim());
adapter.notifyItemInserted(mOwnUser_1.size());
conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);
My Whole Conversation Activity Class:
public class ConversationActivity extends AppCompatActivity {
private static final String TAG = "ConversationActivity";
private EditText editText;
private LinearLayout linearLayout;
private LinearLayoutManager linearLayoutManager;
private ImageView sendBtn;
private ImageView emojiImage;
private View rootView;
private Boolean popUpShown = false;
private Boolean micShown = false;
private ImageView micBtn;
private RelativeLayout micLayout;
private RecyclerView conversationRecyclerView;
// Array Lists for Find USERS
private ArrayList<Boolean> mOwnUser_1 = new ArrayList<>();
private ArrayList<Integer> mUserProfileImg_2 = new ArrayList<>();
private ArrayList<String> mUserText_3 = new ArrayList<>();
private ConversationRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: started");
super.onCreate(savedInstanceState);
EmojiManager.install(new TwitterEmojiProvider());
setContentView(R.layout.activity_conversation);
editText = findViewById(R.id.conversationEditText);
linearLayout = findViewById(R.id.optionsOther);
emojiImage = findViewById(R.id.emojiIconOther);
rootView = findViewById(R.id.root_view_conversation);
micBtn = findViewById(R.id.microphoneBtn);
micLayout = findViewById(R.id.microphoneLayout);
conversationRecyclerView = findViewById(R.id.conversation_recyclerView);
sendBtn = findViewById(R.id.sendBtnConversation);
if (!(Build.VERSION.SDK_INT >= 21))
findViewById(R.id.typingConversationLayout).setBackgroundResource(R.drawable.edit_text_conversation_background_below_api);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = editText.getText().toString().trim();
if (TextUtils.isEmpty(msg)) {
editText.setError("Please add a message");
editText.requestFocus();
} else {
Log.d(TAG, "onClick: send Btn ADDED TEXT.. ");
addData(true, R.drawable.boy0, msg);
}
}
});
initConversationArrayList();
}
private void addData(Boolean user, int image, String message) {
mOwnUser_1.add(user);
mUserProfileImg_2.add(image);
mUserText_3.add(message);
editText.setText("");
editText.requestFocus();
adapter.notifyItemInserted(mOwnUser_1.size());
conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);
}
private void initConversationArrayList() {
Log.d(TAG, "initConversationArrayList: created");
mOwnUser_1.add(true);
mUserProfileImg_2.add(R.drawable.boy0);
mUserText_3.add("Hello How are you?");
Log.d(TAG, "initConversationArrayList: completed");
initConversationRecyclerView();
}
private void initConversationRecyclerView() {
Log.d(TAG, "initConversationRecyclerView: started");
linearLayoutManager = new LinearLayoutManager(this);
adapter = new ConversationRecyclerViewAdapter();
conversationRecyclerView.setAdapter(adapter);
conversationRecyclerView.setLayoutManager(linearLayoutManager);
linearLayoutManager.setStackFromEnd(true);
conversationRecyclerView.setHasFixedSize(true);
conversationRecyclerView.setNestedScrollingEnabled(false);
Log.d(TAG, "initConversationRecyclerView: completed");
}
Currently I am also working on chat module, let me show you how am I doing this. I am going to show you in steps.
Step 1: make two separate layout for recyclerview items, one for message that has been sent from your side and one for message received from another side.
Step 2 : make two view holders to populate different layout according to your scenario, made in above step, like this:
public class ChatNewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Chat> chats;
public ChatNewAdapter(List<Chat> chats) {
this.chats = chats;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
View viewSend = (View) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message_send, parent, false);
return new ViewHolderSend(viewSend);
} else {
View viewReceive = (View) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message_received, parent, false);
return new ViewHolderReceive(viewReceive);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolderSend viewHolderSend = (ViewHolderSend) holder;
viewHolderSend.messageSend.setText(chats.get(position).getMessage());
break;
case 1:
ViewHolderReceive viewHolderReceive = (ViewHolderReceive) holder;
viewHolderReceive.messageReceived.setText(chats.get(position).getMessage());
break;
}
}
#Override
public int getItemCount() {
return chats.size();
}
#Override
public int getItemViewType(int position) {
if (chats != null && !chats.get(position).fromAdmin) {
return 0;
} else
return 1;
}
class ViewHolderSend extends RecyclerView.ViewHolder {
TextView messageSend;
public ViewHolderSend(View itemView) {
super(itemView);
messageSend = (TextView) itemView.findViewById(R.id.messageSend);
}
}
class ViewHolderReceive extends RecyclerView.ViewHolder {
TextView messageReceived;
public ViewHolderReceive(View itemView) {
super(itemView);
messageReceived = (TextView) itemView.findViewById(R.id.messageReceived);
}
}
public int addMessages(Chat chat) {
chats.add(chat);
notifyDataSetChanged();
return chats.size();
}
Step 3 : now in your activity:
public class Test extends AppCompatActivity {
RecyclerView chatList;
RecyclerView.LayoutManager mLayoutManager;
ChatNewAdapter adapter;
ImageView sendButton;
EditText messageEditText;
boolean keyboardUp = false;
boolean isRunning = false;
ArrayList<Chat> chats;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
isRunning = true;
setUpComponents();
}
public void setUpComponents() {
chatList = (RecyclerView) findViewById(R.id.chat_list);
chatList.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
chatList.setLayoutManager(mLayoutManager);
messageEditText = (EditText) findViewById(R.id.messageText);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
sendButton = (ImageView) findViewById(R.id.send);
adapter = new ChatNewAdapter(chats);
chatList.setAdapter(adapter);
chatList.scrollToPosition(chatList.getAdapter().getItemCount() - 1);
messageEditText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (keyboardShown(messageEditText.getRootView())) {
Log.d("keyboard", "keyboard UP");
if (keyboardUp == false) {
if (chats.size() > 0)
chatList.smoothScrollToPosition(chats.size() + 1);
keyboardUp = true;
}
} else {
Log.d("keyboard", "keyboard Down");
keyboardUp = false;
}
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String message = messageEditText.getText().toString().trim();
if (!message.equals("")) {
Chat chat = new Chat();
String name = message;
chat.setMessage(name);
messageEditText.setText("");
adapter.addMessages(chat);
chatList.scrollToPosition(chatList.getAdapter().getItemCount() - 1);
} else {
Log.d("sending message Error", "error fetching dates");
}
}
});
}
private boolean keyboardShown(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}
And this is my model class, ignore #PrimaryKey and #Required annotation it just because I am using Realm for local DB. In your case you wont required these annotation.
public class Chat extends RealmObject {
#PrimaryKey
#Required
public Long id;
public boolean fromAdmin;
#Required
public String message;
public int type;
public boolean isRead;
public boolean isSent;
public Date date;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isFromAdmin() {
return fromAdmin;
}
public void setFromAdmin(boolean fromAdmin) {
this.fromAdmin = fromAdmin;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public boolean isRead() {
return isRead;
}
public void setRead(boolean read) {
isRead = read;
}
public boolean isSent() {
return isSent;
}
public void setSent(boolean sent) {
isSent = sent;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
I hope it will be helpful for you, you can ask further if you want to know anything else related to code.
RecyclerView as the name stands recycles the views. When binding data to a view, you need to ensure you set or reset all views that are touched in the adapter. Messups typically occur when there's data that is set only conditionally for some but not all items.
In particular:
if (mOwnUser_1.get(position)) {
holderConversation.receivedMsgLayout.setVisibility(View.GONE);
holderConversation.sentProfileImg.setImageResource(mUserProfileImg_2.get(position));
holderConversation.sentMsg.setText(mUserText_3.get(position));
} else {
holderConversation.sentMsgLayout.setVisibility(View.GONE);
holderConversation.receivedProfileImg.setImageResource(mUserProfileImg_2.get(position));
holderConversation.receivedMsg.setText(mUserText_3.get(position));
}
Both of these branches will need to reset the other layout back to visible.
Anyway with this kind of two-layout approach you are likely better off by having them as separate view types in your adapter. See How to create RecyclerView with multiple view type?

How to maintain checkbox state after clicking on previous button by using rest api call

Model Class
public class TestListModel {
private String testlist_id;
private String test_price;
private String test_name;
private boolean isSelected;
public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
this.testlist_id = testlist_id;
this.test_price = test_price;
this.test_name = test_name;
this.isSelected = isSelected;
}
public String getTestlist_id() {
return testlist_id;
}
public void setTestlist_id(String testlist_id) {
this.testlist_id = testlist_id;
}
public String getTest_price() {
return test_price;
}
public void setTest_price(String test_price) {
this.test_price = test_price;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
public boolean isSelected() {
return isSelected;
}
public boolean setSelected(boolean isSelected) {
this.isSelected = isSelected;
return isSelected;
}
}
Recycler Adapter Class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
public RecyclerAdapter(ArrayList<TestListModel> android) {
this.android = android;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_list_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
holder.chkSelected.setTag(android.get(position));
holder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
TestListModel contact = (TestListModel) cb.getTag();
contact.setSelected(cb.isChecked());
android.get(position).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView test_name;
private TextView test_price;
public CheckBox chkSelected;
public TestListModel testLists;
public ViewHolder(View itemView) {
super(itemView);
test_name = (TextView)itemView.findViewById(R.id.test_name);
test_price = (TextView)itemView.findViewById(R.id.price_name);
chkSelected = (CheckBox) itemView.findViewById(R.id.check_box);
}
}
// method to access in activity after updating selection
public List<TestListModel> getTestList() {
return android;
}
}
HealthActivity
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
SharePreferenceManager<LoginModel> sharePreferenceManager;
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> data;
private RecyclerAdapter madapter;
private Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
submitButton = (Button) findViewById(R.id.submit_button);
}
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
String serialNo="";
int serialNum=1;
String testListId = "";
int totalPrice = 0;
String testName = "";
String testPrice="";
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
testListId = testListId+ "," + singleStudent.getTestlist_id().toString();
testName = testName + "\n" + "\n" + singleStudent.getTest_name().toString();
testPrice= testPrice+"\n" + "\n" + singleStudent.getTest_price().toString();
serialNo=serialNo + "\n" + "\n"+ Integer.parseInt(String.valueOf(serialNum));
serialNum++;
totalPrice= totalPrice+ Integer.parseInt(stList.get(i).getTest_price());
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_id",testListId);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
in.putExtra("total_price",totalPrice);
in.putExtra("serial_number",serialNo);
in.putExtra("patient_id",patientID);
startActivity(in);
}
else
Toasty.error(getApplicationContext(), "Please Select Test Lists", Toast.LENGTH_SHORT, true).show();
}
break;
/* Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+""+testPrice, Toast.LENGTH_LONG)
.show();*/
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/*
* Api Call For Displaying Test Lists
* */
private void loadJSON() {
String centerID=(sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
// .baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists("http://192.168.1.80/aoplnew/api/users/gettestlist/"+centerID);
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
Toast.makeText(HealthServicesActivity.this, "APi Call Back", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
}
}
AmountCartActivity
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener , PaymentResultListener {
SharePreferenceManager<LoginModel> sharePreferenceManager;
/*
*Setting Recycler View
* */
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
/*
* Getting Bundle Values
* */
Bundle extras ;
String testId="";
String testName="";
String testPrice="";
String totalPrice="";
String serialNumber="";
private Button backButton;
/*
* Api Call For DashBoard
* */
String st;
Api webService = ServiceGenerator.getApi();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
progressDialog = new ProgressDialog(AmountCartActivity.this);
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
backButton=(Button) findViewById(R.id.back_button);
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
backButton.setOnClickListener(this);
gettingValues();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
startActivity(new Intent(getApplicationContext(), HealthServicesActivity.class));
//finish();
break;
default:
break;
}
}
/*
* Getting Bundle Values and Setting Recycler View
* */
private void gettingValues() {
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
bundle = getIntent().getExtras();
if (bundle != null) {
testId=bundle.getString("test_id");
testName = bundle.getString("test_name");
testPrice = bundle.getString("test_price");
totalPrice= String.valueOf(bundle.getInt("total_price"));
serialNumber=bundle.getString("serial_number");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestId(testId);
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setSerialNumber(serialNumber);
mydataList.add(mydata);
totalPriceDisplay.setText("Total Amount : "+totalPrice);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
}
Recycler Adapter for AmountCart
/*
* Recycler Adapter
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
How to maintain the checkbox state across the activities. I am displaying checkbox using recycler view in rest api call. I am selecting checkboxes from HealthActivity and clicking on submit button then the whole list is displaying in AmountCartActivity but when I m clicking on back button then i m not getting those selected checkboxes. And when I add or remove any checkbox then it should give the result as per selection only. How to maintain the state of the selected checkboxes?
In your AmountCartActivity when you listen for back button clicks you do this:
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
startActivity(new Intent(getApplicationContext(), HealthServicesActivity.class));
//finish();
break;
default:
break;
}
}
You are opening a brand new HealthServicesActivity and you don't persist the data anywhere. (When you open a new HealthServicesActivity it does not know anything about your old list). So I think what you aim to do is finishing the AmountCartActivity and resuming the previous HealthServicesActivity like this:
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
finish(); //JUST FINISH THE ACTIVITY AND RETURN TO THE PREVIOUS ACTIVITY
break;
default:
break;
}
}
EDIT: (added item click listener logic)
As you will be using the same HealthServiceActivity every time you submit and go back, I think you should implement an interface to keep your checkbox states updated. Make below changes in your respective methods (Please see my comments)
RecylerAdapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
private OnItemClickListener onItemClickListener; //ADD THIS GLOBAL FIELD
/** THIS METHOD IS TO BIND YOUR NEW ITEM CLICK LISTENER **/
public void setOnItemClickListener(OnItemClickListener onItemClickListener)
{
this.onItemClickListener = onItemClickListener;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
//YOU DON'T HAVE TO DEAL WITH TAGS, JUST USE BELOW CODE TO SET YOUR
// ITEM CLICK LISTENER TO EACH CHECKBOX
holder.chkSelected.setOnClickListener(v ->
onItemClickListener.onClickItem(position);
}
// THIS METHOD WILL SWITCH YOUR SELECT STATES AND UPDATE ITEMS ACCORDINGLY
public void updateCheckboxState(int position){
TestListModel listItem = android.get(position);
listItem.setSelected(!listItem.isSelected());
notifyDataSetChanged();
}
// ADD THIS INTERFACE
public interface OnItemClickListener {
void onClickItem(int position);
}
}
HealthServicesActivity:
//DON'T FORGET TO IMPLEMENT RecylcerAdapter.OnItemClickListener
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener, RecyclerAdapter.OnItemClickListener {
/*
* Api Call For Displaying Test Lists
* */
private void loadJSON() {
{ ... }
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
madapter.setOnItemClickListener(this); // SET YOUR LISTENER HERE
recyclerView.setAdapter(madapter);
Toast.makeText(HealthServicesActivity.this, "APi Call Back", Toast.LENGTH_SHORT).show();
}
// UPDATE CHECKBOX STATES WHEN AN ITEM IS CLICKED
#Override
public void onClickItem(int position) {
madapter.updateCheckboxState(position);
}
}

How to add data into RecyclerView

In my application I want use two recyclerView into one Activity.
I want when click on items of one of this recylerView's items , add item to another recyclerView.
I write below codes, when click on items just add lasted item info to another recyclerView.
But I want when click on each items, add this each items into another recyclerView not just add lasted items.
Now just add lasted items, but I want click each item add this item.
My Activity code:
public class SuggestFilmActivity extends AppCompatActivity implements SuggestedListener {
#BindView(R.id.toolbarTitleTxt)
TextView toolbarTitleTxt;
#BindView(R.id.suggestFilm_searchEditText)
EditText suggestFilm_searchEditText;
#BindView(R.id.suggestFilm_searchBtn)
ImageView suggestFilm_searchBtn;
#BindView(R.id.suggestFilm_recyclerView)
RecyclerView suggestFilm_recyclerView;
#BindView(R.id.suggestFilm_recyclerViewProgress)
ProgressBar suggestFilm_recyclerViewProgress;
#BindView(R.id.newsPageLoadLay)
RelativeLayout newsPageLoadLay;
#BindView(R.id.suggestFilm_recyclerViewSendUser)
RecyclerView suggestFilm_recyclerViewSendUser;
private Context context;
private SuggestFilmAdapter suggestFilmAdapter;
private SuggestFilmUserAdapter suggestFilmUserAdapter;
private List<Result> model = new ArrayList<>();
private InterfaceApi api;
private SharedPrefrencesHandler prefrencesHandler;
private String token;
private GridLayoutManager gridLayoutManager;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suggest_film);
//Initialize
ButterKnife.bind(this);
context = this;
prefrencesHandler = new SharedPrefrencesHandler(context);
api = ApiClient.getClient().create(InterfaceApi.class);
suggestFilmAdapter = new SuggestFilmAdapter(context, model, this);
gridLayoutManager = new GridLayoutManager(context, 3);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
//Get token
token = prefrencesHandler.getFromShared(SharedPrefrencesKeys.TOKEN.name());
//Set toolbar title
toolbarTitleTxt.setText(context.getResources().getString(R.string.SuggestToFollowers));
//Init followers recyclerView
suggestFilm_recyclerView.setLayoutManager(gridLayoutManager);
suggestFilm_recyclerView.setHasFixedSize(true);
//Init send user recyclerView
suggestFilm_recyclerViewSendUser.setLayoutManager(linearLayoutManager);
suggestFilm_recyclerViewSendUser.setHasFixedSize(true);
//Load more
newsPageLoadLay.setVisibility(View.GONE);
suggestFilm_recyclerView.setOnScrollListener(new EndlessRecyclerGridPage1(gridLayoutManager) {
#Override
public void onLoadMore(int current_page) {
newsPageLoadLay.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(current_page));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getStatusCode() != 401
&& response.body().getStatusCode() != 402) {
if (response.body().getData().getResult().size() > 0) {
suggestFilmAdapter.addNewItem(response.body().getData().getResult());
//Gone no explore
newsPageLoadLay.setVisibility(View.GONE);
}
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
newsPageLoadLay.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
newsPageLoadLay.setVisibility(View.GONE);
}
});
}
});
//Get user data
getUserData();
}
private void getUserData() {
suggestFilm_recyclerViewProgress.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(1));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getData().getResult().size() > 0
&& response.body().getStatusCode() != 401 && response.body().getStatusCode() != 402) {
model.clear();
model.addAll(response.body().getData().getResult());
suggestFilmAdapter.notifyDataSetChanged();
suggestFilm_recyclerView.setAdapter(suggestFilmAdapter);
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
});
}
private SuggestFilmSendData filmSendData(int page) {
SuggestFilmSendData sendData = new SuggestFilmSendData();
sendData.setKeyword("");
sendData.setPageIndex(page);
sendData.setPageSize(10);
return sendData;
}
private ArrayList<SuggestFilmAddUser> prepareData(int id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = new ArrayList<>();
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
return suggestFilmAddUserList;
}
#Override
public void onSend(int Id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = prepareData(Id, name, image);
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context, suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
}
}
One recyclerView adapter and send data Interface codes:
public class SuggestFilmAdapter extends RecyclerView.Adapter<SuggestFilmAdapter.ViewHolder> {
private Context context;
private List<Result> model;
private SuggestedListener suggestedListener;
public SuggestFilmAdapter(Context context, List<Result> model, SuggestedListener suggestedListener) {
this.context = context;
this.model = model;
this.suggestedListener = suggestedListener;
}
#Override
public SuggestFilmAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_suggest_film_users_followers, parent, false);
return new SuggestFilmAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final SuggestFilmAdapter.ViewHolder holder, final int position) {
//Name
holder.row_suggestFilmProfileName.setText(model.get(position).getName());
//Image
Glide.with(context)
.load(model.get(position).getImageUrl())
.asBitmap()
.placeholder(R.drawable.default_image)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(300, 300)
.into(new BitmapImageViewTarget(holder.row_suggestFilmProfileImage) {
#Override
protected void setResource(Bitmap resource) {
if (context == null) return;
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
holder.row_suggestFilmProfileImage.setImageDrawable(circularBitmapDrawable);
}
});
//Is Mutual
if (model.get(position).getIsMutual()) {
holder.row_suggestFilmIsOk.setVisibility(View.VISIBLE);
} else {
holder.row_suggestFilmIsOk.setVisibility(View.GONE);
}
holder.row_suggestedLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
suggestedListener.onSend(model.get(position).getUserId(),
model.get(position).getName(),
model.get(position).getImageUrl());
}
});
}
#Override
public int getItemCount() {
return model.size();
}
public void addNewItem(List<Result> newContent) {
int start = this.model.size();
int end = newContent.size();
model.addAll(newContent);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView row_suggestFilmProfileImage, row_suggestFilmIsOk;
private TextView row_suggestFilmProfileName;
private RelativeLayout row_suggestedLay;
public ViewHolder(View itemView) {
super(itemView);
row_suggestFilmProfileImage = (ImageView) itemView.findViewById(R.id.row_suggestFilmProfileImage);
row_suggestFilmIsOk = (ImageView) itemView.findViewById(R.id.row_suggestFilmIsOk);
row_suggestFilmProfileName = (TextView) itemView.findViewById(R.id.row_suggestFilmProfileName);
row_suggestedLay = (RelativeLayout) itemView.findViewById(R.id.row_suggestedLay);
}
}
}
Model class :
public class SuggestFilmAddUser {
private int id;
private String name;
private String image;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
How can I it? Please help me
Inside onSend() , you need to add each objects to an arraylist which should be declared globally. Then call notifyItemInserted(arraylist.size()-1) in adapter to refresh recyclerview
public class SuggestFilmActivity ....
{ ArrayList<SuggestFilmAddUser> suggestFilmAddUserList=new ArrayList();
SuggestFilmUserAdapter suggestFilmUserAdapter;
......
......
protected void onCreate(Bundle savedInstance)
{....
....
....
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context,
suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
.....
.....
}
public void onSend(int Id, String name, String image) {
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
suggestFilmUserAdapter.notifyItemInserted(suggestFilmAddUserList.size()-1)
}

How to instantiate interface from asynctask inside fragment

I have an Interface implemented in ProductListAdapter class which is a list adapter. Items in this list have three input fields. to keep track of those values I have implemented a class MyCustomEditTextListener which extends a TextWatcher class. This class simply create array list of edited data. I want to get reference to array list every time it changes from fragment which contains list view. For that I have implemented DataChangedListener
ProductListAdapter.java
public class ProductListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private LayoutInflater inflater;
private ArrayList<Products> listData;
private ArrayList<Products> editedData;
private Context context;
private DataChangedListener dataChangedListener;
private static final int ITEM = 0;
private static final int LOADING = 1;
private static final int QUANTITY = 5;
private static final int FREE_QUANTITY = 10;
private static final int DISCOUNT = 15;
public ProductListAdapter(ArrayList<Products> listData, ArrayList<Products> editedData, Context context) {
this.listData = listData;
this.context = context;
this.editedData = editedData;
inflater = LayoutInflater.from(this.context);
}
public void updateData(ArrayList<Products> data) {
this.listData = data;
notifyDataSetChanged();
}
public void setDataChangedListener(DataChangedListener listener) {
this.dataChangedListener = listener;
}
#Override
public int getItemViewType(int position) {
return listData.get(position) == null ? LOADING : ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.list_footer, parent, false);
viewHolder = new LoadingVH(v2);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Products productObject = listData.get(position);
switch (getItemViewType(position)) {
case ITEM:
for(int i=0; i<editedData.size(); i++){
if(productObject.getProductId().equals(editedData.get(i).getProductId())){
productObject.setQuantity(editedData.get(i).getQuantity());
productObject.setFreeQuantity(editedData.get(i).getFreeQuantity());
productObject.setDiscount(editedData.get(i).getDiscount());
}
}
String productName = productObject.getProductName();
String quantityValue = productObject.getQuantity();
String freeQuantityValue = productObject.getFreeQuantity();
String discountValue = productObject.getDiscount();
String quantityInHand = productObject.getQuantityInHand();
String price = productObject.getWholeSalePrice();
ContentViewHolder movieVH = (ContentViewHolder) holder;
movieVH.productName.setText(productName);
movieVH.stock.setText(quantityInHand);
movieVH.price.setText("Rs."+price);
movieVH.quantityEditTextListener.updatePosition(movieVH.getLayoutPosition());
movieVH.quantity.setText(quantityValue);
movieVH.freeQuantityEditTextListener.updatePosition(movieVH.getLayoutPosition());
movieVH.freeQuantity.setText(freeQuantityValue);
movieVH.discountEditTextListener.updatePosition(movieVH.getLayoutPosition());
movieVH.discount.setText(discountValue);
movieVH.quantity.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
return false;
}
});
break;
case LOADING:
//Do nothing
break;
}
}
#Override
public int getItemCount() {
return listData == null ? 0 : listData.size();
}
#NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
View view = inflater.inflate(R.layout.custom_product_list_item, parent, false);
viewHolder = new ContentViewHolder(view, new MyCustomEditTextListener()
, new MyCustomEditTextListener(), new MyCustomEditTextListener());
return viewHolder;
}
/**
* View holder for main container
*/
public class ContentViewHolder extends RecyclerView.ViewHolder{
private TextView productName;
private EditText quantity;
private EditText freeQuantity;
private EditText discount;
private TextView stock;
private TextView price;
private MyCustomEditTextListener quantityEditTextListener;
private MyCustomEditTextListener freeQuantityEditTextListener;
private MyCustomEditTextListener discountEditTextListener;
public ContentViewHolder(View itemView, MyCustomEditTextListener textListener
, MyCustomEditTextListener textListener2, MyCustomEditTextListener textListener3) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.product_name_data);
quantity = (EditText) itemView.findViewById(R.id.quantity_1_edit_text);
freeQuantity = (EditText) itemView.findViewById(R.id.quantity_2_edit_text);
discount = (EditText) itemView.findViewById(R.id.quantity_3_edit_text);
stock = (TextView) itemView.findViewById(R.id.quantity_in_hand_value);
price = (TextView) itemView.findViewById(R.id.price_value);
quantityEditTextListener = textListener;
quantityEditTextListener.setEditTextType(QUANTITY);
freeQuantityEditTextListener = textListener2;
freeQuantityEditTextListener.setEditTextType(FREE_QUANTITY);
discountEditTextListener = textListener3;
discountEditTextListener.setEditTextType(DISCOUNT);
this.quantity.addTextChangedListener(quantityEditTextListener);
this.freeQuantity.addTextChangedListener(freeQuantityEditTextListener);
this.discount.addTextChangedListener(discountEditTextListener);
}
}
/**
* View holder to display loading list item
*/
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(View itemView) {
super(itemView);
}
}
/**
* textWatcher for to keep track of changed data.
*/
private class MyCustomEditTextListener implements TextWatcher {
private int position;
private int type;
public void updatePosition(int position) {
this.position = position;
}
public void setEditTextType(int type) {
this.type = type;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
// no op
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (type == QUANTITY) {
listData.get(position).setQuantity(charSequence.toString());
} else if (type == FREE_QUANTITY) {
listData.get(position).setFreeQuantity(charSequence.toString());
} else if (type == DISCOUNT) {
listData.get(position).setDiscount(charSequence.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
boolean matchFound = false;
if(s.toString().length()>0){
for (int i=0;i<editedData.size();i++){
if(editedData.get(i).getProductId()
.equals(listData.get(position).getProductId())){
matchFound = true;
if (type == QUANTITY) {
editedData.get(i).setQuantity(s.toString());
} else if (type == FREE_QUANTITY) {
editedData.get(i).setFreeQuantity(s.toString());
} else if (type == DISCOUNT) {
editedData.get(i).setDiscount(s.toString());
}
}
}
if(!matchFound){
editedData.add(listData.get(position));
}
if(dataChangedListener!=null){
dataChangedListener.onDataChanged(editedData);
}
}
}
}
public interface DataChangedListener{
void onDataChanged(ArrayList<Products> editedData);
}
In my OrderEditFragment i'm trying to implement that interface to do necessary calculations.
OrderEditFragment.java
public class OrderEditFragment extends Fragment implements ProductListAdapter.DataChangedListener {
private LinearLayoutManager layoutManager;
private RecyclerView productRecyclerView;
private static ProductListAdapter productListAdapter;
private String employeeId;
private static ArrayList<Products> editedData;
private static ArrayList<Products> productsData;
private SharedPreferences sharedpreferences;
private final static OkHttpClient client = new OkHttpClient();
public OrderEditFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_order_edit, container, false);
initComponents(inflate);
return inflate;
}
private void initComponents(View view) {
productRecyclerView = (RecyclerView) view.findViewById(R.id.product_edit_recycler_view);
progressView = (CircularProgressView) view.findViewById(R.id.progress_view);
layoutManager = new LinearLayoutManager(getContext());
sharedpreferences = getActivity().getSharedPreferences("dgFashionPref", Context.MODE_PRIVATE);
employeeId = sharedpreferences.getString("employee_id","");
productsData = new ArrayList<>();
editedData = new ArrayList<>();
isLoading = false;
isLastPage = false;
isFirstLoad = true;
isSearch = false;
new GetProductListGetRequest(getContext(), productRecyclerView, layoutManager)
.execute(RestConnection.PRODUCT_LIST_GET
+ RestConnection.CUSTOMER_ID_FOR_NAME + employeeId);
}
#Override
public void onDataChanged(ArrayList<Products> editedData) {
Log.d(TAG,editedData.toString());
}
/**
* AsyncTask class which handel the GET request to get product list
**/
public static class GetProductListGetRequest extends AsyncTask<String, Void, String>{
private WeakReference<Context> ActivityWeakReference;
private WeakReference<RecyclerView> recyclerViewWeakReference;
private WeakReference<RecyclerView.LayoutManager> layoutManagerWeakReference;
public GetProductListGetRequest(Context activity, RecyclerView recyclerView
, RecyclerView.LayoutManager layoutManager) {
ActivityWeakReference = new WeakReference<>(activity);
recyclerViewWeakReference = new WeakReference<>(recyclerView);
layoutManagerWeakReference = new WeakReference<>(layoutManager);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String urlEndPoint = params[0];
Request request = new Request.Builder()
.url(RestConnection.API_BASE + urlEndPoint)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if( productsData.size()>0){
productsData.remove(productsData.size() - 1);
}
JSONArray responseBody;
try {
if (response != null && ActivityWeakReference.get() != null) {
responseBody = new JSONArray(response);
for (int i = 0; i < responseBody.length(); i++) {
JSONObject row = responseBody.getJSONObject(i);
String productId = row.getString("ProductID");
String productName = row.getString("Name");
String unit = row.getString("Unit");
String wholeSalePrice = row.getString("WSalePrice");
String packSize = row.getString("PackSize");
String retailPrice = row.getString("RetailPrice");
String costPrice = row.getString("CostPrice");
String qtyInHand = row.getString("QtyInHand");
Products productObj = new Products();
productObj.setProductName(productName);
productObj.setProductId(productId);
productObj.setUnit(unit);
productObj.setWholeSalePrice(wholeSalePrice);
productObj.setPackSize(packSize);
productObj.setRetailPrice(retailPrice);
productObj.setCostPrice(costPrice);
productObj.setQuantityInHand(qtyInHand);
productsData.add(productObj);
}
productListAdapter = new ProductListAdapter(productsData, editedData, ActivityWeakReference.get());
productListAdapter.setDataChangedListener(ActivityWeakReference.get());
recyclerViewWeakReference.get().setAdapter(productListAdapter);
recyclerViewWeakReference.get().setLayoutManager(layoutManagerWeakReference.get());
recyclerViewWeakReference.get().addItemDecoration(new RecyclerViewDivider(2));
} else {
Toast.makeText(ActivityWeakReference.get(), "Can't connect to the server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e)
{
Log.d(TAG, "Get customer details onPostExecute :" + e.getLocalizedMessage());
}
}
}
/**
* A class that define space between list items
*/
private static class RecyclerViewDivider extends RecyclerView.ItemDecoration {
int space;
public RecyclerViewDivider(int space) {
this.space = space;
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.bottom = space;
if (parent.getChildLayoutPosition(view) == 0) {
outRect.top = space;
}
}
}
}
As you can see I'm trying to instantiate interface inside AsyncTask class soon after created productListAdapter object by calling setDataChangedListener(DataChangedListener listener); method. But it did not take ActivityWeakReference.get() as a valid parameter. I have done slimier thing before with list adapter to bring custom created onListItemClick event to activity. In those cases ActivityWeakReference.get() works fine. I think this is happening because I'm in a fragment, But I can't figure out which object I should pass. I need to create Adapter inside AsyncTask because i have implemented pagination for list view. I remove those codes to make this post short. Please help.
Found the solution. You need to pass fragment object to interface not the activity.
Here's my fragment class now.
/**
* AsyncTask class which handel the GET request to get product list
**/
public static class GetProductListGetRequest extends AsyncTask<String, Void, String>{
private WeakReference<OrderEditFragment> fragmentWeakReference;
private WeakReference<RecyclerView> recyclerViewWeakReference;
private WeakReference<RecyclerView.LayoutManager> layoutManagerWeakReference;
public GetProductListGetRequest(OrderEditFragment fragment, RecyclerView recyclerView
, RecyclerView.LayoutManager layoutManager) {
fragmentWeakReference = new WeakReference<>(fragment);
recyclerViewWeakReference = new WeakReference<>(recyclerView);
layoutManagerWeakReference = new WeakReference<>(layoutManager);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String urlEndPoint = params[0];
Request request = new Request.Builder()
.url(RestConnection.API_BASE + urlEndPoint)
.build();
//Log.d(TAG,RestConnection.API_BASE + urlEndPoint);
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if( productsData.size()>0){
productsData.remove(productsData.size() - 1);
}
JSONArray responseBody;
//Log.d(TAG,response);
try {
if (response != null && fragmentWeakReference.get() != null) {
responseBody = new JSONArray(response);
for (int i = 0; i < responseBody.length(); i++) {
JSONObject row = responseBody.getJSONObject(i);
String productId = row.getString("ProductID");
String productName = row.getString("Name");
String unit = row.getString("Unit");
String wholeSalePrice = row.getString("WSalePrice");
String packSize = row.getString("PackSize");
String retailPrice = row.getString("RetailPrice");
String costPrice = row.getString("CostPrice");
String qtyInHand = row.getString("QtyInHand");
Products productObj = new Products();
productObj.setProductName(productName);
productObj.setProductId(productId);
productObj.setUnit(unit);
productObj.setWholeSalePrice(wholeSalePrice);
productObj.setPackSize(packSize);
productObj.setRetailPrice(retailPrice);
productObj.setCostPrice(costPrice);
productObj.setQuantityInHand(qtyInHand);
productsData.add(productObj);
}
/** if lower limit and upper limit change, change responseBody.length()<10 respectively **/
if (responseBody.length() == 0 || responseBody.length() < 10) {
isLastPage = true;
}
if (isFirstLoad) {
progressView.setVisibility(View.GONE);
recyclerViewWeakReference.get().setVisibility(View.VISIBLE);
productListAdapter = new ProductListAdapter(productsData, editedData, fragmentWeakReference.get().getContext());
productListAdapter.setDataChangedListener(fragmentWeakReference.get());
recyclerViewWeakReference.get().setAdapter(productListAdapter);
recyclerViewWeakReference.get().setLayoutManager(layoutManagerWeakReference.get());
recyclerViewWeakReference.get().addItemDecoration(new RecyclerViewDivider(2));
isFirstLoad = false;
} else {
productListAdapter.updateData(productsData);
isLoading = false;
}
} else {
Toast.makeText(fragmentWeakReference.get().getContext(), "Can't connect to the server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e)
{
Log.d(TAG, "Get customer details onPostExecute :" + e.getLocalizedMessage());
}
}
}
And create AsyncTask object like bellow.
new GetProductListGetRequest(this, productRecyclerView, layoutManager)
.execute(RestConnection.PRODUCT_LIST_GET
+ RestConnection.CUSTOMER_ID_FOR_NAME + employeeId);

Why not show posts from server when use Retrofit in Android

I want to use Retrofit to load data from server, and I use DataModel for set and get data.
This is what I would like to do. When I click on a Category, I want to see posts from this category in the other Activity.
For showing category posts I use this link : http://tellfa.com/tafrihgah/?json=get_category_posts
For filtering I use category id.
For example : http://tellfa.com/tafrihgah/?json=get_category_posts&id=1 by this link i see all of posts from Category1.
My Retrofit interface for set link: (I set base_url in other class)
public interface Retrofit_ApiInterface {
// For Categories Response
#GET("tafrihgah/?json=get_category_posts&")
Call<R_CatModelResponse> getCatResponse(#Query("id") Integer id);
}
I send category id to other activity by this code :
public class ColoniesAdapter extends RecyclerView.Adapter<ColoniesAdapter.ViewHolder> {
private List<Retrofit_ColoniesModel> mDateSet;
private Context mContext;
private SparseBooleanArray expandState = new SparseBooleanArray();
public ColoniesAdapter(Context context, List<Retrofit_ColoniesModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
for (int i = 0; i < mDateSet.size(); i++) {
expandState.append(i, false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.colonies_title.setText(mDateSet.get(position).getTitle());
holder.colonies_title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
Retrofit_ColoniesModel model = mDateSet.get(pos);
mContext.startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getTitle())
.putExtra("categoryID", model.getId()));
Toast.makeText(mContext, " " + model.getId(), Toast.LENGTH_SHORT).show();
}
});
...
Category_page code:
public class Category_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private TextView toolbar_title;
private ImageView toolbar_menuImage;
private RelativeLayout root;
private CategoryAdapter mAdapter;
private RecyclerView cat_recyclerView;
private LinearLayoutManager mLayoutManager;
private RelativeLayout loadLayout;
private String catTitle = "";
private Integer catID;
private Bundle bundle;
private int pageCount = 1;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_page);
//if (!EventBus.getDefault().isRegistered(this)) {
// EventBus.getDefault().register(this);
//}
// Hide StatusBar color
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
// Initializing
context = Category_page.this;
toolbar = (Toolbar) findViewById(R.id.category_toolbar);
cat_recyclerView = (RecyclerView) findViewById(R.id.category_recycler);
toolbar_title = (TextView) toolbar.findViewById(R.id.toolbar_pages_title);
mLayoutManager = new LinearLayoutManager(this);
root = (RelativeLayout) findViewById(R.id.category_root);
loadLayout = (RelativeLayout) findViewById(R.id.category_empty_layout);
// Toolbar
setSupportActionBar(toolbar);
if (toolbar != null) {
getSupportActionBar().setTitle("");
}
// Receive Data
bundle = getIntent().getExtras();
catID = bundle.getInt("categoryID");
if (bundle != null) {
catTitle = bundle.getString("categoryTitle");
}
if (catTitle != null) {
toolbar_title.setText(catTitle);
}
// Load data
//LoadData(catID);
// Menu
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
toolbar_menuImage = (ImageView) toolbar.findViewById(R.id.toolbar_pages_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView
cat_recyclerView.setLayoutManager(mLayoutManager);
cat_recyclerView.setHasFixedSize(true);
// Retrofit //////////
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);
call.enqueue(new Callback<R_CatModelResponse>() {
#Override
public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
List<R_CatModel> models = response.body().getCat_posts();
mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
cat_recyclerView.setAdapter(mAdapter);
Toast.makeText(Category_page.this, "Response", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
Toast.makeText(Category_page.this, "Error", Toast.LENGTH_SHORT).show();
}
});
I send category_id with below code from one adapter :
mContext.startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getTitle())
.putExtra("categoryID", model.getId()));
and receive this data with below code :
// Receive Data
bundle = getIntent().getExtras();
catID = bundle.getInt("categoryID");
But Error message (Toast) instead of category posts!
show error toast from :
#Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
Toast.makeText(Category_page.this, "Error", Toast.LENGTH_SHORT).show();
}
Update :
This is the error I get, :
E/CatResponseError: Error : com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 48 path $.category
Update #2 :
Added my POJO class :
public class R_CatModelResponse {
#SerializedName("status")
public String Cat_status;
#SerializedName("count")
public int Cat_count;
#SerializedName("pages")
public int Cat_pages;
#SerializedName("category")
public List<Retrofit_ColoniesModel> category;
#SerializedName("posts")
public List<R_CatModel> Cat_posts;
public String getCat_status() {
return Cat_status;
}
public void setCat_status(String cat_status) {
Cat_status = cat_status;
}
public int getCat_count() {
return Cat_count;
}
public void setCat_count(int cat_count) {
Cat_count = cat_count;
}
public int getCat_pages() {
return Cat_pages;
}
public void setCat_pages(int cat_pages) {
Cat_pages = cat_pages;
}
public List<Retrofit_ColoniesModel> getCategory() {
return category;
}
public void setCategory(List<Retrofit_ColoniesModel> category) {
this.category = category;
}
public List<R_CatModel> getCat_posts() {
return Cat_posts;
}
public void setCat_posts(List<R_CatModel> cat_posts) {
Cat_posts = cat_posts;
}
}
How can I fix this?
Please help me. Thanks in advance.
See this pattern which make your life easier:D, based on that use following structure:
Your data model should be:
public class Model {
String status;
int count;
int page;
Category category;
List<Post> posts;
// implement rest of thing
public class Category{
int id;
String slug;
String title;
String description;
int parent;
int post_count;
}
public class Post {
int id;
String type;
String slug;
//..rest of thing
}
}
Your service interface should be:
public interface IService {
#GET("/tafrihgah/?json=get_category_posts")
Call<Model> getCategoryPost(
#Query("id") String id
//...other query if you need should added like below
#Query("categorySlug") String categorySlug,
#Query("tag") String tag,
);
}
And your ServiceHelper contains following method:
public Call<CategoryModel> getAllCategory() {
return service.getCateogryPost();
}
And your error cause your POJO is not fitted to server Model. Double check your Model and make sure Object instead of List/Array;
In your case instead of List<Retrofit_ColoniesModel> category use Retrofit_ColoniesModel category;

Categories

Resources