Обновление с помощью retrofit2 и ohttp3 в android studio - PullRequest
0 голосов
/ 09 апреля 2020

Этот код очень хорошо работает для отправки данных на сервер, но теперь я хочу иметь возможность использовать тот же шаг для обновления данных по идентификатору продукта.

                public class PostProduct extends AppCompatActivity implements View.OnClickListener {


                    public  static final int RequestPermissionCode  = 1 ;
                    ProgressBar progressBar;
                    ImageView image,b2;
                    TextView b1;
                    RelativeLayout layout;
                    Button btnConnect;
                    TextView connected;
                    Spinner category_spinner,category_spinner2;
                    int PICK_IMAGE_MULTIPLE = 1;
                    String imageEncoded;
                    List<String> imagesEncodedList;
                    private GridView gvGallery;
                    private GalleryAdapter galleryAdapter;
                ImageButton imageButton;










                    EditText model,password,phone;



                    private String TAG = "PostProduct";
                    Button submitBtn,btnChoose,next;

                    private TextInputLayout textpersontype;
                    private SharedPreferences sharedPreferences;
                    private SharedPreferences.Editor editor;
                    String accesstoken;

                    private TextInputLayout textphone;
                    private TextInputLayout textPassword;

                    Button btnUpload, btnMulUpload, btnPickImage, btnPickVideo;
                    String mediaPath, mediaPath1;
                    ImageView imgView;
                    String[] mediaColumns = {MediaStore.Video.Media._ID};
                    ProgressDialog progressDialog;
                    TextView str1, str2;
                    String token;
                    private String idCategory="39";
                    private String idCategory2="49";
                  ImageButton CaptureImageFromCamera,UploadImageToServer;
                    Intent intent ;
                    Bitmap bitmap;
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.fragment_sell);

                        progressDialog = new ProgressDialog(this);
                        progressDialog.setMessage("Uploading...");
                        CaptureImageFromCamera = (ImageButton)findViewById(R.id.camera_btn);
                        btnMulUpload = (Button) findViewById(R.id.uploadMultiple);
                        btnPickImage = (Button) findViewById(R.id.pick_img);
                        gvGallery= (GridView ) findViewById(R.id.gv);
                        str1 = (TextView) findViewById(R.id.filename1);
                        str2 = (TextView) findViewById(R.id.filename2);
                        imageButton=(ImageButton)findViewById(R.id.warning);


                        category_spinner=findViewById(R.id.category_spinner);
                        category_spinner2=findViewById(R.id.category_spinner4);
                        category_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                if(position==0){
                                    idCategory="39";
                                }
                                if(position==1){
                                    idCategory="41";
                                }
                                if(position==2){
                                    idCategory="43";
                                }
                                if(position==3){
                                    idCategory="45";
                                }
                                if(position==4){
                                    idCategory="47";
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        category_spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                if(position==0){
                                    idCategory2="49";
                                }
                                if(position==1){
                                    idCategory2="51";
                                }
                                if(position==2){
                                    idCategory2="53";
                                }
                                if(position==3){
                                    idCategory2="55";
                                }
                                if(position==4){
                                    idCategory2="57";
                                }
                                if(position==4){
                                    idCategory2="59";
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        EnableRuntimePermissionToAccessCamera();
                        CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                startActivityForResult(intent, 0);

                            }
                        });
                        sharedPreferences=getApplicationContext().getSharedPreferences("token",0);
                        editor=sharedPreferences.edit();
                        token=sharedPreferences.getString("access_token",null);







                        btnPickImage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                Intent intent = new Intent();
                                intent.setType("image/*");
                                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);


                                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(galleryIntent, 0);
                            }
                        });

                        imageButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AlertDialog.Builder dialog=new AlertDialog.Builder(PostProduct.this);
                                dialog.setMessage("Veuillez selectionez au moins six photos format jpg and png et remplir le formulaire pour la publication de votre produit");
                                dialog.setTitle("Commment sa marche");
                                dialog.setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                                int which) {
                                                Toast.makeText(getApplicationContext(),"Ok",Toast.LENGTH_LONG).show();
                                            }
                                        });
                                dialog.setNegativeButton("cancel",new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //   Toast.makeText(getApplicationContext(),"cancel is clicked",Toast.LENGTH_LONG).show();
                                    }
                                });
                                AlertDialog alertDialog=dialog.create();
                                alertDialog.show();
                            }
                        });


                        next=(Button) findViewById(R.id.next);
                       next.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                Intent i2 = new Intent(PostProduct.this, ProductsDetails.class);
                                startActivity(i2);
                            }
                        });

                        b2=(ImageView) findViewById(R.id.back);
                        b2.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                Intent i2 = new Intent(getApplicationContext(), MainActivity.class);
                                startActivity(i2);
                            }
                        });

                        final EditText et1 = (EditText)findViewById(R.id.name);
                        final EditText et2 = (EditText)findViewById(R.id.price);
                        final EditText et3 = (EditText)findViewById(R.id.quantity);
                        final EditText et4 = (EditText)findViewById(R.id.model);
                        final EditText et5 = (EditText)findViewById(R.id.models);



                        Button submitBtn1 = (Button)findViewById(R.id.uploadMultiple);




                        submitBtn1.setOnClickListener(new View.OnClickListener() {


                                                          @Override
                                                          public void onClick(View v) {
                                                              switch (v.getId()){


                                                              }
                                                              ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
                                                              NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
                                                              if (null != activeNetwork) {
                                                                  if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                                                                      Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
                                                              } else {
                                                                  Toast.makeText(getApplicationContext(), "Connexion internet non disponible", Toast.LENGTH_SHORT).show();

                                                              }





                                                              String name = et1.getText().toString().trim();
                                                              String price= et2.getText().toString().trim();
                                                              String quantity = et3.getText().toString().trim();
                                                              String model = et4.getText().toString().trim();
                                                              String models = et5.getText().toString().trim();
                                                              File file = new File(mediaPath);
                if(file.equals(null))
                {
                    Toast.makeText(PostProduct.this,"Veuillez choisir un photo ou plusieur photos",Toast.LENGTH_SHORT).show();
                }

                                                            //  File file1 = new File(mediaPath1);

                                                              // Parsing any Media type file
                                                              RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
                                                            //  RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);

                                                              MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file", file.getName(), requestBody1);
                                                             // MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);

                                                              if (TextUtils.isEmpty(name) )


                                                              {
                                                                  et1.setError("Nom du Produit obligatoire");

                                                                  return;
                                                              }
                                                              else if (TextUtils.isEmpty(price))
                                                              {
                                                                  et2.setError("Prix obligatoire");
                                                              }

                                                              else if (TextUtils.isEmpty(quantity))
                                                              {
                                                                  et3.setError("Quantity obligatoire");
                                                              }



                                                              else if (TextUtils.isEmpty(models)) {
                                                                  et5.setError("Details du Produit Obligatoire");


                                                                  return;

                                                              }

                                                              else if (TextUtils.isEmpty(model)) {
                                                                  et4.setError("Model du Produit Obligatoire");


                                                                  return;

                                                              }





                                                              {
                                                                  sendProduct(name,price,quantity,model,file);
                                                              }




                                                              }
                                                          }



                        );


                    }



                    private void alertDialog() {


                        }



                    // Requesting runtime permission to access camera.
                    public void EnableRuntimePermissionToAccessCamera(){

                        if (ActivityCompat.shouldShowRequestPermissionRationale(PostProduct.this,
                                Manifest.permission.CAMERA))
                        {

                            // Printing toast message after enabling runtime permission.
                            Toast.makeText(PostProduct.this,"L'autorisation CAMERA nous permet d'accéder à l'application CAMERA", Toast.LENGTH_LONG).show();

                        } else {

                            ActivityCompat.requestPermissions(PostProduct.this,new String[]{Manifest.permission.CAMERA}, RequestPermissionCode);

                        }
                    }




                    private void sendProduct(String name, String price, String quantity, String model ,File file) {
                        final SweetAlertDialog pDialog = new SweetAlertDialog(PostProduct.this, SweetAlertDialog.PROGRESS_TYPE);
                        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.colorPrimary));
                        pDialog.setTitleText("Chargement");
                        pDialog.setCancelable(false);
                        pDialog.show();
                        //ApiInterface apiService=Api.getClient();
                        ApiService apiService = Okhttp_RetrofitClient.getClient().create(ApiService.class);
                        try {
                            List<MultipartBody.Part> filelist=new ArrayList<>();
                            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"),file.getAbsolutePath());
                            MultipartBody.Part body=MultipartBody.Part.createFormData("files",file.getName(),requestBody);
                            filelist.add(body);
                            /*JSONObject paramObject = new JSONObject();
                            paramObject.put("name",name);
                            paramObject.put("price",price);
                            paramObject.put("quantity", quantity);
                            paramObject.put("idCategory", 41);
                            paramObject.put("model", model);

                           RequestBody requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf((paramObject)));*/
                         //   RequestBody body2 = RequestBody.create(MediaType.parse("*/*"), file);
                            RequestBody name_body = RequestBody.create(MediaType.parse("text/plain"), name);
                            RequestBody price_body = RequestBody.create(MediaType.parse("text/plain"), price);
                            RequestBody quantity_body = RequestBody.create(MediaType.parse("text/plain"), quantity);
                            RequestBody idCategory_body = RequestBody.create(MediaType.parse("text/plain"), idCategory);
                            RequestBody idCategory_body2 = RequestBody.create(MediaType.parse("text/plain"), idCategory2);
                            RequestBody model_body = RequestBody.create(MediaType.parse("text/plain"), model);
                            Call<Product> call = apiService.saveProduct(filelist,name_body,price_body,quantity_body,idCategory_body,idCategory_body2,model_body,token);
                            call.enqueue(new Callback<Product>() {
                                @Override
                                public void onResponse(Call<Product> call, Response<Product> response) {
                                    pDialog.dismiss();
                                    if (response.isSuccessful() && response.code() == 200) {
                                        showResponse(response.body().toString());
                                        //SharedPrefManager.getInstance(getActivity()).userLogin(response.body());
                                        Log.d(TAG, "post submitted to API." +response.body().getId());
                                        new SweetAlertDialog(PostProduct.this, SweetAlertDialog.SUCCESS_TYPE)
                                                .setTitleText("Publication de votre produit")
                                                .setContentText("reussi!")
                                                .show();




                                    }

                                    else if(response.code()==400){
                                        JSONObject jsonObject= null;

                                        try {
                                            String errorjson=response.errorBody().string();
                                            jsonObject=new JSONObject(errorjson);
                                            JSONObject error=jsonObject.getJSONObject("error");
                                            String message=error.getString("message");
                                            Log.d(TAG, "post error " +message);
                                            Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
                                        }


                                        catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                        catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }




                                    else {
                                        Log.d(TAG, "post submitted response not successful." + response.errorBody().toString());
                                    }

                                }


                                @Override
                                public void onFailure(Call<Product> call, Throwable t) {
                                    Log.d(TAG, "post submitted to API onFailure." + t.getMessage());
                                }
                            });
                        } catch (Exception e) {
                            Log.d(TAG, "post submitted to API catch." + e.getCause());
                            e.printStackTrace();
                        }


                    }

                    public void showResponse(String response) {

                    }


                    @Override
                    public void onClick(View v) {





                    }
                    @Override
                    public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {

                        switch (RC) {

                            case RequestPermissionCode:

                                if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {

                                  //  Toast.makeText(PostProduct.this,"Autorisation accordée, votre application peut désormais accéder à CAMERA.", Toast.LENGTH_LONG).show();

                                } else {

                                    Toast.makeText(PostProduct.this,"Autorisation annulée, votre application ne peut plus accéder à CAMERA.", Toast.LENGTH_LONG).show();

                                }
                                break;
                        }
                    }

                }

это мой интерфейс apiservice для этого кода

                    @Multipart
                          @POST("/se/product")
                            /* @Headers("Content-Type: application/json")*/
                          Call<Product> saveProduct(@Part List<MultipartBody.Part> file, @Part("name") RequestBody name, @Part("price") RequestBody price, @Part("quantity") RequestBody quantity, @Part("idCategory") RequestBody idCategory,
                                                    @Part("idCategory2") RequestBody idCategory2,
                                                    @Part("model") RequestBody model, @Header("Authorization") String token);

теперь для обновления я создаю аписервис обновления ниже

                            @PUT("/se/product/{id}")
                            Call<ResponseBody> updateProduct(List<MultipartBody.Part> filelist, RequestBody name_body, RequestBody price_body, RequestBody quantity_body, RequestBody idCategory_body, RequestBody model_body, @Header("Authorization") String token);

любой может помочь мне как разобраться в этом вопросе? я уверен, что класс обновления должен быть похож на класс Product.class, но я не знаю, где я должен внести изменения

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...