i created checkoutpage then it contain total,payment due and payment balance. If give total it show the payment due amount & payment balance amount in mobile app. But it doesn't update the browser?
public class FinalCheckOutActivity extends Activity implements View.OnClickListener {
private AQuery mAQuery;
private TransparentProgressDialog mTransparentProgressDialog;
private String mStrCheckOut = "", mStrGEtData = "", mStrAddressData = "", mStrPaypAl = "";
private Spinner mSpnDefualtAddress, mSpnShipAddress;
private Button mBtnPlaceOrder;
private CheckBox mChBxSameAddres, mChkBxDiffAddress, mChkBoxAccept;
private RadioButton mRdoPayPal, mRdoCash;
private RadioGroup mRdoGroupPay;
private ImageView mIvBack;
private TextView mTvAddAddress, mTvSubTot, mTvDiscount, mTVGrandTot, mTvPendingAmt, mTvPayNow, mIvAddAddress;
private ArrayList<SpinnerData> mArrayListAddres;
private LinearLayout mLinearLayoutShiipingMethod, mLinearLayoutPayMethod, mLinearLayoutOrderDetails;
private RadioGroup mRbnOptionshippingmethods;
private ArrayList<UserAddressData> mArrayListshippingMethod;
private ArrayList<UserAddressData> mArrayListPaymentMethods;
private String shippingMethodId;
private RadioGroup mRbnOptionPaymentMethods;
private String shippingPaymentID;
private View viewOrderData;
private JSONObject mJsonObject, jsonObjectData;
private LinearLayout mLinearLayoutTabShiping;
private RadioButton newRadioButton;
private ArrayList<SpinnerData> mArrayListBilign;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_check_out);
//setUI();
}
private void setUI() {
mAQuery = new AQuery(this);
mTransparentProgressDialog = new TransparentProgressDialog(this, R.drawable.ic_loader_image);
mSpnDefualtAddress = (Spinner) findViewById(R.id.spn_default_address);
mSpnShipAddress = (Spinner) findViewById(R.id.spn_ship_address);
mBtnPlaceOrder = (Button) findViewById(R.id.btn_place_order);
mRdoGroupPay = (RadioGroup) findViewById(R.id.rdo_payment);
mRdoCash = (RadioButton) findViewById(R.id.rdo_cash);
mRdoPayPal = (RadioButton) findViewById(R.id.rdo_paypal);
mLinearLayoutTabShiping = (LinearLayout) findViewById(R.id.layout_shiping);
mChBxSameAddres = (CheckBox) findViewById(R.id.chk_ship_to_same_address);
mChkBxDiffAddress = (CheckBox) findViewById(R.id.chk_diff_ship_address);
mChkBoxAccept = (CheckBox) findViewById(R.id.chk_acceept);
mLinearLayoutShiipingMethod = (LinearLayout) findViewById(R.id.layout_shipping_method);
mLinearLayoutPayMethod = (LinearLayout) findViewById(R.id.layout_payment_method);
mLinearLayoutOrderDetails = (LinearLayout) findViewById(R.id.lv_shipping_order_view);
mIvAddAddress = (TextView) findViewById(R.id.img_add_address);
mTvSubTot = (TextView) findViewById(R.id.tv_subtotal);
mTvDiscount = (TextView) findViewById(R.id.tv_discount);
mTVGrandTot = (TextView) findViewById(R.id.tv_grand_tot);
mTvPendingAmt = (TextView) findViewById(R.id.tv_pending_pay);
mTvPayNow = (TextView) findViewById(R.id.tv_payable_now);
mIvBack = (ImageView) findViewById(R.id.img_back_one_page);
mArrayListAddres = new ArrayList<>();
mArrayListshippingMethod = new ArrayList<>();
mArrayListPaymentMethods = new ArrayList<>();
mArrayListBilign = new ArrayList<>();
mBtnPlaceOrder.setOnClickListener(this);
mIvAddAddress.setOnClickListener(this);
// mTvAddAddress.setOnClickListener(this);
mIvBack.setOnClickListener(this);
ajaxCallback.setTimeout(Integer.parseInt(getString(R.string.ajax_timeout)));
mChBxSameAddres.setChecked(true);
mLinearLayoutTabShiping.setVisibility(View.GONE);
mChBxSameAddres.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mLinearLayoutTabShiping.setVisibility(View.GONE);
//mSpnShipAddress.setVisibility(View.GONE);
// perform logic
}
}
});
mChkBxDiffAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mChBxSameAddres.setChecked(false);
mLinearLayoutTabShiping.setVisibility(View.VISIBLE);
}
}
});
SpinnerData data = new SpinnerData();
data.setmStrName("Select Address");
mArrayListAddres.add(data);
mSpnDefualtAddress.setAdapter(new SpinnerAdapter(this, mArrayListAddres));
getFinalCheckOutData();
}
#Override
protected void onResume() {
super.onResume();
setUI();
//getAddressData();
}
/**
* get user address web service call
**/
private void getAddressData() {
mStrAddressData = getString(R.string.WS_HOST) + getString(R.string.WS_GET_MULTIPLE_ADDRESS);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("customer_id", SessionClass.getUserId(this));
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrAddressData, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* get user address web service call
**/
private void getPaypalData() {
mStrPaypAl = getString(R.string.WS_HOST) + getString(R.string.WS_PAYPAL);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("order_increment_id", orderID);
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrPaypAl, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* Get final checkout data
**/
private void getFinalCheckOutData() {
mStrGEtData = getString(R.string.WS_HOST) + getString(R.string.WS_FINAL_CHECKOUT_DETAIls);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cart_id", IntermediateCheckoutActivity.cartId);
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrGEtData, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* Place order web service call
**/
private void placeOrder() {
mStrCheckOut = getString(R.string.WS_HOST) + getString(R.string.WS_PLACE_ORDER);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cart_id", IntermediateCheckoutActivity.cartId);
hashMap.put("checkoutdetails", jsonObjectData.toString());
Log.e("Place order", "hash map-->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrCheckOut, hashMap, JSONObject.class, ajaxCallback);
} else {
//showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
private boolean checkValidationn() {
if (mSpnDefualtAddress.getSelectedItemPosition() == 0) {
showAlert("Please select billing address first.", -1);
mSpnDefualtAddress.requestFocus();
return false;
} else if (mRbnOptionshippingmethods.getCheckedRadioButtonId() == -1) {
showAlert("Please select shipping method first.", -1);
mRbnOptionshippingmethods.requestFocus();
return false;
} else if (mRdoGroupPay.getCheckedRadioButtonId() == -1) {
showAlert("Please select payment method first.", -1);
mRdoGroupPay.requestFocus();
return false;
} else if (!mChkBoxAccept.isChecked()) {
showAlert("Please select terms and conditions first.", -1);
mChkBoxAccept.requestFocus();
return false;
}
return true;
}
private void showAlert(String message, final int flg) {
AlertDialog.Builder aBuilder = new AlertDialog.Builder(this);
aBuilder.setCancelable(false);
aBuilder.setMessage(message);
aBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setNxtFlg(flg);
}
});
aBuilder.create();
aBuilder.show();
}
private void setNxtFlg(int flg) {
switch (flg) {
case 3:
Intent intent = new Intent(FinalCheckOutActivity.this, PayPalPaymentActivity.class);
intent.putExtra("key", urlMain);
intent.putExtra("order_id", orderID);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(FinalCheckOutActivity.this, MainActivity.class);
intent1.putExtra("key", "4");
startActivity(intent1);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
}
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.btn_place_order:
getCheckOutData();
if (checkValidationn()) {
placeOrder();
}
break;
case R.id.img_back_one_page:
onBackPressed();
//finish();
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
case R.id.img_add_address:
intent = new Intent(FinalCheckOutActivity.this, CheckoutActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
/*case R.id.txt_add_address:
intent = new Intent(FinalCheckOutActivity.this, AddUserAddressActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
//finish();
break;*/
}
}
private void getCheckOutData() {
mJsonObject = new JSONObject();
jsonObjectData = new JSONObject();
try {
if (mChBxSameAddres.isChecked()) {
jsonObjectData.put("billing_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
} else {
// jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnShipAddress.getSelectedItemPosition()).getmStrId());
}
if (mChkBxDiffAddress.isChecked()) {
jsonObjectData.put("billing_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnShipAddress.getSelectedItemPosition()).getmStrId());
} else {
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
}
JSONObject mJsonObjectPay = new JSONObject();
if (mRdoCash.isChecked()) {
shippingPaymentID = "checkmo";
mJsonObjectPay.put("method", shippingPaymentID);
} else if (mRdoPayPal.isChecked()) {
shippingPaymentID = "paypaladaptive";
mJsonObjectPay.put("method", shippingPaymentID);
}
jsonObjectData.put("payment", mJsonObjectPay);
jsonObjectData.put("shipping_method", shippingMethodId);
jsonObjectData.put("checkout_method", "customer");
jsonObjectData.put("onestepcheckout_feedback_freetext", "");
jsonObjectData.put("accept_terms", 1);
jsonObjectData.put("customer_id", SessionClass.getUserId(FinalCheckOutActivity.this));
mJsonObject.put("checkoutdetails", jsonObjectData);
//showAlert("place order array" + jsonObjectData.toString(), -1);
//Log.e("Place order", "Data-->" + jsonObjectData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
private String orderID;
private String urlMain;
/**
* web service responce
**/
AjaxCallback<JSONObject> ajaxCallback = new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
super.callback(url, object, status);
Log.e("Check out", "Url-->" + url);
Log.e("Check out", "Responce-->" + object);
if (object != null) {
if (status.getCode() == 200) {
if (mTransparentProgressDialog.isShowing()) {
mTransparentProgressDialog.dismiss();
}
if (url.equalsIgnoreCase(mStrAddressData)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
setAddressData(object.getJSONArray("data"));
//getFinalCheckOutData();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrGEtData)) {
try {
String now = getIntent().getExtras().getString("pay_now");
String due = getIntent().getExtras().getString("pay_due");
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject mJsonObject = object.getJSONObject("data");
setShippingMethods(mJsonObject.getJSONArray("shippingmethods"));
setPaymentMethods(mJsonObject.getJSONArray("paymentmethods"));
if (!mJsonObject.isNull("items")) {
setOrderView(mJsonObject.getJSONArray("items"));
}
mTvSubTot.setText(mJsonObject.getString("subtotal"));
mTvDiscount.setText(mJsonObject.getString("discount"));
mTVGrandTot.setText(mJsonObject.getString("grandtotal"));
// mTvPendingAmt.setText(mJsonObject.getString("pendingpayment"));
// mTvPayNow.setText(mJsonObject.getString("payablenow"));
mTvPendingAmt.setText(now);
mTvPayNow.setText(due);
getAddressData();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrCheckOut)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
//showAlert("Your order placed successfully.", -1);
if (shippingPaymentID.equalsIgnoreCase("paypaladaptive")) {
JSONObject mJsonObject = object.getJSONObject("data");
orderID = mJsonObject.getString("order_increment_id");
getPaypalData();
} else {
showAlert("Your order placed successfully.", 1);
}
//SessionClass.logout(FinalCheckOutActivity.this);
SessionClass.setUrerCartId(FinalCheckOutActivity.this, "");
} else if (object.getString("errorcode").equalsIgnoreCase("1")) {
showAlert("There is error in order creation.", -1);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrPaypAl)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject mJsonObject = object.getJSONObject("data");
urlMain = mJsonObject.getString("url").replace("/\\/", "");
Log.e("Final url", "Url-->" + urlMain);
showAlert("Click on ok to continue.", 3);
} else if (object.getString("errorcode").equalsIgnoreCase("2")) {
showAlert("Paypal API call failed. Account not found. Unilateral receiver not allowed in chained payment is restricted.", -1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
// showAlert(getString(R.string.no_connection_server), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_connection_server, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
}
};
/**
* Set order view data from web servicie responce
**/
private void setOrderView(JSONArray items) {
try {
mLinearLayoutOrderDetails.removeAllViews();
//mArrayListMethod.clear();
for (int i = 0; i < items.length(); i++) {
JSONObject mJsonObject = items.getJSONObject(i);
viewOrderData = getLayoutInflater().inflate(R.layout.single_chkout_order_listing, null);
TextView mTvName = (TextView) viewOrderData.findViewById(R.id.tv_order_name);
TextView mTvPrice = (TextView) viewOrderData.findViewById(R.id.tv_order_price);
TextView mTvQuan = (TextView) viewOrderData.findViewById(R.id.tv_order_quantity);
TextView mTvSubTot = (TextView) viewOrderData.findViewById(R.id.tv_order_sub_total);
mTvName.setText(mJsonObject.getString("name"));
mTvPrice.setText(mJsonObject.getString("price"));
mTvQuan.setText(mJsonObject.getString("quantity"));
mTvSubTot.setText(mJsonObject.getString("rowtotal"));
mLinearLayoutOrderDetails.addView(viewOrderData);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I am developing Android app which obtains information about restaurants from server and shows them in RecyclerView. When first package of information is obtained from server, everything works as expected, but, when I change search criteria and request new package of information from server, RecyclerView becomes blank. I used Toasts to debug what is coming from server and I am convinced that data is properly formatted. Also, variables that are used for accepting the data are also properly handled in code, according to my observations. Do you maybe know why my RecyclerView is empty when second package of data should be shown? Here is the code.
AfterLoginActivity.java
public class AfterLoginActivity extends AppCompatActivity {
/* interface main elements */
LinearLayout afterLoginLayout;
LinearLayout restaurantListLayout;
EditText restaurantEditText;
Button findRestaurantButton;
LoadingDialog loadingDialog;
AlphaAnimation loadingAnimation;
RecyclerView restaurantsRecyclerView;
int recycler_set = 0;
Button signOutButton;
GoogleSignInClient mGoogleSignInClient;
MyAdapter myAdapter = null;
/* server-client communication data */
public static String UploadUrl = "https://gdedakliknem.com/klopator.php";
public static String[] received;
String restaurants[] = new String[40];
String logos_as_strings[] = new String[40];
Bitmap logos[] = new Bitmap[40];
int num_of_elements = 0;
int data_received = 0;
/* user data */
String person_email;
String person_name;
String restaurant;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
/* interface main elements */
afterLoginLayout = findViewById(R.id.afterLoginLayout);
restaurantListLayout = findViewById(R.id.restaurantListLayout);
restaurantEditText = findViewById(R.id.restaurantEditText);
findRestaurantButton = findViewById(R.id.findRestaurantButton);
restaurantsRecyclerView = findViewById(R.id.restaurantsRecyclerView);
signOutButton = findViewById(R.id.signOutButton);
loadingAnimation = new AlphaAnimation(1F, 0.8F);
loadingDialog = new LoadingDialog(AfterLoginActivity.this);
/* UPDATING INTERFACE ELEMENTS */
/* execution thread */
final Handler handler = new Handler();
final int delay = 2000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
/* check if recycler view is set */
if(recycler_set == 0){
/* if not, check if there is data to fil it with */
if(data_received == 1){
/* convert received strings to images */
for(int i = 0; i < num_of_elements; i++){
logos[i] = stringToBitmap(logos_as_strings[i]);
}
/* fill interface elements */
loadingDialog.dismissDialog();
myAdapter = new MyAdapter(AfterLoginActivity.this, restaurants, logos, num_of_elements);
restaurantsRecyclerView.setAdapter(myAdapter);
restaurantsRecyclerView.setLayoutManager(new LinearLayoutManager(AfterLoginActivity.this));
afterLoginLayout.setVisibility(View.GONE);
restaurantListLayout.setVisibility(View.VISIBLE);
recycler_set = 1;
}
}
handler.postDelayed(this, delay);
}
}, delay);
/* catch restaurant name from user's entry */
findRestaurantButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
restaurant = restaurantEditText.getText().toString();
if(!restaurant.isEmpty()){
view.startAnimation(loadingAnimation);
loadingDialog.startLoadingDialog();
sendRequest();
} else{
Toast.makeText(AfterLoginActivity.this, "Unesite naziv restorana!", Toast.LENGTH_LONG).show();
}
}
});
/* enable signing out */
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.signOutButton:
signOut();
break;
}
}
});
/* obtaining email */
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null) {
person_email = acct.getEmail();
person_name = acct.getDisplayName();
}
}
#Override
public void onBackPressed() {
afterLoginLayout.setVisibility(View.VISIBLE);
restaurantsRecyclerView.setVisibility(View.GONE);
data_received = 0;
recycler_set = 0;
}
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AfterLoginActivity.this, "Signed out", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void sendRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, UploadUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if (Response.equals("Restaurant not found")){
loadingDialog.dismissDialog();
Toast.makeText(getApplicationContext(), "Uneti restoran ne postoji u sistemu! Proverite da li ste dobro napisali naziv", Toast.LENGTH_LONG).show();
} else{
received = Response.split(";");
if (received.length > 0){
data_received = 1;
num_of_elements = received.length / 2;
//Toast.makeText(getApplicationContext(), "num of elements: " + num_of_elements, Toast.LENGTH_LONG).show();
for(int i = 0; i < num_of_elements; i++){
logos_as_strings[i] = received[i*2];
restaurants[i] = received[i*2+1];
//Toast.makeText(getApplicationContext(), "restaurants: " + restaurants, Toast.LENGTH_LONG).show();
}
} else{
loadingDialog.dismissDialog();
Toast.makeText(getApplicationContext(), "Greška u prijemu", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(final VolleyError error) {
//volleyError = error;
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Toast.makeText(getApplicationContext(), "get params", Toast.LENGTH_LONG).show();
Map<String, String> params = new HashMap<>();
params.put("control", "find_restaurant");
params.put("restaurant", restaurant);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(AfterLoginActivity.this);
requestQueue.add(stringRequest);
}
public static Bitmap stringToBitmap(String encodedString) {
try {
byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
} catch (Exception e) {
e.getMessage();
return null;
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
String restaurants[];
Bitmap logos[];
Context context;
int num_of_elements;
public MyAdapter(Context ct, String rests[], Bitmap lgs[], int num){
context = ct;
restaurants = rests;
logos = lgs;
num_of_elements = num;
Toast.makeText(context, Integer.toString(restaurants.length), Toast.LENGTH_LONG).show();
for(int i = 0; i < restaurants.length; i++){
Toast.makeText(context, restaurants[i], Toast.LENGTH_SHORT).show();
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.restaurant_item_layout, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
holder.restaurantNameTextView.setText(restaurants[position]);
holder.restaurantLogoImageView.setImageBitmap(logos[position]);
holder.restaurantItemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AfterPickingRestaurantActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
logos[position].compress(Bitmap.CompressFormat.PNG, 50, bs);
intent.putExtra("byteArray", bs.toByteArray());
intent.putExtra("picked_restaurant_name", restaurants[position]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
/*
int i = 0;
if (restaurants != null){
while(restaurants[i] != null){
i++;
}
} else{
i = restaurants.length;
}
return i;
*/
return num_of_elements;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView restaurantNameTextView;
ImageView restaurantLogoImageView;
LinearLayout restaurantItemLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
restaurantNameTextView = itemView.findViewById(R.id.restaurantNameTextView);
restaurantLogoImageView = itemView.findViewById(R.id.restaurantLogoImageView);
restaurantItemLayout = itemView.findViewById(R.id.restaurantItemLayout);
}
}
Add this lines after getting new data
myAdapter.notifyDataSetChanged()
Your Adapter Already set with RecyclerView in OnCreate Method.
so when'er you click on findRestaurantButton you just get Resturent data from server but collected data not pass in adapter so thats why to getting blank adapter..
Just put this line in your onResponse after set data in array..
myAdapter.notifyDataSetChanged()
I found out where is the mistake. If you take a look at the section where overriding of back button click is happening, I by mistake set to GONE recyclerView itself:
restaurantsRecyclerView.setVisibility(View.GONE);
instead of LinearLayout in which recyclerView is contained. Desired action was:
restaurantListLayout.setVisibility(View.GONE);
P.S. Everything works without calling notifyDataSetChanged(), I just create a new instance of myAdapater each time when I receive new data. I hope Garbage Collector is doing its job :)
Thanks everyone on help!
I want to pass an ArrayList to my fragment from my activity that is accessed through the bottom navigation bar, the bundle returns null when I call getInt() or getParcelableArrayList()
EDIT: pasted whole files, in hope that will help... + put the bundle in on create(didn't help)
Code:
main activity(where it's sent)
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
private AdView mAdView;
private boolean isAdsRemoved;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private List<AppListModel> list = new ArrayList<>();
private int totalUsage = 0;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!checkForPermission(this)) {
startActivity(new Intent(this, CheckForPermissionActivity.class));
finish();
}
long startTime = System.currentTimeMillis() - 86400000;
long endTime = System.currentTimeMillis();
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService("usagestats");
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
for (UsageStats us : queryUsageStats) {
Drawable icon;
int totalTimeMin = (int) us.getTotalTimeInForeground() / 60000;
boolean alreadyThere = false;
PackageManager pm = getPackageManager();
ApplicationInfo ai;
if (us.getPackageName().equals("com.android.systemui")) {
continue;
}
try {
ai = pm.getApplicationInfo(us.getPackageName(), 0);
icon = getPackageManager().getApplicationIcon(us.getPackageName());
} catch (PackageManager.NameNotFoundException e) {
ai = null;
icon = null;
Log.d(TAG, "Package name not found");
e.printStackTrace();
}
String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
if (applicationName.length() > 15) {
applicationName = applicationName.substring(0, Math.min(applicationName.length(), 13)) + "...";
}
//if packages that have the same names, but are registered multiple times, they are merged
if (list.size() > 0) {
for (AppListModel item : list) {
if (item.getAppName().equals(applicationName)) {
item.setTotalTime(totalTimeMin + item.getTotalTime());
totalUsage += totalTimeMin;
alreadyThere = true;
}
}
}
if (totalTimeMin > 0 && !alreadyThere) {
if (!applicationName.equals("(unknown)")) {
list.add(new AppListModel(applicationName, icon, totalTimeMin));
}
Log.d(TAG, us.getPackageName() + " = " + us.getTotalTimeInForeground());
totalUsage += totalTimeMin;
}
}
preferences = getSharedPreferences("label", 0);
if (preferences.getBoolean("ad_removed", false)) {
isAdsRemoved = true;
}
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (preferences.getBoolean("ad_removed", false)) {
mAdView.setVisibility(View.GONE);
}
if (!preferences.getBoolean("ad_removed", false) && !isAdsRemoved) {
Intent intent = getIntent();
isAdsRemoved = intent.getBooleanExtra("ad_removal", false);
}
editor = preferences.edit();
editor.putBoolean("ad_removed", isAdsRemoved).commit();
bottomNavigationView = findViewById(R.id.bottomNavigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
bottomNavigationView.setSelectedItemId(R.id.itemDashboard);
Fragment dashboard = new FragmentDashboard();
ArrayList<AppListModel> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);
Bundle bundle = new Bundle();
bundle.putInt("totalUsage", totalUsage);
bundle.putParcelableArrayList("arrayList", arrayList);
dashboard.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, dashboard).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.itemStats:
selectedFragment = new FragmentStats();
break;
case R.id.itemDashboard:
selectedFragment = new FragmentDashboard();
break;
case R.id.itemStore:
selectedFragment = new FragmentStore();
break;
case R.id.itemSettings:
selectedFragment = new FragmentSettings();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, selectedFragment).commit();
return true;
}
};
private boolean checkForPermission(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return (mode == AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
}
FragmentDashboard
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//View itself
view = inflater.inflate(R.layout.fragment_dashboard, container, false);
//'TIME WASTED' counter
count = view.findViewById(R.id.mainFragmentText);
//RecyclerView
recyclerView = view.findViewById(R.id.recyclerView);
//Buttons
showAllBtn = view.findViewById(R.id.showAllButton);
hideBtn = view.findViewById(R.id.hideAllButton);
timeNotifBtn = view.findViewById(R.id.timeButton);
stopLimiterButton = view.findViewById(R.id.disableLimit);
list = getArguments().getParcelableArrayList("arrayList");
totalUsage = getArguments().getInt("totalUsage", 0);
int totalUsageHrs = (int) totalUsage / 60;
int totalUsageMin = (int) totalUsage - totalUsageHrs * 60;
if (totalUsageHrs == 0) {
count.setText(totalUsageMin + " minutes");
} else {
count.setText(totalUsageHrs + " hours, " + totalUsageMin + " minutes");
}
//sorts list in descending order
Collections.sort(list, new Comparator<AppListModel>() {
#Override
public int compare(AppListModel appListModel, AppListModel t1) {
return Integer.valueOf(t1.getTotalTime()).compareTo(Integer.valueOf(appListModel.getTotalTime()));
}
});
mostUsedApps = list.subList(0, Math.min(list.size(), 3));
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(mostUsedApps);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(list);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setVisibility(View.INVISIBLE);
hideBtn.setVisibility(View.VISIBLE);
}
});
hideBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hideBtn.setVisibility(View.GONE);
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(mostUsedApps);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setVisibility(View.VISIBLE);
hideBtn.setVisibility(View.INVISIBLE);
}
});
timeNotifBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (totalUsage > 720) {
Toast.makeText(getActivity(), "Take a break, you have spent too much on your phone", Toast.LENGTH_SHORT).show();
} else {
DialogDashboard dialogDashboard = new DialogDashboard();
dialogDashboard.show(getChildFragmentManager(), "notif_dialog");
}
}
});
stopLimiterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isJobServiceOn(getActivity())) {
JobScheduler scheduler = (JobScheduler) getActivity().getSystemService(Context.JOB_SCHEDULER_SERVICE);
scheduler.cancel(JOB_ID);
} else {
Toast.makeText(getActivity(), "No limit set", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getParcelableArrayList(java.lang.String)' on a null object reference
at com.example.dashboard.FragmentDashboard.onCreateView(FragmentDashboard.java:78)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1395)
at android.app.Activity.performStart(Activity.java:7348)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3145)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7078)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
EDIT 2, I fixed the problem, I just put the bundle in both onCreate and onMenuItemSelected
case R.id.itemStats:
selectedFragment = new FragmentDashboard();
ArrayList<AppListModel> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);
Bundle bundle = new Bundle();
bundle.putInt("totalUsage", totalUsage);
bundle.putParcelableArrayList("arrayList", arrayList);
selectedFragment.setArguments(bundle);
break;
case R.id.itemDashboard:
selectedFragment = new FragmentDashboard();
break;
In this part of your code you instantiate FragmentDashboard in two case statement which in second one you did not pass any bundle as arguments and because this you get error when you call getArguments().get... in it.
You only set the arguments on your FragmentStats instance. Other fragments such as the FragmentDashboard seen in the stacktrace don't have arguments set, and getArguments() returns null.
If you want the same arguments to be applied to all fragments, move the Bundle setup and setArguments() after the switch-case. (And maybe add a default case too so selectedFragment won't ever be null.)
I have an activity in which I have used Recycle View to show all items as a list. On same activity I have given functionality to add new item. Everything is working fine. Items are adding in my database and its showing in list. I have added pagination on Recycle View it is also working fine. What I want that when user add new item at the same time when new data added to database but it is not updating in list. When user press back and again come on activity after that it is showing in list. I want to add add new item at same time without scroll the list or without go back.
TimelineActivity.java
public class TimelineActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private TimeLineListAdapter listAdapter;
private List<TimeLineItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
btnPost = (Button) findViewById(R.id.btnPost);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
/*pref = getApplicationContext().getSharedPreferences("MayahudiPref", 0);
editor = pref.edit();*/
buttonClickEvent();
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new TimeLineListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
getTimeLineData(token, "1");
}
});
}
}, 0, 2000);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
if (image.equals("")) {
item.setImge(image);
} else {
item.setImge(AppConfig.storyPic + image);
}
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(AppConfig.profilePic + feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
//This method will get data from the web API
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
public void buttonClickEvent() {
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isInternetPresent) {
String text = txtStatusBox.getText().toString().trim();
if (!text.isEmpty()) {
if (thumbnail != null) {
String image = getStringImage(thumbnail);
JSONObject student2 = new JSONObject();
try {
student2.put("size", "1000");
student2.put("type", "image/jpeg");
student2.put("data", image);
} catch (JSONException e) {
e.printStackTrace();
}
addStory(text, token, String.valueOf(student2));
} else {
addStory(text, token, "");
}
} else {
Toast.makeText(TimelineActivity.this, "Please add some text or image.", Toast.LENGTH_SHORT).show();
}
} else {
final SweetAlertDialog alert = new SweetAlertDialog(TimelineActivity.this, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
});
imgImageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
/*fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialogFragment.show(getFragmentManager(), "MyDialogFragment");
//Toast.makeText(TimelineActivity.this, "Floating Button", Toast.LENGTH_SHORT).show();
}
});*/
}
private void addStory(final String story_text, final String token, final String image) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.addStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(TimelineActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TimelineActivity.this, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_text", story_text);
params.put("image", image);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
TimeLineListAdapter.java
public class TimeLineListAdapter extends RecyclerView.Adapter<TimeLineListAdapter.ViewHolder> {
private List<TimeLineItem> timeLineItems;
String message, storyId, token;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TimeLineListAdapter(List<TimeLineItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
TimeLineItem item = timeLineItems.get(position);
if (item.getTotalLikes().equals("0")){
holder.txtLike.setText("");
}else {
holder.txtLike.setText(item.getTotalLikes());
}
if (item.getTotalComment().equals("0")){
holder.txtComment.setText("");
}else {
holder.txtComment.setText("("+item.getTotalComment()+")");
}
if (item.getIsLike() == 0){
}else {
holder.imageLike.setImageBitmap(null);
holder.imageLike.setBackgroundResource(R.drawable.islike);
holder.txtLike.setTextColor(Color.parseColor("#3498db"));
}
holder.name.setText(item.getName() + " " + item.getLname());
/*Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getTimeStamp());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new TimeLineImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name, timestamp, statusMsg, url, txtLike, txtComment, txtCommentLabel;
NetworkImageView profilePic;
TimeLineImageView feedImageView;
ImageView imageLike;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (TimeLineImageView) itemView.findViewById(R.id.feedImage1);
imageLike = (ImageView) itemView.findViewById(R.id.imgLike);
txtLike = (TextView) itemView.findViewById(R.id.txtLike);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtCommentLabel = (TextView) itemView.findViewById(R.id.txtCommentLabel);
}
}
You have to notifiy dataset changed on listview when new feed is added so there are two things you can do :
Create a new TimeLineItem item when new feed is entered and add new item to it like this :
`
item.setStatus("New Status");
item.setProfilePic("New Profile Pic");
item.setTimeStamp("New TimeStamp");
item.setIsLike("True");
item.setTotalLikes("1000");
item.setTotalComment("2");
`
and then use timeLineItems.add(item) to add new item to ArrayList and call adapter.notifyDataSetChanged(); to get it in view .
2. Again create volley request and it will do it automatically but this is slower then above example.
If you have any query please ask .
You have to set this new list to the adapter.
You can create a setDataSet() method in your adapter and call it before notifydatasetchanged
Add below method in adapter
public void setDataSet(List<TimeLineItem> timeLineItems) {
this.timeLineItems = timeLineItems;
}
and call it before notifydatasetChanged like this:
adapter.setDataSet(timeLineItems);
adapter.notifyDataSetChanged();
public class mychatorderdetails extends ActionBarActivity {
private MyApplication app;
private String order_id;
private String orderdate;
private String cust_name;
private String cust_address;
private String cust_pincode;
private String cust_mobile;
private String action;
private String UPI;
private Button bt;
private OrderDetailsAdapter oa;
private ListView lv;
private ArrayList<HashMap<String, String>> messageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mychatorderdetails);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
messageList = new ArrayList<HashMap<String, String>>();
app=((MyApplication) getApplicationContext());
Bundle extras = getIntent().getExtras();
if(extras != null) {
order_id = extras.getString("order_id");
orderdate = extras.getString("orderdate");
cust_name = extras.getString("cust_name");
cust_address = extras.getString("cust_address");
cust_pincode = extras.getString("cust_pincode");
cust_mobile=extras.getString("cust_mobile");
UPI=extras.getString("UPI");
action=extras.getString("action"); //setaccepted, setdelivered
}
bt = (Button) findViewById(R.id.btnAction);
switch (action)
{
case "setdelivered":{
bt.setText("Delivered");
break;
}
case "setaccepted":{
bt.setText("Accept");
break;
}
default:
}
try {
String dpart = orderdate.substring(0, 10);
String tpart = orderdate.substring(11, 19);
orderdate = dpart.substring(8,10);
orderdate+="/"+dpart.substring(5,7);
orderdate+="/"+dpart.substring(0,4);
orderdate+=" "+tpart;
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
HashMap<String, String> row = new HashMap<String, String>();
row.put("type", "text");
row.put("details", "Order ID:"+order_id);
messageList.add(row);
HashMap<String, String> rowd = new HashMap<String, String>();
rowd.put("type", "text");
rowd.put("details", "Order Date:"+orderdate);
messageList.add(rowd);
HashMap<String, String> row1 = new HashMap<String, String>();
row1.put("type", "text");
row1.put("details",cust_name);
messageList.add(row1);
HashMap<String, String> row2 = new HashMap<String, String>();
row2.put("type", "text");
row2.put("details",cust_address);
messageList.add(row2);
HashMap<String, String> row3 = new HashMap<String, String>();
row3.put("type", "text");
row3.put("details","Pin:"+cust_pincode);
messageList.add(row3);
HashMap<String, String> row4 = new HashMap<String, String>();
row4.put("type", "text");
row4.put("details","Mob:"+cust_mobile);
messageList.add(row4);
HashMap<String, String> row5 = new HashMap<String, String>();
row5.put("type", "text");
row5.put("details","UPI:"+UPI);
messageList.add(row5);
oa=new OrderDetailsAdapter(mychatorderdetails.this,messageList);
lv = (ListView) findViewById(R.id.lstOrderDetails);
lv.setAdapter(oa);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
HashMap<String, String> temp = new HashMap<String, String>();
temp = messageList.get(position);
if(temp.get("type")=="image")
{
//Uri uri = Uri.parse(temp.get("details"));
showImage(temp.get("details"));
}
} catch (Exception e) {
Log.d(getString(R.string.app_name), e.getMessage());
}
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray det = app.getMyChatOrderDetails(order_id);
for (int i = 0; i < det.length(); i++) {
JSONObject cat = det.getJSONObject(i);
HashMap<String, String> row = new HashMap<String, String>();
if(!TextUtils.isEmpty(cat.getString("msg_image").toString()))
{
row.put("type", "image");
row.put("details",cat.getString("msg_image").toString());
}
else
{
row.put("type", "text");
String mfv=cat.getString("msg_for_vendor").toString();
if(mfv.equals("1"))
{
row.put("details","Customer: "+cat.getString("msg_text").toString());
}
else{
row.put("details","Me: "+cat.getString("msg_text").toString());
}
}
messageList.add(row);
}
oa.notifyDataSetChanged();
} catch (JSONException e) {
Log.d(getString(R.string.app_name), e.getMessage());
} catch (Exception e) { //connection timeout
Log.d(getString(R.string.app_name), e.getMessage());
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
public void showImage(String imageUri) {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
try {
ImageView imageView = new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUri).getContent());
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(450, 400);
imageView.setLayoutParams(layoutParams);
imageView.setVisibility(View.VISIBLE);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
}
public void doAction(View v)
{
switch (action)
{
case "setdelivered":{
if(app.setOrderDelivered(order_id)) {
Toast.makeText(this,"Order marked as delivered...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
case "setaccepted":{
if(app.acceptChatOrder(order_id)){
Toast.makeText(this,"Order accepted...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
default:
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mychatorderdetails, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent;
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
app = ((MyApplication) getApplicationContext());
app.logOut();
intent = new Intent(mychatorderdetails.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mychatorderdetails.this.startActivity(intent);
}
mychatorderdetails.this.finish();
return super.onOptionsItemSelected(item);
}
}
Following is the code to display my List ITEMS. I wanted my 5th row item i.e UPI to be enabled copying when long pressed on it. How do I do this? Please edit my code for the same to happen.
Change in layout file: add the below property to your TextView:
android:textIsSelectable="true"
OR
In your Java class write this line to set it programatically:
myTextView.setTextIsSelectable(true);
Copy text:
tv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", tv.getText());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Copied to clipboard", Toast.LENGTH_SHORT).show();
return true;
}
});
Make sure you have imported android.content.ClipboardManager and NOT android.text.ClipboardManager.
In your row_layout for your ListView, just add the property android:textIsSelectable to the TextView on which you want copying to be allowed.
I'm trying to do my first app, I'm self-taught in Java and I started 2 month ago so please forgive my errors.
I want to pass the CheckBoxes values to an email text but I think I need to refresh "something" before sending the email because the values are always false..and I don't know how can I do.
Here is the code:
public class Appuntamento extends Activity{
String paziente;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
final boolean lun = lunedi.isSelected();
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
final boolean mar = martedi.isSelected();
final CheckBox mercoledi = (CheckBox) findViewById(R.id.checkboxMercoledi);
final boolean mer = mercoledi.isSelected();
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
final boolean giov = giovedi.isSelected();
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
final boolean ven = venerdi.isSelected();
StringBuilder testoMail = new StringBuilder();
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
final String giorni = testoMail.toString();
Button richiestaAppuntamento = (Button)findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}
two way you can do this one
like
public class Appuntamento extends Activity
{
String paziente;
boolean lun,mar ,mer,giov,ven;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
final CheckBox mercoledi =(CheckBox)findViewById(R.id.checkboxMercoledi);
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
Button richiestaAppuntamento = (Button) findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ven = venerdi.isChecked();
lun = lunedi.isChecked();
mar = martedi.isChecked();
mer = mercoledi.isChecked();
giov = giovedi.isChecked();
StringBuilder testoMail = new StringBuilder();
//your code this is fine if only one selected item info or data you want to send in mail
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
// if you want all then comment above code and uncomment below code
/*
if (lun ){
testoMail.append("Lunedì");
}
if (mar){
testoMail.append("Martedì");
}
if (mer) {
testoMail.append("Mercoledì");
}
if (giov) {
testoMail.append("Giovedì");
}
if (ven) {
testoMail.append("Venerdì");
}
*/
String giorni = testoMail.toString();
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}
other way is
like
public class Appuntamento extends Activity
{
String paziente;
boolean lun,mar ,mer,giov,ven;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
lunedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
lun=isChecked;
//either one above or below
//lun = lunedi.isChecked();
}
}
);
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
martedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mar=isChecked;
//either one above or below
//mar = martedi.isChecked();
}
}
);
final CheckBox mercoledi =(CheckBox)findViewById(R.id.checkboxMercoledi);
mercoledi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mer=isChecked;
//either one above or below
// mer = mercoledi.isChecked();
}
}
);
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
giovedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
giov=isChecked;
//either one above or below
// giov = giovedi.isChecked();
}
}
);
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
venerdi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
ven=isChecked;
//either one above or below
//ven = venerdi.isChecked();
}
}
);
Button richiestaAppuntamento = (Button) findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ven = venerdi.isChecked();
// lun = lunedi.isChecked();
// mar = martedi.isChecked();
// mer = mercoledi.isChecked();
// giov = giovedi.isChecked();
StringBuilder testoMail = new StringBuilder();
//your code this is fine if only one selected item info or data you want to send in mail
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
// if you want all then comment above code and uncomment below code
/*
if (lun ){
testoMail.append("Lunedì");
}
if (mar){
testoMail.append("Martedì");
}
if (mer) {
testoMail.append("Mercoledì");
}
if (giov) {
testoMail.append("Giovedì");
}
if (ven) {
testoMail.append("Venerdì");
}
*/
String giorni = testoMail.toString();
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}