Java tutorial
package com.annanovas.bestprice; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Base64; import android.util.Log; import android.util.Patterns; import android.util.TypedValue; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.annanovas.bestprice.Adapter.AreaAdapter; import com.annanovas.bestprice.Adapter.ProductAdapter; import com.annanovas.bestprice.Utils.AppGlobal; import com.annanovas.bestprice.Utils.AreaObject; import com.annanovas.bestprice.Utils.BrandObject; import com.annanovas.bestprice.Utils.MyDatabaseManager; import com.annanovas.bestprice.Utils.ProductsObject; import com.annanovas.bestprice.Utils.SignUpListener; import com.annanovas.bestprice.Volley.UpdateUserInfo; import com.bumptech.glide.Glide; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Random; import io.github.luizgrp.sectionedrecyclerviewadapter.Section; import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter; import io.github.luizgrp.sectionedrecyclerviewadapter.StatelessSection; public class DashBoardEditActivity extends AppCompatActivity implements SignUpListener { private int REQUEST_CAMERA = 2, SELECT_FILE = 3; private static final Random RANDOM = new Random(); private AreaAdapter areaAdapter; private ProductAdapter productAdapter; private SharedPreferences sharedPreferences; private SectionedRecyclerViewAdapter sectionAdapter; private MyDatabaseManager myDB; private ArrayList<ProductsObject> productsObjectArrayList = new ArrayList<>(); private ArrayList<ProductsObject> productsObjectArrayListForSearch = new ArrayList<>(); private ArrayList<AreaObject> areaArrayList = new ArrayList<>(); private ArrayList<AreaObject> areaObjectArrayListForSearch = new ArrayList<>(); private ArrayList<String> selectedProductList = new ArrayList<>(); private ArrayList<String> selectedProductIdList = new ArrayList<>(); private ArrayList<String> chosenBrandIdList = new ArrayList<>(); private ArrayList<ArrayList<String>> chosenBrandList = new ArrayList<ArrayList<String>>(); private LinearLayout areaLayout, brandLayout, productLayout, layoutCamera, layoutGallery, productCategoryLayout, carCategoryLayout, brandCategoryLayout, areaCategoryLayout, layoutSearchCar, layoutSearchProduct, layoutSearchArea, layoutSearchBrand, layoutQuotation, tvDealerShip, tvProduct; private EditText etAddress, etShopName, etDrivingLicense, etNid, etExperience, etFirstName, etMiddleName, etLastName, etEmail, etPhoneNumber; private EditText etProductSearch, etBrandSearch, etAreaSearch; private Button buttonSubmit; private ImageView userImage; private TextView tvAddress, tvArea, tvSelectedBrand, tvDealerShipWith, tvSelectedProduct, tvSelectedArea; private RecyclerView productRecyclerView, brandRecyclerView, areaRecyclerView; private ImageView ivArrow1, ivArrow2, ivArrow3, ivArrow4; private ProgressDialog progressDialog; private String imageUri = "", brandName = "", image = ""; private int userType, areaId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dash_board_edit); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } // chosenBrandList.add(new ArrayList<String>()); // chosenBrandList.add(new ArrayList<String>()); // chosenBrandList.add(new ArrayList<String>()); etAddress = (EditText) findViewById(R.id.et_address); etEmail = (EditText) findViewById(R.id.et_email); etShopName = (EditText) findViewById(R.id.et_shop_name); etDrivingLicense = (EditText) findViewById(R.id.et_driving_licence); etNid = (EditText) findViewById(R.id.et_nid); etExperience = (EditText) findViewById(R.id.et_experience); etFirstName = (EditText) findViewById(R.id.et_first_name); etMiddleName = (EditText) findViewById(R.id.et_middle_name); etLastName = (EditText) findViewById(R.id.et_last_name); etPhoneNumber = (EditText) findViewById(R.id.et_phone); tvAddress = (TextView) findViewById(R.id.tv_address); tvArea = (TextView) findViewById(R.id.tv_area); tvDealerShip = (LinearLayout) findViewById(R.id.tv_dealership); tvDealerShipWith = (TextView) findViewById(R.id.tv_dealership_content); tvSelectedProduct = (TextView) findViewById(R.id.tv_select_product_content); tvProduct = (LinearLayout) findViewById(R.id.tv_select_product); buttonSubmit = (Button) findViewById(R.id.button_submit); areaLayout = (LinearLayout) findViewById(R.id.layout_area); brandLayout = (LinearLayout) findViewById(R.id.layout_brand); productLayout = (LinearLayout) findViewById(R.id.layout_product); layoutCamera = (LinearLayout) findViewById(R.id.layout_camera); layoutGallery = (LinearLayout) findViewById(R.id.layout_gallery); userImage = (ImageView) findViewById(R.id.iv_user_image); areaRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_area); brandRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_brand); productRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_product); etProductSearch = (EditText) findViewById(R.id.et_product_name); etBrandSearch = (EditText) findViewById(R.id.et_brand_name); etAreaSearch = (EditText) findViewById(R.id.et_area_name); layoutSearchArea = (LinearLayout) findViewById(R.id.layout_search_area); layoutSearchProduct = (LinearLayout) findViewById(R.id.layout_search_product); layoutSearchBrand = (LinearLayout) findViewById(R.id.layout_search_brand); tvSelectedBrand = (TextView) findViewById(R.id.tv_selected_brand); tvSelectedArea = (TextView) findViewById(R.id.tv_setect_area); ivArrow1 = (ImageView) findViewById(R.id.iv_arrow1); ivArrow2 = (ImageView) findViewById(R.id.iv_arrow2); ivArrow3 = (ImageView) findViewById(R.id.iv_arrow3); ivArrow4 = (ImageView) findViewById(R.id.iv_arrow4); myDB = MyDatabaseManager.getInstance(getApplicationContext()); sharedPreferences = getSharedPreferences(AppGlobal.MY_PREFS_NAME, MODE_PRIVATE); userType = sharedPreferences.getInt("user_type", 1); int imageDimen = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.size_150dp), getResources().getDisplayMetrics()); myDB.open(); Cursor cursor = myDB.getUserInfo(userType, sharedPreferences.getString("user_phone_number", "")); if (userType == AppGlobal.CAR_OWNER) { userImage.setImageResource(R.drawable.ic_car_owner); tvAddress.setVisibility(View.VISIBLE); etAddress.setVisibility(View.VISIBLE); tvArea.setVisibility(View.VISIBLE); areaLayout.setVisibility(View.VISIBLE); if (!cursor.isLast()) { while (cursor.moveToNext()) { etFirstName.setText(cursor.getString(cursor.getColumnIndex("firstname"))); etMiddleName.setText(cursor.getString(cursor.getColumnIndex("middlename"))); etLastName.setText(cursor.getString(cursor.getColumnIndex("lastname"))); if (cursor.getString(cursor.getColumnIndex("address")) != null && !cursor.getString(cursor.getColumnIndex("address")).equals("null")) { etAddress.setText(cursor.getString(cursor.getColumnIndex("address"))); } etPhoneNumber.setText(cursor.getString(cursor.getColumnIndex("phone"))); etEmail.setText(cursor.getString(cursor.getColumnIndex("email"))); etShopName.setText(cursor.getString(cursor.getColumnIndex("shopname"))); areaId = cursor.getInt(cursor.getColumnIndex("area_id")); if (areaId != 0) { tvSelectedArea.setText(myDB.getAreaName(areaId)); } else { tvSelectedArea.setText(getResources().getString(R.string.select_area)); } if (cursor.getString(cursor.getColumnIndex("image")) != null && !cursor.getString(cursor.getColumnIndex("image")).equals("null")) { Glide.with(getApplicationContext()) .load(AppGlobal.userImagePath + cursor.getString(cursor.getColumnIndex("image"))) .error(R.drawable.ic_supplier).dontAnimate().override(imageDimen, imageDimen) .into(userImage); } else { userImage.setImageResource(R.drawable.ic_car_owner); } } } cursor.close(); generateAreaRecyclerView(); } else if (userType == AppGlobal.SUPPLIER) { tvAddress.setVisibility(View.VISIBLE); etAddress.setVisibility(View.VISIBLE); tvDealerShip.setVisibility(View.VISIBLE); tvProduct.setVisibility(View.VISIBLE); tvArea.setVisibility(View.VISIBLE); brandLayout.setVisibility(View.VISIBLE); productLayout.setVisibility(View.VISIBLE); areaLayout.setVisibility(View.VISIBLE); etShopName.setVisibility(View.VISIBLE); if (!cursor.isLast()) { while (cursor.moveToNext()) { etFirstName.setText(cursor.getString(cursor.getColumnIndex("firstname"))); etMiddleName.setText(cursor.getString(cursor.getColumnIndex("middlename"))); etLastName.setText(cursor.getString(cursor.getColumnIndex("lastname"))); etPhoneNumber.setText(cursor.getString(cursor.getColumnIndex("phone"))); etEmail.setText(cursor.getString(cursor.getColumnIndex("email"))); etShopName.setText(cursor.getString(cursor.getColumnIndex("shopname"))); etAddress.setText(cursor.getString(cursor.getColumnIndex("address"))); areaId = cursor.getInt(cursor.getColumnIndex("area_id")); if (areaId != 0) { tvSelectedArea.setText(myDB.getAreaName(areaId)); } else { tvSelectedArea.setText(getResources().getString(R.string.select_area)); } selectedProductIdList = myDB.getSelectedProductList(cursor.getInt(cursor.getColumnIndex("id"))); chosenBrandIdList = myDB.getSelectedBrandList(cursor.getInt(cursor.getColumnIndex("id"))); if (cursor.getString(cursor.getColumnIndex("image")) != null && !cursor.getString(cursor.getColumnIndex("image")).equals("null")) { Glide.with(getApplicationContext()) .load(AppGlobal.userImagePath + cursor.getString(cursor.getColumnIndex("image"))) .error(R.drawable.ic_supplier).dontAnimate().override(imageDimen, imageDimen) .into(userImage); } else { userImage.setImageResource(R.drawable.ic_supplier); } } } cursor.close(); generateAreaRecyclerView(); generateProductRecyclerView(); } else if (userType == AppGlobal.DRIVER) { etDrivingLicense.setVisibility(View.VISIBLE); etNid.setVisibility(View.VISIBLE); etExperience.setVisibility(View.VISIBLE); if (!cursor.isLast()) { while (cursor.moveToNext()) { etFirstName.setText(cursor.getString(cursor.getColumnIndex("firstname"))); etMiddleName.setText(cursor.getString(cursor.getColumnIndex("middlename"))); etLastName.setText(cursor.getString(cursor.getColumnIndex("lastname"))); etAddress.setText(cursor.getString(cursor.getColumnIndex("address"))); etPhoneNumber.setText(cursor.getString(cursor.getColumnIndex("phone"))); etEmail.setText(cursor.getString(cursor.getColumnIndex("email"))); etDrivingLicense.setText(cursor.getString(cursor.getColumnIndex("drivinglicence"))); etNid.setText(cursor.getString(cursor.getColumnIndex("nid"))); etExperience.setText(cursor.getString(cursor.getColumnIndex("yearofexperience"))); if (cursor.getString(cursor.getColumnIndex("image")) != null && !cursor.getString(cursor.getColumnIndex("image")).equals("null")) { Glide.with(getApplicationContext()) .load(AppGlobal.userImagePath + cursor.getString(cursor.getColumnIndex("image"))) .error(R.drawable.ic_supplier).dontAnimate().override(imageDimen, imageDimen) .into(userImage); } else { userImage.setImageResource(R.drawable.ic_car_owner); } } } cursor.close(); } else if (userType == AppGlobal.SHOP_WORKER) { etShopName.setVisibility(View.VISIBLE); etNid.setVisibility(View.VISIBLE); if (!cursor.isLast()) { while (cursor.moveToNext()) { etFirstName.setText(cursor.getString(cursor.getColumnIndex("firstname"))); etMiddleName.setText(cursor.getString(cursor.getColumnIndex("middlename"))); etLastName.setText(cursor.getString(cursor.getColumnIndex("lastname"))); etAddress.setText(cursor.getString(cursor.getColumnIndex("address"))); etPhoneNumber.setText(cursor.getString(cursor.getColumnIndex("phone"))); etEmail.setText(cursor.getString(cursor.getColumnIndex("email"))); etShopName.setText(cursor.getString(cursor.getColumnIndex("shopname"))); etNid.setText(cursor.getString(cursor.getColumnIndex("nid"))); if (cursor.getString(cursor.getColumnIndex("image")) != null && !cursor.getString(cursor.getColumnIndex("image")).equals("null")) { Glide.with(getApplicationContext()) .load(AppGlobal.userImagePath + cursor.getString(cursor.getColumnIndex("image"))) .error(R.drawable.ic_supplier).dontAnimate().override(imageDimen, imageDimen) .into(userImage); } else { userImage.setImageResource(R.drawable.ic_car_owner); } } } cursor.close(); } myDB.close(); areaLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (layoutSearchArea.getVisibility() == View.GONE) { layoutSearchArea.setVisibility(View.VISIBLE); areaRecyclerView.setVisibility(View.VISIBLE); ivArrow2.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_up_arrow)); } else { layoutSearchArea.setVisibility(View.GONE); areaRecyclerView.setVisibility(View.GONE); ivArrow2.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_down_arrow)); } } }); brandLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (selectedProductIdList.size() == 0) { Toast.makeText(getApplicationContext(), R.string.add_product, Toast.LENGTH_SHORT).show(); return; } if (layoutSearchBrand.getVisibility() == View.GONE) { layoutSearchBrand.setVisibility(View.VISIBLE); brandRecyclerView.setVisibility(View.VISIBLE); ivArrow3.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_up_arrow)); } else { layoutSearchBrand.setVisibility(View.GONE); brandRecyclerView.setVisibility(View.GONE); ivArrow3.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_down_arrow)); } } }); productLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (layoutSearchProduct.getVisibility() == View.GONE) { layoutSearchProduct.setVisibility(View.VISIBLE); productRecyclerView.setVisibility(View.VISIBLE); ivArrow1.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_up_arrow)); } else { layoutSearchProduct.setVisibility(View.GONE); productRecyclerView.setVisibility(View.GONE); ivArrow1.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_down_arrow)); } } }); layoutCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File file = createImageFile(); imageUri = String.valueOf(file); // showLog(imageUri); Uri photoURI = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(intent, REQUEST_CAMERA); } catch (IOException e) { e.printStackTrace(); } } }); layoutGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE); } }); buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progressDialog = new ProgressDialog(DashBoardEditActivity.this); progressDialog.setMessage(getResources().getString(R.string.please_wait)); progressDialog.setCancelable(false); progressDialog.show(); UpdateUserInfo updateUserInfo = new UpdateUserInfo(getApplicationContext()); updateUserInfo.signUpListener = DashBoardEditActivity.this; //viewEnable(false); if (userType == AppGlobal.CAR_OWNER) { boolean hasError = false; boolean hasPhoneNoError = false; if (etFirstName.getText().length() == 0) { etFirstName.setError(getResources().getString(R.string.enter_first_name)); hasError = true; } if (etLastName.getText().length() == 0) { etLastName.setError(getResources().getString(R.string.enter_last_name)); hasError = true; } if (etPhoneNumber.getText().length() == 0) { etPhoneNumber.setError(getResources().getString(R.string.enter_phone_no)); hasError = true; hasPhoneNoError = true; } if (!hasPhoneNoError && etPhoneNumber.getText().length() != 11) { etPhoneNumber.setError(getResources().getString(R.string.enter_valid_phone_no)); hasError = true; } if (etEmail.getText().length() != 0 && !Patterns.EMAIL_ADDRESS.matcher(etEmail.getText().toString()).matches()) { etEmail.setError(getResources().getString(R.string.enter_valid_email)); hasError = true; } if (etAddress.getText().length() == 0) { etAddress.setError(getResources().getString(R.string.enter_address)); hasError = true; } if (hasError) { if (progressDialog.isShowing()) progressDialog.dismiss(); return; } HashMap<String, String> params = new HashMap<>(); params.put("authentication", AppGlobal.authentication); params.put("api_token", sharedPreferences.getString("api_token", "")); params.put("phone", etPhoneNumber.getText().toString()); params.put("firstname", etFirstName.getText().toString()); if (!etMiddleName.getText().toString().equals("")) { params.put("middlename", etMiddleName.getText().toString()); } params.put("lastname", etLastName.getText().toString()); params.put("district_id", "1"); params.put("area_id", String.valueOf(areaId)); params.put("address", etAddress.getText().toString()); if (!etEmail.getText().toString().equals("")) { params.put("email", etEmail.getText().toString()); } if (!image.equals("")) { params.put("image", image); } updateUserInfo.parseData(params, "updateCarOwnerInfo"); } else if (userType == AppGlobal.SUPPLIER) { boolean hasError = false; boolean hasPhoneNoError = false; if (etFirstName.getText().length() == 0) { etFirstName.setError(getResources().getString(R.string.enter_first_name)); hasError = true; } if (etLastName.getText().length() == 0) { etLastName.setError(getResources().getString(R.string.enter_last_name)); hasError = true; } if (etPhoneNumber.getText().length() == 0) { etPhoneNumber.setError(getResources().getString(R.string.enter_phone_no)); hasError = true; hasPhoneNoError = true; } if (!hasPhoneNoError && etPhoneNumber.getText().length() != 11) { etPhoneNumber.setError(getResources().getString(R.string.enter_valid_phone_no)); hasError = true; } if (etEmail.getText().length() != 0 && !Patterns.EMAIL_ADDRESS.matcher(etEmail.getText().toString()).matches()) { etEmail.setError(getResources().getString(R.string.enter_valid_email)); hasError = true; } if (etShopName.getText().length() == 0) { etShopName.setError(getResources().getString(R.string.enter_shop_name)); hasError = true; } if (etAddress.getText().length() == 0) { etAddress.setError(getResources().getString(R.string.enter_address)); hasError = true; } if (hasError) { if (progressDialog.isShowing()) progressDialog.dismiss(); return; } HashMap<String, String> params = new HashMap<>(); params.put("authentication", AppGlobal.authentication); params.put("api_token", sharedPreferences.getString("api_token", "")); params.put("phone", etPhoneNumber.getText().toString()); params.put("firstname", etFirstName.getText().toString()); if (!etMiddleName.getText().toString().equals("")) { params.put("middlename", etMiddleName.getText().toString()); } params.put("lastname", etLastName.getText().toString()); params.put("district_id", "1"); params.put("area_id", String.valueOf(areaId)); if (!etEmail.getText().toString().equals("")) { params.put("email", etEmail.getText().toString()); } if (!image.equals("")) { params.put("image", image); } params.put("shopname", etShopName.getText().toString()); params.put("address", etAddress.getText().toString()); for (int i = 0; i < selectedProductIdList.size(); i++) { params.put("products[" + i + "]", selectedProductIdList.get(i)); } for (int i = 0; i < chosenBrandIdList.size(); i++) { params.put("brands[" + i + "]", chosenBrandIdList.get(i)); } updateUserInfo.parseData(params, "updateSupplierInfo"); } else if (userType == AppGlobal.DRIVER) { boolean hasError = false; boolean hasPhoneNoError = false; boolean hasDrivingLicenseNoError = false; boolean hasNidNoError = false; if (etFirstName.getText().length() == 0) { etFirstName.setError(getResources().getString(R.string.enter_first_name)); hasError = true; } if (etLastName.getText().length() == 0) { etLastName.setError(getResources().getString(R.string.enter_last_name)); hasError = true; } if (etPhoneNumber.getText().length() == 0) { etPhoneNumber.setError(getResources().getString(R.string.enter_phone_no)); hasError = true; hasPhoneNoError = true; } if (!hasPhoneNoError && etPhoneNumber.getText().length() != 11) { etPhoneNumber.setError(getResources().getString(R.string.enter_valid_phone_no)); hasError = true; } if (etEmail.getText().length() != 0 && !Patterns.EMAIL_ADDRESS.matcher(etEmail.getText().toString()).matches()) { etEmail.setError(getResources().getString(R.string.enter_valid_email)); hasError = true; } if (etDrivingLicense.getText().length() == 0) { etDrivingLicense.setError(getResources().getString(R.string.enter_driving_licence)); hasError = true; hasDrivingLicenseNoError = true; } if (!hasDrivingLicenseNoError && etDrivingLicense.getText().length() != 15) { etDrivingLicense.setError(getResources().getString(R.string.enter_valid_driving_licence)); hasError = true; } if (etNid.getText().length() == 0) { etNid.setError(getResources().getString(R.string.enter_nid_no)); hasError = true; hasNidNoError = true; } if (!hasNidNoError && etNid.getText().length() != 17) { etNid.setError(getResources().getString(R.string.enter_valid_nid)); hasError = true; } if (etExperience.getText().length() == 0) { etExperience.setError(getResources().getString(R.string.enter_year_of_experience)); hasError = true; } if (hasError) { if (progressDialog.isShowing()) progressDialog.dismiss(); return; } HashMap<String, String> params = new HashMap<>(); params.put("authentication", AppGlobal.authentication); params.put("api_token", sharedPreferences.getString("api_token", "")); params.put("phone", etPhoneNumber.getText().toString()); params.put("firstname", etFirstName.getText().toString()); if (!etMiddleName.getText().toString().equals("")) { params.put("middlename", etMiddleName.getText().toString()); } params.put("lastname", etLastName.getText().toString()); params.put("drivinglicence", etDrivingLicense.getText().toString()); params.put("nid", etNid.getText().toString()); params.put("yearofexperience", etExperience.getText().toString()); if (!etEmail.getText().toString().equals("")) { params.put("email", etEmail.getText().toString()); } if (!image.equals("")) { params.put("image", image); } updateUserInfo.parseData(params, "updateDriverInfo"); } else if (userType == AppGlobal.SHOP_WORKER) { boolean hasError = false; boolean hasPhoneNoError = false; if (etFirstName.getText().length() == 0) { etFirstName.setError(getResources().getString(R.string.enter_first_name)); hasError = true; } if (etLastName.getText().length() == 0) { etLastName.setError(getResources().getString(R.string.enter_last_name)); hasError = true; } if (etPhoneNumber.getText().length() == 0) { etPhoneNumber.setError(getResources().getString(R.string.enter_phone_no)); hasError = true; hasPhoneNoError = true; } if (!hasPhoneNoError && etPhoneNumber.getText().length() != 11) { etPhoneNumber.setError(getResources().getString(R.string.enter_valid_phone_no)); hasError = true; } if (etEmail.getText().length() != 0 && !Patterns.EMAIL_ADDRESS.matcher(etEmail.getText().toString()).matches()) { etEmail.setError(getResources().getString(R.string.enter_valid_email)); hasError = true; } if (etNid.getText().length() == 0) { etNid.setError(getResources().getString(R.string.enter_nid_no)); hasError = true; } if (etShopName.getText().length() == 0) { etShopName.setError(getResources().getString(R.string.enter_shop_name)); hasError = true; } if (hasError) { if (progressDialog.isShowing()) progressDialog.dismiss(); return; } HashMap<String, String> params = new HashMap<>(); params.put("authentication", AppGlobal.authentication); params.put("api_token", sharedPreferences.getString("api_token", "")); params.put("phone", etPhoneNumber.getText().toString()); params.put("firstname", etFirstName.getText().toString()); if (!etMiddleName.getText().toString().equals("")) { params.put("middlename", etMiddleName.getText().toString()); } params.put("lastname", etLastName.getText().toString()); params.put("nid", etNid.getText().toString()); params.put("shopname", etShopName.getText().toString()); if (!etEmail.getText().toString().equals("")) { params.put("email", etEmail.getText().toString()); } if (!image.equals("")) { params.put("image", image); } updateUserInfo.parseData(params, "updateWorkerInfo"); } } }); } //Toolbar back button @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } private void generateAreaRecyclerView() { myDB.open(); areaArrayList = myDB.getAllAreas(); areaObjectArrayListForSearch.addAll(areaArrayList); if (areaId != 0) { for (int i = 0; i < areaObjectArrayListForSearch.size(); i++) { if (areaObjectArrayListForSearch.get(i).getId() == areaId) { AreaObject loop = areaObjectArrayListForSearch.get(i); loop.setChecked(true); areaObjectArrayListForSearch.set(i, loop); break; } } } areaAdapter = new AreaAdapter(DashBoardEditActivity.this, areaObjectArrayListForSearch); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DashBoardEditActivity.this); areaRecyclerView.setLayoutManager(linearLayoutManager); areaRecyclerView.setItemAnimator(new DefaultItemAnimator()); areaRecyclerView.setAdapter(areaAdapter); areaRecyclerView.setNestedScrollingEnabled(false); myDB.close(); areaRecyclerView.addOnItemTouchListener(new AreaAdapter.RecyclerTouchListener(getApplicationContext(), areaRecyclerView, new AreaAdapter.ClickListener() { @Override public void onClick(View view, int position) { for (int i = 0; i < areaObjectArrayListForSearch.size(); i++) { if (areaObjectArrayListForSearch.get(i).getChecked()) { AreaObject loop = areaObjectArrayListForSearch.get(i); loop.setChecked(false); areaObjectArrayListForSearch.set(i, loop); areaAdapter.notifyItemChanged(i); // showLog(productsObjectArrayListForSearch.get(i).getName() + " selected" + productsObjectArrayListForSearch.get(i).getIsChecked()); } } AreaObject areaObject = areaObjectArrayListForSearch.get(position); areaObject.setChecked(true); areaObjectArrayListForSearch.set(position, areaObject); areaAdapter.notifyItemChanged(position); areaId = areaObject.getId(); tvSelectedArea.setText(areaObject.getName()); } @Override public void onLongClick(View view, int position) { } })); etAreaSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String newText = s.toString(); ArrayList<AreaObject> newListArea = new ArrayList<>(); for (AreaObject areaItem : areaArrayList) { String name = areaItem.getName().toLowerCase(); if (name.contains(newText)) { newListArea.add(areaItem); } } areaObjectArrayListForSearch.clear(); areaObjectArrayListForSearch.addAll(newListArea); areaAdapter.setFilter(newListArea); } @Override public void afterTextChanged(Editable s) { } }); } private void generateProductRecyclerView() { myDB.open(); productsObjectArrayList = myDB.getAllProducts(); productsObjectArrayListForSearch.addAll(productsObjectArrayList); if (selectedProductIdList.size() != 0) { for (int i = 0; i < selectedProductIdList.size(); i++) { selectedProductList.add(myDB.getProductName(Integer.parseInt(selectedProductIdList.get(i)))); } tvSelectedProduct.setText(TextUtils.join(", ", selectedProductList)); for (int i = 0; i < productsObjectArrayListForSearch.size(); i++) { String cellId = String.valueOf(productsObjectArrayListForSearch.get(i).getId()); if (selectedProductIdList.contains(cellId)) { ProductsObject loop = productsObjectArrayListForSearch.get(i); loop.setIsChecked(true); productsObjectArrayListForSearch.set(i, loop); } } generateBrandRecyclerView(); } productAdapter = new ProductAdapter(DashBoardEditActivity.this, productsObjectArrayListForSearch); LinearLayoutManager linearLayoutManager4 = new LinearLayoutManager(DashBoardEditActivity.this); productRecyclerView.setLayoutManager(linearLayoutManager4); productRecyclerView.setItemAnimator(new DefaultItemAnimator()); productRecyclerView.setAdapter(productAdapter); productRecyclerView.setNestedScrollingEnabled(false); myDB.close(); productRecyclerView.addOnItemTouchListener(new ProductAdapter.RecyclerTouchListener(getApplicationContext(), productRecyclerView, new ProductAdapter.ClickListener() { @Override public void onClick(View view, int position) { ProductsObject productsObject = productsObjectArrayListForSearch.get(position); String cellId = String.valueOf(productsObject.getId()); if (selectedProductIdList.contains(cellId)) { selectedProductIdList.remove(cellId); selectedProductList.remove(productsObject.getName()); productsObject.setIsChecked(false); } else { int totalId = selectedProductIdList.size(); selectedProductIdList.add(totalId, cellId); selectedProductList.add(totalId, productsObject.getName()); productsObject.setIsChecked(true); } productsObjectArrayListForSearch.set(position, productsObject); productAdapter.notifyItemChanged(position); tvSelectedProduct.setText(TextUtils.join(", ", selectedProductList)); chosenBrandIdList.clear(); chosenBrandList.clear(); tvDealerShipWith.setText(""); generateBrandRecyclerView(); } @Override public void onLongClick(View view, int position) { } })); etProductSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String newText = s.toString(); ArrayList<ProductsObject> newList4 = new ArrayList<>(); for (ProductsObject productsObjectItem : productsObjectArrayList) { String name = productsObjectItem.getName().toLowerCase(); if (name.contains(newText)) { newList4.add(productsObjectItem); } } productsObjectArrayListForSearch.clear(); productsObjectArrayListForSearch.addAll(newList4); productAdapter.notifyDataSetChanged(); //productAdapter.setFilter(newList4); } @Override public void afterTextChanged(Editable s) { } }); } private void generateBrandRecyclerView() { sectionAdapter = new SectionedRecyclerViewAdapter(); myDB.open(); for (int i = 0; i < selectedProductIdList.size(); i++) { chosenBrandList.add(new ArrayList<String>()); ArrayList<BrandObject> brandArrayList = myDB.getAllBrands(selectedProductIdList.get(i)); showLog("Size " + chosenBrandIdList.size()); if (chosenBrandIdList.size() != 0) { for (int j = 0; j < brandArrayList.size(); j++) { String cellId = String.valueOf(brandArrayList.get(j).getId()); if (chosenBrandIdList.contains(cellId)) { BrandObject loop = brandArrayList.get(j); loop.setChecked(true); brandArrayList.set(j, loop); chosenBrandList.get(i).add(loop.getName()); showLog("Brand " + loop.getName()); } } } String sectionTag = String.format("section%sTag", getRandomStringNumber()); sectionAdapter.addSection(sectionTag, new BrandSectionAdapter(i, getApplicationContext(), sectionTag, selectedProductList.get(i), brandArrayList)); } if (chosenBrandIdList.size() != 0) { brandName = ""; for (int i = 0; i < chosenBrandList.size(); i++) { if (chosenBrandList.get(i).size() > 0) { //brandName += productTypeList[i] + ":" + TextUtils.join(", ", chosenBrandList.get(i)) + "\n"; brandName += selectedProductList.get(i) + ":" + TextUtils.join(", ", chosenBrandList.get(i)) + "\n"; showLog("Product " + selectedProductList.get(i)); } } tvDealerShipWith.setText(brandName); } myDB.close(); LinearLayoutManager linearLayoutManager3 = new LinearLayoutManager(DashBoardEditActivity.this); brandRecyclerView.setLayoutManager(linearLayoutManager3); brandRecyclerView.setItemAnimator(new DefaultItemAnimator()); brandRecyclerView.setAdapter(sectionAdapter); brandRecyclerView.setNestedScrollingEnabled(false); etBrandSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String newText = s.toString(); for (Section section : sectionAdapter.getSectionsMap().values()) { if (section instanceof FilterableSection) { ((FilterableSection) section).filter(newText); } } sectionAdapter.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable s) { } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == SELECT_FILE) { if (resultCode == Activity.RESULT_OK) { Bitmap selectedImage = null; try { selectedImage = decodeUri(data.getData()); selectedImage = imageProcess(selectedImage); if (selectedImage != null) { new ImageString(selectedImage).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); showLog("Bitmap Size " + selectedImage.getHeight() + "*" + selectedImage.getWidth()); userImage.setImageBitmap(selectedImage); } } catch (FileNotFoundException e) { e.printStackTrace(); } } } else if (requestCode == REQUEST_CAMERA) { if (resultCode == Activity.RESULT_OK) { File file = new File(imageUri); Bitmap selectedImage = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 1000); selectedImage = imageProcess(selectedImage); if (selectedImage != null) { new ImageString(selectedImage).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); showLog("Bitmap Size " + selectedImage.getHeight() + "*" + selectedImage.getWidth()); userImage.setImageBitmap(selectedImage); } } else if (resultCode == Activity.RESULT_CANCELED) { // showLog("Canceled"); File file = new File(imageUri); file.delete(); } } } public File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Best Price"); if (!storageDir.exists()) { storageDir.mkdirs(); } File image = File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents imageUri = "file:" + image.getAbsolutePath(); return image; } private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(getApplicationContext().getContentResolver().openInputStream(selectedImage), null, o); // The new size we want to scale to final int REQUIRED_SIZE = 1000; // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) { break; } width_tmp /= 2; height_tmp /= 2; scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream( getApplicationContext().getContentResolver().openInputStream(selectedImage), null, o2); } public Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH //First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize, Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; options.inPreferredConfig = Bitmap.Config.RGB_565; int inSampleSize = 1; if (height > reqHeight) { inSampleSize = Math.round((float) height / (float) reqHeight); } int expectedWidth = width / inSampleSize; if (expectedWidth > reqWidth) { //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize.. inSampleSize = Math.round((float) width / (float) reqWidth); } options.inSampleSize = inSampleSize; // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(path, options); } private Bitmap imageProcess(Bitmap imageBitmap) { int width = imageBitmap.getWidth(); int height = imageBitmap.getHeight(); int newWidth = 1000; int newHeight = 1000; if (width > 1000) { double x = (double) width / 1000d; newHeight = (int) (height / x); newWidth = 1000; } else if (height > 1000) { double x = (double) height / 1000d; newWidth = (int) (width / x); newHeight = 1000; } // calculate the scale - in this case = 0.4f ExifInterface exif = null; int rotationAngle = 0; try { exif = new ExifInterface(imageUri); String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION); // showLog("orientString:" + orientString + " DateTime:" + exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH)); int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL; if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90; if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180; if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270; // showLog("Rotation Angle:" + rotationAngle); } catch (IOException e) { // showLog("ExifInterface Failed!"); e.printStackTrace(); } float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); matrix.postRotate(rotationAngle); return Bitmap.createBitmap(imageBitmap, 0, 0, width, height, matrix, true); } @NonNull private String getRandomStringNumber() { return String.valueOf(RANDOM.nextInt(100000)); } @Override public void SignUpSuccess(boolean result) { if (progressDialog.isShowing()) progressDialog.dismiss(); onBackPressed(); } public class BrandSectionAdapter extends StatelessSection implements FilterableSection { private String title, TAG; private int sectionIndex; private Context context; private ArrayList<BrandObject> brandSectionArrayList, filteredList; public BrandSectionAdapter(int sectionIndex, Context context, String TAG, String title, ArrayList<BrandObject> brandSectionArrayList) { super(R.layout.section_header_brand, R.layout.single_product_view); this.context = context; this.TAG = TAG; this.title = title; this.sectionIndex = sectionIndex; this.brandSectionArrayList = brandSectionArrayList; this.filteredList = new ArrayList<>(brandSectionArrayList); } @Override public RecyclerView.ViewHolder getItemViewHolder(View view) { return new MyItemViewHolder(view); } @Override public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) { final MyItemViewHolder itemHolder = (MyItemViewHolder) holder; itemHolder.brandName.setText(filteredList.get(position).getName()); itemHolder.layoutSingleItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(getApplicationContext(), String.format("Clicked on position #%s of Section %s", sectionAdapter.getPositionInSection(itemHolder.getAdapterPosition()), title), Toast.LENGTH_SHORT).show(); int adapterPosition = itemHolder.getAdapterPosition(); if (adapterPosition != RecyclerView.NO_POSITION) { int positionInSection = sectionAdapter.getPositionInSection(adapterPosition); BrandObject brandObject = filteredList.get(positionInSection); Toast.makeText(getApplicationContext(), String.format("Clicked on position #%d of Section %s", sectionIndex, title), Toast.LENGTH_SHORT).show(); //if (selectedBrandList.contains(brandObject.getBrandname())) { if (chosenBrandList.get(sectionIndex).contains(brandObject.getName())) { //selectedBrandList.remove(brandObject.getBrandname()); chosenBrandIdList.remove(String.valueOf(brandObject.getId())); chosenBrandList.get(sectionIndex).remove(brandObject.getName()); brandObject.setChecked(false); } else { //int totalId = selectedBrandList.size(); //selectedBrandList.add(totalId, brandObject.getBrandname()); chosenBrandIdList.add(String.valueOf(brandObject.getId())); chosenBrandList.get(sectionIndex).add(brandObject.getName()); brandObject.setChecked(true); } filteredList.set(positionInSection, brandObject); sectionAdapter.notifyItemChangedInSection(TAG, positionInSection); brandName = ""; for (int i = 0; i < chosenBrandList.size(); i++) { if (chosenBrandList.get(i).size() > 0) { //brandName += productTypeList[i] + ":" + TextUtils.join(", ", chosenBrandList.get(i)) + "\n"; brandName += selectedProductList.get(i) + ":" + TextUtils.join(", ", chosenBrandList.get(i)) + "\n"; showLog("Product " + selectedProductList.get(i)); } } tvDealerShipWith.setText(brandName); } } }); if (filteredList.get(position).getChecked()) { itemHolder.ivCheckMark.setVisibility(View.VISIBLE); } else { itemHolder.ivCheckMark.setVisibility(View.GONE); } } class MyItemViewHolder extends RecyclerView.ViewHolder { public TextView brandName; public LinearLayout layoutSingleItem; public ImageView ivCheckMark; MyItemViewHolder(View itemView) { super(itemView); brandName = (TextView) itemView.findViewById(R.id.tv_item_name); ivCheckMark = (ImageView) itemView.findViewById(R.id.tick_mark); layoutSingleItem = (LinearLayout) itemView.findViewById(R.id.layout_single_item); } } @Override public RecyclerView.ViewHolder getHeaderViewHolder(View view) { return new HeaderViewHolder(view); } @Override public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) { HeaderViewHolder hHolder = (HeaderViewHolder) holder; hHolder.headerTitle.setText(title); } class HeaderViewHolder extends RecyclerView.ViewHolder { TextView headerTitle; HeaderViewHolder(View itemView) { super(itemView); headerTitle = (TextView) itemView.findViewById(R.id.tv_section_header2); } } @Override public int getContentItemsTotal() { return filteredList.size(); // number of items of this section } @Override public void filter(String query) { if (TextUtils.isEmpty(query)) { filteredList = new ArrayList<>(brandSectionArrayList); this.setVisible(true); } else { filteredList.clear(); for (BrandObject brandObject : brandSectionArrayList) { if (brandObject.getName().toLowerCase().contains(query.toLowerCase())) { filteredList.add(brandObject); } } this.setVisible(!filteredList.isEmpty()); } } } interface FilterableSection { void filter(String query); } private class ImageString extends AsyncTask<String, String, String> { Bitmap bitmap; ImageString(Bitmap bitmap) { this.bitmap = bitmap; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { return encodeToBase64(bitmap, Bitmap.CompressFormat.JPEG, 100); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); image = result; showLog(image); } } public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality) { ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); image.compress(compressFormat, quality, byteArrayOS); return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT); } private void showLog(String message) { if (!AppGlobal.show_log) return; String TAG = "DashBoardEditActivity"; Log.e(TAG, message); } }