0

I am building an app to upload images to my company server, Now the URL for said upload is being generated with URI.builder using data from a login screen, and 2 Spinners,The spinners are in a seprate activity(TimeLogActvity) and the URI.Builder is in(Camra Activity) At the moment the data from the spinners are being passed to the URI.builder using intents.and using getSelectedItem.toString to pass the data to a string and calll within URI.builder,

Now my Question is, I am using JSON data from the server to populate the spinners, SO the one spinner has a client Name , the issue I can't figure out is I have to pass a value to the uri.builder, but The json has 2 values for each Client, The Name and its Client ID, So What I want to do is the spinner must show the client name BUT the data being passed to the uri builder must only be the ClientID,I have tried to google this but I can't find anything that is of help

activity TmeLogActivity houses the spinners

public class TimeLogActivity extends AppCompatActivity {
Spinner spinner;
    Spinner spinner2;
    String URL="placeURLHERE";
    String URL2="PLACEURLHERE";
    ArrayList<String> CountryName;
    ArrayList<String> ClientName;
    String Item;
    String Item2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_log);
        CountryName=new ArrayList<>();
        ClientName=new ArrayList<>();
        spinner=findViewById(R.id.spinner);
        spinner2=findViewById(R.id.spinner2);
        Button button23=findViewById(R.id.button1234);
        button23.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


                Intent intent=new Intent(TimeLogActivity.this,
                        CameraActivity.class);
                intent.putExtra("Spinner", Item);
                intent.putExtra("Spinner2", Item2);

                startActivity(intent);
            }
        });


        loadSpinnerData(URL);
        loadSpinnerData2(URL2);

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


            }

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


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


            }

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


            }

        });

    }

    private void loadSpinnerData(String url) {

        RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                String array=response.substring(47);


                try {
                    JSONObject jsonObject=new JSONObject(array);

                    if (jsonObject.getInt("success") == 1) {

                        JSONArray jsonArray=jsonObject.getJSONArray("Name");
                        for (int i=0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1=jsonArray.getJSONObject(i);

                            String country=jsonObject1.getString("Country");
                            CountryName.add(country);
                        }
                    }
                    spinner.setAdapter(new ArrayAdapter<String>(TimeLogActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        int socketTimeout=30000;
        RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);

        requestQueue.add(stringRequest);


    }

    private void loadSpinnerData2(String url) {

        RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                String array=response.substring(47);


                try {
                    JSONObject jsonObject=new JSONObject(array);

                    if (jsonObject.getInt("success") == 1) {

                        JSONArray jsonArray=jsonObject.getJSONArray("Name");
                        for (int i=0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1=jsonArray.getJSONObject(i);

                            String clientName=jsonObject1.getString("ClientName");
                            ClientName.add(clientName);
                        }
                    }
                    spinner2.setAdapter(new ArrayAdapter<String>(TimeLogActivity.this, android.R.layout.simple_spinner_dropdown_item, ClientName));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        int socketTimeout=30000;
        RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);

        requestQueue.add(stringRequest);
    }
}

CameraActivity houses the URI.Builder and upload,camera functions

public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
    private final int PICK_IMAGE=12345;
    private final int REQUEST_CAMERA=6352;
    private static final int REQUEST_CAMERA_ACCESS_PERMISSION=5674;
    private Bitmap bitmap;

    String myURL;
    String clientId;
    String email;
    String pwd;


    private ImageView imageView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        Intent intent = getIntent();
        clientId = intent.getStringExtra("clientId");
         email = intent.getStringExtra("email");
        pwd = intent.getStringExtra("pass");


        imageView=findViewById(R.id.imageView);
        Button fromCamera=findViewById(R.id.fromCamera);
        Button fromGallery=findViewById(R.id.fromGallery);
        Button upload=findViewById(R.id.upload);
        upload.setOnClickListener(this);
        fromCamera.setOnClickListener(this);
        fromGallery.setOnClickListener(this);
        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            String clientID = extras.getString("KEY");
        }



        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            fromCamera.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View view) {



        switch (view.getId()) {
            case R.id.fromCamera:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                        && ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA},
                            REQUEST_CAMERA_ACCESS_PERMISSION);
                } else {
                    getImageFromCamera();
                }
                break;
            case R.id.fromGallery:
                getImageFromGallery();
                break;
            case R.id.upload:
                if (bitmap != null)
                    uploadImageToServer();
                break;

        }


    }


    private void uploadImageToServer() {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
        String currentTimeStamp = dateFormat.format(new Date());
        final ProgressDialog pd=new ProgressDialog(CameraActivity.this);
        pd.setMessage("Uploading, Please Wait....");
        pd.show();
        Intent intent = getIntent();
        String Item= intent.getStringExtra("Spinner");
        String Item2= intent.getStringExtra("Spinner2");


        Uri.Builder builder=new Uri.Builder();
        builder.scheme("https")
                .authority("www.smartpractice.co.za")
                .appendPath("files-upload-ruben.asp")
                .appendQueryParameter("MyForm", "Yes")
                .appendQueryParameter("ClientID",clientId)
                .appendQueryParameter("Username", email)
                .appendQueryParameter("Pwd", pwd)
        .appendQueryParameter("category",Item )
        .appendQueryParameter("client",Item2 );
        myURL=builder.build().toString();
        Toast toast = Toast.makeText(CameraActivity.this, myURL , Toast.LENGTH_LONG);
        toast.show();

        File imageFile=persistImage(bitmap,currentTimeStamp);

        Ion.with(this)
                .load(myURL)
                .uploadProgressDialog(pd)
                .setMultipartFile("SP-LOG", "image/jpeg", imageFile)


                .asString()


                .setCallback(new FutureCallback<String>() {
                    @Override
                    public void onCompleted(Exception e, String result) {
                     pd.cancel();
                        Toast.makeText(getApplicationContext(),"Uploaded",Toast.LENGTH_SHORT).show();

                    }
                });

    }

    private File persistImage(Bitmap bitmap, String name) {
        File filesDir=getApplicationContext().getFilesDir();
        File imageFile=new File(filesDir, name + ".jpg");

        OutputStream os;
        try {
            os=new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }

        return imageFile;
    }


    private void getImageFromCamera() {
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    private void getImageFromGallery() {
        Intent intent=new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE) {
            if (resultCode == Activity.RESULT_OK) {
                try {
                    InputStream inputStream=getContentResolver().openInputStream(data.getData());
                    bitmap=BitmapFactory.decodeStream(inputStream);
                    imageView.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        } else if (requestCode == REQUEST_CAMERA) {
            if (resultCode == Activity.RESULT_OK) {
                Bundle extras=data.getExtras();
                bitmap=(Bitmap) extras.get("data");
                imageView.setImageBitmap(bitmap);
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getImageFromCamera();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        }
    }
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ruben Meiring
  • 333
  • 2
  • 21
  • Create a class ClinetInfo to store json data for each client and implement spinner adapter and show only client name. and when user select spinner item then get the ClinetInfo object and pass the object to another activity. Make sure your clientInfo boject is parcelable – dastan Aug 15 '19 at 08:16
  • @dastan I only have been doing coding for about 2 weeks, can you expand on this please? – Ruben Meiring Aug 15 '19 at 09:06
  • How about your concept? creating class and creating spinner adapter , can you write by yourself ? – dastan Aug 15 '19 at 09:33
  • @dastan to an extent yes, if you can link me an example or something it will help – Ruben Meiring Aug 15 '19 at 09:33
  • okay check this example if you can manage to convert your above code to this then there is a little change in onItemSelected(), in onitemSelected in this example its reading text from textview but you need whole object ClientInfo https://www.zoftino.com/android-spinner-custom-adapter-&-layout – dastan Aug 15 '19 at 09:35
  • To get the clientInfo object you can do one one thing store this in public arralist for ex. ```arrayList=CouponStoreData.getOfferData() new CustomArrayAdapter(this, R.layout.customspinneritem, arrayList);``` then in onItemSelected(,,pos,); your 3rd param is position so you can easily get the whole object by calling ClientInfo clientInfo=arrayList.get(pos)``` then you can access your clientInfoId and can pass to another activiy or pass whole clientInfo object to anotheractivity – dastan Aug 15 '19 at 09:39

2 Answers2

0

Sounds like you didn't use spinner well,have a look at How to create Spinner-list using CustomAdapter in android ,a custom Adapter should answer your question

邵传超
  • 11
  • 3
0

Just follow this example and add this method in CustomArrayAdapter

Offer getItem(position){
   return items.get(position);
}

and in onItemSelected add this code

void onItemSelected(parent,view,position,id){
  Offer offer=customArrayAdapter.getItem(position);
}

If this work, then you can convert Offer to your Client class. Hope this might help

dastan
  • 892
  • 10
  • 17
  • Thanks for the Advice me and my Supervisor decided we are going to do it server side so no need fpr extra code in the app – Ruben Meiring Aug 15 '19 at 13:47