Uploading data via a post method to a server Android Studio

Viewed 2271

I'm trying to upload an image to a server via a POST request in android studio and I'm totally stuck. The console gives me no information that could indicate whats going wrong and when i click upload it just doesn't work.

Here's the code:

public class UploadActivity extends AppCompatActivity implements View.OnClickListener {
ImageView imageToUpload;
Button uploadButton;
EditText imageNameText;
ImageButton backButton;
private static final int RESULT_LOAD_IMAGE=1;
private static final String SERVER_ADDESS = "http://lukertestsite.000webhostapp.com/";      // address of my free 000webhost domain


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

    imageToUpload = (ImageView)findViewById(R.id.imageToUpload);
    uploadButton = (Button)findViewById(R.id.uploadImageButton);
    imageNameText = (EditText)findViewById(R.id.imageName);
    backButton = (ImageButton)findViewById(R.id.returnButton);




    // set a listener for each button that will pass this as the view, since this class implements listener
    imageToUpload.setOnClickListener(this);
    uploadButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.imageToUpload:
            Intent localImagesIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(localImagesIntent, RESULT_LOAD_IMAGE);

            break;
        case R.id.uploadImageButton:
            Bitmap pic = ((BitmapDrawable) imageToUpload.getDrawable()).getBitmap();        // grab the pic as a bitmap
            new UploadImage(pic,imageNameText.getText().toString()).execute();
            break;

        case R.id.returnButton:

            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == RESULT_LOAD_IMAGE && resultCode==RESULT_OK && data!=null) {        // ensuring the gallery intent is what calls the method, and the result is ok and data is passed i.e. not null
        Uri selectedImage = data.getData();                             // making a uniform result (basically a pointer to the image)
        imageToUpload.setImageURI(selectedImage);           // set the image to upload display to the selected image.
    }
}



// asynch task to commiunicate with server in the background

private class UploadImage extends AsyncTask<Void,Void,Void>{
    Bitmap image;
    String name;


    public UploadImage(Bitmap image, String name){
        this.image=image;
        this.name=name;

    }

    @Override
    protected Void doInBackground(Void... voids) {
        // encode image in base 64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        image.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);    // compress as a png into bytearraystream
        String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);

        ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("image",encodedImage));
        dataToSend.add(new BasicNameValuePair("name",name));

        HttpParams httpRequestParams = getHttpRequestParams();
        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost(SERVER_ADDESS + "UploadPic.php");

        try{
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            System.out.println("set post entity");
            client.execute(post);
            System.out.println("executing post");
        }catch (Exception e){
            e.printStackTrace();
        }



        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Toast.makeText(getApplicationContext(),"Your pic was uploaded",Toast.LENGTH_SHORT);     //Toast to alert user their file was uploaded
        System.out.println("toasted");
    }
}

private HttpParams getHttpRequestParams(){

    System.out.println("getting request params");
    HttpParams httpRequestParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpRequestParams,1000*40);
    HttpConnectionParams.setSoTimeout(httpRequestParams,1000*40);

    return httpRequestParams;
}

And here's the output i get in the console.

> Connected to process 13772 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/ample.picloade: The ClassLoaderContext is a special shared library.
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/ample.picloade: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/ample.picloade: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xf0cd5a30, tid 13864
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xf0ae20c0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xf0ae20c0: ver 2 0 (tinfo 0xf0e1e7f0) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
    HostConnection::get() New Host Connection established 0xf0cd5af0, tid 13864
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fa2b4000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2 
I/Choreographer: Skipped 122 frames!  The application may be doing too much work on its main thread.
W/ample.picloade: JNI critical lock held for 65.664ms on Thread[1,tid=13772,Runnable,Thread*=0xe2cc4610,peer=0x71ffe018,"main"]
I/AssistStructure: Flattened final assist data: 1464 bytes, containing 1 windows, 9 views
I/System.out: getting request params
I/System.out: set post entity
I/System.out: executing post
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10152; state: ENABLED
I/System.out: toasted

And here's the PHP file that's used in the code:

<?php 
if(isset($_POST['name'])){ $name = $_POST['name']; }
if(isset($_POST['image'])){ $image = $_POST['image']; }

$decodedImage = base64_decode("$image");
file_put_contents("picbox_pics/" . $name . ".PNG", $decodedImage);

?>

Any idea's would be greatly appreciated, as I've been stuck for a day or so now. I think it may have something to do with the "D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10152; state: ENABLED" that happens just when the toast should (or at least some time before my "toasted" print), but I can't turn that option off in the emulator, and I'm not even sure that's the issue.

EDIT: heres the php output:

Notice: Undefined index: name in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 2

Notice: Undefined index: image in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 3
Here is some more debugging info:Array ( )
Warning: file_put_contents(picbox_pics/.PNG): failed to open stream: No such file or directory in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 9
1 Answers

You didn't call show() on the toast that is why it doesn't show. should be like this: Toast.makeText(getApplicationContext(),"Your pic was uploaded",Toast.LENGTH_SHORT).show();

Related