I have made an ecommerce android app.
Whenever I add product in the database table the MySQL query is inserting the same data two times in the table.
I have provided my PHP file and JAVA file .
<?php
$productname = $_POST['productName'];
$productPrice = $_POST['price'];
$desc = $_POST['desc'];
$unit = $_POST['unit'];
$mini = $_POST['minimum'];
$category = $_POST['category'];
$offer = $_POST['offer'];
$image1 = $_POST['img1'];
$image2 = $_POST['img2'];
$image3 = $_POST['img3'];
$image4 = $_POST['img4'];
$image5 = $_POST['img5'];
$sellerId = (Integer) $_POST['seller'];
date_default_timezone_set('Asia/Kolkata');
$date=date("Y-m-d");
//echo $date;
$time =date("H:i:s");
$filename1 = rand().".jpg";
file_put_contents("product_images/".$filename1,base64_decode($image1));
$filename2 = rand().".jpg";
file_put_contents("product_images/".$filename2,base64_decode($image2));
if($image3=="non"){
$filename3 ="non";
}else{
$filename3 = rand().".jpg";
file_put_contents("product_images/".$filename3,base64_decode($image3));
}
if($image4=="non"){
$filename4 = "non";
}else{
$filename4 = rand().".jpg";
file_put_contents("product_images/".$filename4,base64_decode($image4));
}
if($image5=="non"){
$filename5 = "non";
}else{
$filename5 = rand().".jpg";
file_put_contents("product_images/".$filename5,base64_decode($image5));
}
include "config.php";
$sql="INSERT INTO `products` (`sellerId`,`productname`, `price`, `unit`, `image1`,
`image2`, `image3`,`image4`,`image5`, `description`, `offer`, `category`, `minimum`,
`inStock`,`date`)
VALUES ('{$sellerId}','{$productname}', '{$productPrice}', '{$unit}', '{$filename1}',
'{$filename2}', '{$filename3}','{$filename4}','{$filename5}','{$desc}', '{$offer}',
'{$category}', '{$mini}', '0' , '{$date}')";
$result=mysqli_query($conn,$sql) or die("result failed");
echo "added successfully";
?>
This is the java file. I am adding data throgh volley class and the function name is volleyMethodAddingProduct() .
public class addProductPage extends AppCompatActivity {
RecyclerView imageRecycler;
ImageView camera ;
Toolbar toolbar;
Button add , cancel, gallery;
EditText name , price , desc ,offers , minimum;
ArrayList<String> images = new ArrayList<>();
AutoCompleteTextView catDropdown , unitDropdown;
TextInputLayout DropText , unitText;
private final String url = "https://atttherate.com/Z_getUnits.php";
private final String url2 = "https://atttherate.com/Z_getCategory.php";
private final String url3 = "https://atttherate.com/Z_addProduct.php";
Button retry;
Dialog dialog;
int className;
int getsession;
ArrayList<productImageModal> list;
ArrayList<String> category = new ArrayList<>();
ArrayList<String> unit = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product_page);
catDropdown = findViewById(R.id.auto);
unitDropdown = findViewById(R.id.unit);
SharedPreferencelogin session = new SharedPreferencelogin(addProductPage.this);
getsession = session.getSession();
getUnits();
getCategories();
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addProductPage.this,
R.layout.sampledroptextlayout,category);
catDropdown.setAdapter(myAdapter);
ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(addProductPage.this,
R.layout.sampledroptextlayout,unit);
unitDropdown.setAdapter(myAdapter2);
Intent get = getIntent();
className = get.getIntExtra("class",-1);
gallery = findViewById(R.id.addgalleryimg);
toolbar = findViewById(R.id.toolbaar2);
add = findViewById(R.id.addSaveProduct);
cancel = findViewById(R.id.addSavecancel);
name = findViewById(R.id.addproductName);
price = findViewById(R.id.addproductPrice);
desc = findViewById(R.id.addproductDesc);
offers = findViewById(R.id.addOffer);
DropText = findViewById(R.id.dropText);
unitText = findViewById(R.id.dropText2);
imageRecycler = findViewById(R.id.EditproductImageRecycler);
minimum = findViewById(R.id.addproductminimum);
gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkRequest();
pick();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nameText = name.getText().toString().trim();
String priceText = price.getText().toString().trim();
String decsText = desc.getText().toString().trim();
String offersText = offers.getText().toString().trim();
String catDropdownText = catDropdown.getText().toString().trim();
String unitDropdownText = unitDropdown.getText().toString().trim();
String mini = minimum.getText().toString().trim();
int imagesSize = images.size();
ConnectivityManager cm = (ConnectivityManager)
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (nameText.equals("") || priceText.equals("") || decsText.equals("") ||
catDropdownText.equals("") || unitDropdownText.equals("") ||
mini.equals("") ) {
Toast.makeText(addProductPage.this,"Fill up all required
feilds",Toast.LENGTH_SHORT).show();
}else {
if (null == netInfo) {
dialog = new Dialog(addProductPage.this);
dialog.setContentView(R.layout.dialoglayout);
dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.dialogback));
dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
dialog.show();
retry = dialog.findViewById(R.id.Retry);
retry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recreate();
}
});
} else {
if (offers.getText().toString().isEmpty() ||
Double.valueOf(offers.getText().toString().trim()) == 0) {
offers.setText("no");
}
volleyMethodAddingProduct();
Intent intent = new Intent(addProductPage.this,
SellerAddedProductConfirm.class);
intent.putExtra("class" , className);
startActivity(intent);
}
}
}
});
}
private void pick(){
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE , true);
intent.setType("image/*");
launcher.launch(intent);
}
private String encodeBitmapImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,70,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
String tring= android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
return tring;
}
ActivityResultLauncher<Intent> launcher = registerForActivityResult(new
ActivityResultContracts.StartActivityForResult(), new
ActivityResultCallback<ActivityResult>() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onActivityResult(ActivityResult result) {
if (result != null && result.getResultCode() == RESULT_OK) {
list = new ArrayList<>();
ClipData clips = result.getData().getClipData();
images.add(0,"non");
images.add(1,"non");
images.add(2,"non");
images.add(3,"non");
images.add(4,"non");
if (clips !=null) {
if (6 > clips.getItemCount() && 1 < clips.getItemCount()) {
if (clips != null) {
for (int i = 0; i < clips.getItemCount(); i++) {
Uri imgUri = clips.getItemAt(i).getUri();
try {
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(addProductPage.this.getContentResolver(), imgUri);
String str = encodeBitmapImage(bitmap);
images.set(i,str);
ByteArrayOutputStream bytes = new
ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
String path =
MediaStore.Images.Media.insertImage(addProductPage.this.getContentResolver(), bitmap,
"image", "val");
byte[] bytee = bytes.toByteArray();
list.add(new productImageModal(bytee));
} catch (Exception e) {
}
}
} else {
Toast.makeText(addProductPage.this, "No image
founddddddddddddddddd", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(addProductPage.this, "Select minimum 3 images and
maximum 5 images", Toast.LENGTH_LONG).show();
pick();
}
}else {
Toast.makeText(addProductPage.this, "Select minimum 3 images and maximum
5 images", Toast.LENGTH_LONG).show();
pick();
}
imageRecycler = findViewById(R.id.EditproductImageRecycler);
productImageAdapter adapter = new productImageAdapter(list,
addProductPage.this);
imageRecycler.setAdapter(adapter);
LinearLayoutManager layout = new LinearLayoutManager(addProductPage.this,
LinearLayoutManager.VERTICAL, false);
imageRecycler.setLayoutManager(layout);
}
}
});
private boolean checkRequest(){
if(Build.VERSION.SDK_INT >= 23){
int camera = ActivityCompat.checkSelfPermission(addProductPage.this ,
Manifest.permission.CAMERA);
int write = ActivityCompat.checkSelfPermission(addProductPage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(camera == PackageManager.PERMISSION_DENIED && write ==
PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(addProductPage.this , new String[]
{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE} , 2);
return false;
}
}
return true ;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==2 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED){
pick();
}else{
Toast.makeText(addProductPage.this, "Not granted " , Toast.LENGTH_LONG).show();
}
}
public void getCategories(){
ArrayList<frontCategoryModal> catArray = new ArrayList<>();
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
String image = object.getString("image");
int id = object.getInt("id");
String imgUrl = "https://atttherate.com/category_images/"+image;
category.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addProductPage.this);
queue.add(request);
};
public void getUnits(){
ArrayList<frontCategoryModal> catArray = new ArrayList<>();
StringRequest request = new StringRequest(Request.Method.POST, url, new
Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
unit.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addProductPage.this);
queue.add(request);
};
public void volleyMethodAddingProduct() {
ExecutorService executer = Executors.newSingleThreadExecutor();
executer.execute(new Runnable() {
@Override
public void run() {
SharedPreferencelogin session = new
SharedPreferencelogin(addProductPage.this);
getsession = session.getSession();
final String seller = String.valueOf(getsession);
final String addProductName = name.getText().toString().trim();
final String addPrice = price.getText().toString().trim();
final String addDesc = desc.getText().toString().trim();
final String addUnit = unitDropdown.getText().toString().trim();
final String addOffer = String.valueOf(offers.getText().toString().trim());
final String category = catDropdown.getText().toString().trim();
final String minimumOrder = minimum.getText().toString().trim();
final String image1 ;
final String image2 ;
final String image3 ;
final String image4 ;
final String image5 ;
image1 = images.get(0);
image2 = images.get(1);
image3 = images.get(2);
image4 = images.get(3);
image5 = images.get(4);
StringRequest request = new StringRequest(Request.Method.POST, url3, new
Response.Listener<String>() {
@Override
public void onResponse(String response) {
name.setText("");
price.setText("");
desc.setText("");
unitDropdown.setText("");
String success = response;
Toast.makeText(addProductPage.this,success,Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
})
{
@Override
protected Map<String, String> getParams() {
Map<String,String> map=new HashMap<String, String>();
map.put("productName",addProductName);
map.put("price",addPrice);
map.put("desc",addDesc);
map.put("unit",addUnit);
map.put("img1",image1);
map.put("img2",image2);
map.put("img3",image3);
map.put("img4",image4);
map.put("img5",image5);
map.put("minimum",minimumOrder);
map.put("offer",addOffer);
map.put("category",category);
map.put("seller",seller);
return map;
}
};
RequestQueue queue = Volley.newRequestQueue(addProductPage.this);
queue.add(request);
}
});
}
}