Komang Putra Ответов: 0

Volley POST request in loop игнорирует все, кроме параметров последнего вызова


Я просто пытаюсь сделать запрос volley с помощью метода post using loop, вот мой код

package com.example.eis2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.eis2.Item.getNo_pengajuan_full;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.example.eis2.Item.LoginItem.KEY_NIK;
import static com.example.eis2.izin.txt_nomor;
import static com.example.eis2.izinfull.txt_lokasi;

public class sakit extends AppCompatActivity {
    private Spinner spinner;
    ArrayList<String> Karyawan;
    EditText nopengajuan, editText, keterangan;
    Button pengajuan, upload;
    private List<getNo_pengajuan_full> no_pengajuan;
    ProgressDialog pDialog;
    final int CODE_GALLERY_REQUEST = 999;
    LinearLayout container;
    ImageView upload_gambar;
    Bitmap bitmap;
    ImageButton add;
    private Calendar date;
    public int numberOfLines = 3;
    private SimpleDateFormat dateFormatter;

    public void showDateTimePicker(){
        final Calendar currentDate = Calendar.getInstance();
        Calendar twoDaysAgo = (Calendar) currentDate.clone();
        twoDaysAgo.add(Calendar.DATE, -3);

        date = currentDate.getInstance();

        DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                date.set(year, monthOfYear, dayOfMonth );

                editText.setText(dateFormatter.format(date.getTime()));
            }
        };
        DatePickerDialog datePickerDialog = new  DatePickerDialog(sakit.this, dateSetListener, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH),   currentDate.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker().setMinDate(twoDaysAgo.getTimeInMillis());
        datePickerDialog.show();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sakit);
        final String nik_baru = getIntent().getStringExtra(KEY_NIK);
        Karyawan = new ArrayList<>();
        spinner = (Spinner) findViewById(R.id.karyawan);
        nopengajuan = (EditText) findViewById(R.id.nopengajuan);
        editText = (EditText) findViewById(R.id.tanggal);
        keterangan = (EditText) findViewById(R.id.keterangan_text);
        upload_gambar = (ImageView) findViewById(R.id.gambar1);
        no_pengajuan = new ArrayList<>();
        pengajuan = (Button) findViewById(R.id.pengajuanfull);
        dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

        add = (ImageButton) findViewById(R.id.add);

        nopengajuan.setFocusable(false);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout ll = (LinearLayout)findViewById(R.id.container);
                final EditText tanggal1 = new EditText(sakit.this);
                final TextView tanggald = new TextView(sakit.this);

                LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                tanggald.setLayoutParams(p);
                tanggald.setId(numberOfLines + 1);
                tanggald.setText("tanggal");

                tanggal1.setLayoutParams(p);
                tanggal1.setId(numberOfLines + 1);
                ll.addView(tanggald);

                ll.addView(tanggal1);
                tanggal1.setFocusable(false);
                numberOfLines++;

                tanggal1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final Calendar currentDate = Calendar.getInstance();
                        Calendar twoDaysAgo = (Calendar) currentDate.clone();
                        twoDaysAgo.add(Calendar.DATE, -3);

                        date = currentDate.getInstance();

                        DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                                date.set(year, monthOfYear, dayOfMonth );

                                tanggal1.setText(dateFormatter.format(date.getTime()));
                            }
                        };
                        DatePickerDialog datePickerDialog = new  DatePickerDialog(sakit.this, dateSetListener, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH),   currentDate.get(Calendar.DAY_OF_MONTH));
                        datePickerDialog.getDatePicker().setMinDate(twoDaysAgo.getTimeInMillis());
                        datePickerDialog.show();

                    }
                });
            }
        });
        TextView tvResourceId = findViewById(R.id. tvResourceId ) ;
        tvResourceId.setText(String. valueOf (upload_gambar)) ;

        editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateTimePicker();
            }
        });

        pengajuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.getText().toString().length() == 0) {
                    editText.setError("Masukkan Tanggal!");
                } else if (keterangan.getText().toString().length() == 0) {
                    keterangan.setError("Masukkan Keterangan!");
                } else if (upload_gambar.getDrawable() == null){
                    Toast.makeText(getApplicationContext(), "Upload gambar terlebih dahulu", Toast.LENGTH_SHORT).show();
                } else {
                    postfull();
                }
            }
        });

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String karyawan = spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
                Toast.makeText(getApplicationContext(), karyawan, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
        getLokasi();
        getNo();


        upload = (Button) findViewById(R.id.upload);
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(sakit.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CODE_GALLERY_REQUEST);
            }
        });
    }

    private void Add_Line() {

    }


    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == CODE_GALLERY_REQUEST){
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Select Image"), CODE_GALLERY_REQUEST);
            }else{
                Toast.makeText(getApplicationContext(), "You don't have permission to access gallery!", Toast.LENGTH_LONG).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CODE_GALLERY_REQUEST && resultCode == RESULT_OK && data != null){
            Uri path = data.getData();
            try {
                InputStream inputStream = getContentResolver().openInputStream(path);
                bitmap = BitmapFactory.decodeStream(inputStream);
                upload_gambar.setImageBitmap(bitmap);
                upload_gambar.setVisibility(View.VISIBLE);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Toast.makeText(sakit.this, "o", Toast.LENGTH_SHORT).show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void getLokasi() {

        String lokasi = txt_lokasi.getText().toString().trim();
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://hrd.tvip.co.id/rest_server/master/karyawan/index?lokasi_struktur=" + lokasi, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getString("status").equals("true")) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            String karyawan = jsonObject1.getString("nama_karyawan_struktur");
                            String nik = jsonObject1.getString("nik_baru");
                            Karyawan.add(karyawan + " (" + nik + ") ");

                        }

                    }
                    spinner.setAdapter(new ArrayAdapter<String>(sakit.this, android.R.layout.simple_spinner_dropdown_item, Karyawan));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void getNo() {
        pDialog = new ProgressDialog(this);
        showDialog();
        pDialog.setContentView(R.layout.progress_dialog);
        pDialog.getWindow().setBackgroundDrawableResource(
                android.R.color.transparent
        );
        StringRequest stringRequest1 = new StringRequest(Request.Method.GET, "http://10.12.1.75/db_eis/izin_full_day.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj = new JSONObject(response);
                            JSONArray movieArray = obj.getJSONArray("data");

                            ///get last data only///
                            for (int i = 0; i < movieArray.length(); i++) {
                                JSONObject movieObject = movieArray.getJSONObject(i);
                                getNo_pengajuan_full nomor = new getNo_pengajuan_full(
                                        movieObject.getInt("no_pengajuan_full_day"));
                                no_pengajuan.add(nomor);
                            }
                            getNo_pengajuan_full item = no_pengajuan.get(no_pengajuan.size() - 1);

                            nopengajuan.setText(String.valueOf(item.getNo_pengajuan_full() + 1));
                            hideDialog();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Maaf, ada kesalahan", Toast.LENGTH_SHORT).show();
                    }
                });
        RequestQueue requestQueue1 = Volley.newRequestQueue(this);
        requestQueue1.add(stringRequest1);
    }


    private void postfull(){

        pDialog = new ProgressDialog(this);
        showDialog();
        pDialog.setContentView(R.layout.progress_dialog);
        pDialog.getWindow().setBackgroundDrawableResource(
                android.R.color.transparent
        );
        StringRequest stringRequest2 = new StringRequest(Request.Method.POST, "http://10.12.1.75/db_eis/izin_full_insert.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        hideDialog();
                        Toast.makeText(getApplicationContext(), "data sudah dimasukkan", Toast.LENGTH_LONG).show();
                        sakit.this.finish();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        hideDialog();
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String > params = new HashMap<String, String>();
                String pengajuan = nopengajuan.getText().toString();
                String nik_baru = getIntent().getStringExtra(KEY_NIK);
                String tanggal = editText.getText().toString();
                String jabatan = txt_nomor.getText().toString();
                String karyawan = spinner.getSelectedItem().toString();
                String[] splited_text = karyawan.split(" \\(");
                karyawan = splited_text[0];
                String keterangan_sakit = keterangan.getText().toString();
                String gambar = imagetoString(bitmap);

                params.put("no_pengajuan_full_day", pengajuan);
                params.put("nik_full_day", nik_baru);
                params.put("jabatan_full_day", jabatan);
                params.put("jenis_full_day","SA");

                params.put("start_full_day", tanggal);
                params.put("karyawan_pengganti", karyawan);
                params.put("ket_tambahan", keterangan_sakit);
                params.put("status_full_day","0");

                params.put("status_full_day_2","0");
                params.put("upload_full_day", gambar);

                return params;
            }

        };

        RequestQueue requestQueue2 = Volley.newRequestQueue(this);
        requestQueue2.add(stringRequest2);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
    private String imagetoString(Bitmap bitmap)
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, byteArrayOutputStream);
        byte[] imageType = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(imageType, Base64.DEFAULT);
    }
}




он сохраняет пост только один запрос

Что я уже пробовал:

add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout ll = (LinearLayout)findViewById(R.id.container);
                final EditText tanggal1 = new EditText(sakit.this);
                final TextView tanggald = new TextView(sakit.this);

                LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                tanggald.setLayoutParams(p);
                tanggald.setId(numberOfLines + 1);
                tanggald.setText("tanggal");

                tanggal1.setLayoutParams(p);
                tanggal1.setId(numberOfLines + 1);
                ll.addView(tanggald);

                ll.addView(tanggal1);
                tanggal1.setFocusable(false);
                numberOfLines++;

                tanggal1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final Calendar currentDate = Calendar.getInstance();
                        Calendar twoDaysAgo = (Calendar) currentDate.clone();
                        twoDaysAgo.add(Calendar.DATE, -3);

                        date = currentDate.getInstance();

                        DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                                date.set(year, monthOfYear, dayOfMonth );

                                tanggal1.setText(dateFormatter.format(date.getTime()));
                            }
                        };
                        DatePickerDialog datePickerDialog = new  DatePickerDialog(sakit.this, dateSetListener, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH),   currentDate.get(Calendar.DAY_OF_MONTH));
                        datePickerDialog.getDatePicker().setMinDate(twoDaysAgo.getTimeInMillis());
                        datePickerDialog.show();

                    }
                });
            }
        });


это я использовал для добавления textview для циклического запроса

0 Ответов