Search code examples
androidandroid-studiourlion-koush

How to build a URL in Koush ion


I am building an app to upload images to my company server I am using koush-ion for the upload, now my problem is I have to dynamically change the URL for upload depending on information entered in another activity(LoginActivity) via edittext boxes and I don't understand how to do that so what I want to happen is the client enters thier Email, password and clientID(4 digits)(in LoginActivity) and the app uses that to build a url for the upload like this one(in CameraActivity) https://www.blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes&ClientID=1234&[email protected]&Pwd=BlahBlah123@

I got this From the koush github, and i am unsure if this is what i am looking for and also how to implement data from another activity in koush-ion

Post application/x-www-form-urlencoded and read a String

 Ion.with(getContext())
   .load("https://koush.clockworkmod.com/test/echo")
   .setBodyParameter("goop", "noop")
   .setBodyParameter("foo", "bar")
   .asString()
   .setCallback(...)

Camera Activity

  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;

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        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);


        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() {

I want to call the url here

  File imageFile = persistImage(bitmap, "SP_Upload");
        Ion.with(this)
                .load("https://www.Blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes")
                .setMultipartFile("SP-LOG", "image/jpeg", imageFile)
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {

                    }
                });
    }

    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);
        }
    }
}

LoginActivity

     public class LoginActivity extends AppCompatActivity {

    private EditText email, password, id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        email=findViewById(R.id.emailtext);
        password=findViewById(R.id.pwdtext);
        id=findViewById(R.id.clientid);
        Button loginBtn=findViewById(R.id.button);

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String emailAddress=email.getText().toString().trim();
                String userPassword=password.getText().toString().trim();
                String clientId=id.getText().toString().trim();
                Intent intent=new Intent(LoginActivity.this, CameraActivity.class);
                intent.putExtra("clientId", clientId);
                intent.putExtra("email", emailAddress);
                intent.putExtra("password", userPassword);
                startActivity(intent);
            }
        });
    }
}

Solution

  • You could store the url on the shared preferences and retrieve it every time you execute your upload task and set it on the .load() method.

    Also, what you need to send an image to your server is a multipart post. I haven't used Ion but I have used multipart in other libraries like OkHttp, I´ve copied the method that appears on the Ion documentation:

    String dynamicUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(CURRENT_SELECTED_URL, null);
    File myImage = new File(myImagePath);
    
    if(dynamicUrl != null) {
        Ion.with(getContext())
        .load(dynamicUrl)
        .uploadProgressBar(uploadProgressBar)
        .setMultipartParameter("goop", "noop")
        .setMultipartFile("myImageName", "image/*", myImage)
        .asJsonObject()
        .setCallback(...)
    }