2

I am trying to develop a simple application that allows me to take a photo and upload that photo to my apache server via php web-services. I have read some tutorials and i'm trying it out, here's my code for android and php.

Android

package com.test.multipartupload;
import java.io.File;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class MainActivity extends AppCompatActivity {

    TextView textTargetUri;
    ImageView targetImage;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonLoadImage = (Button)findViewById(R.id.loadimage);
        textTargetUri = (TextView)findViewById(R.id.targeturi);
        targetImage = (ImageView)findViewById(R.id.targetimage);

        buttonLoadImage.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 0);
            }});
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK){
            Uri targetUri = data.getData();
            textTargetUri.setText(targetUri.toString());
            Bitmap bitmap;
            try {
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
                targetImage.setImageBitmap(bitmap);


                try
                {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost("http://192.168.1.36/postImage.php");

                    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
                    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                    entityBuilder.addTextBody("USERNAME", "TEST");
                    entityBuilder.addTextBody("NAME", "admin");
                    File file = new File(targetUri.getPath());

                    Log.d("MainActivity", targetUri.getPath());

                    if(file != null)
                    {
                        entityBuilder.addBinaryBody("IMAGE", file);
                    }

                    //ERROR HERE  java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/message/BasicHeaderValueFormatter; in class Lorg/apache/http/message/BasicHeaderValueFormatter; or its superclasses (declaration of 'org.apache.http.message.BasicHeaderValueFormatter' appears in /system/framework/org.apache.http.legacy.boot.jar)

                    HttpEntity entity = entityBuilder.build();
                    post.setEntity(entity);
                    HttpResponse response = client.execute(post);
                    HttpEntity httpEntity = response.getEntity();
                    String result = EntityUtils.toString(httpEntity);
                    Log.v("result", result);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Php

<?php
        $username = $_POST['USERNAME'];
        $name = $_POST['NAME'];
        $type = $_FILES['IMAGE']['type'];
        $size = $_FILES['IMAGE']['size'];

        $target = "profilepicture/" . $username . "_" . $name . ".jpeg";
        $tmpfile = $_FILES['IMAGE']['tmp_name'];

        $result = move_uploaded_file($tmpfile, $target);
?>

My android gradle

apply plugin: 'com.android.application'

android {
    useLibrary 'org.apache.http.legacy'
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.test.multipartupload"
        minSdkVersion 22
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'

    testCompile 'junit:junit:4.12'
}

LAYOUT

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello"
        android:background="@drawable/back"
        />
    <Button
        android:id="@+id/loadimage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Load Image"
        />
    <TextView
        android:id="@+id/targeturi"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

    <ImageView
        android:id="@+id/targetimage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />
</LinearLayout>

Do note that i am able to compile and run this set of codes, it only crashes after i've selected the image

Error Stacktrace

01-20 22:51:36.726 11378-11378/sg.edu.nyp.multipartupload E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: sg.edu.nyp.multipartupload, PID: 11378
                                                                            java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/message/BasicHeaderValueFormatter; in class Lorg/apache/http/message/BasicHeaderValueFormatter; or its superclasses (declaration of 'org.apache.http.message.BasicHeaderValueFormatter' appears in /system/framework/org.apache.http.legacy.boot.jar)
                                                                                at org.apache.http.entity.ContentType.toString(ContentType.java:153)
                                                                                at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:56)
                                                                                at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
                                                                                at org.apache.http.entity.mime.MultipartEntityBuilder.build(MultipartEntityBuilder.java:240)
                                                                                at sg.edu.nyp.multipartupload.MainActivity.onActivityResult(MainActivity.java:86)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6479)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3884)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3931)
                                                                                at android.app.ActivityThread.access$1400(ActivityThread.java:180)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1524)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                                at android.os.Looper.loop(Looper.java:207)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5710)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
  • Please, post your stacktrace –  Ekalips Jan 20 '17 at 15:21
  • I can assume, than you didn't get internet access in your's app manifest –  Ekalips Jan 20 '17 at 15:23
  • @Ekalips Oh yeah! I totally forgot to add the permission. ps! Thanks! I'll try out . –  Jan 20 '17 at 15:34
  • Also, package `org.apache.http` is removed from Android starting from 6 version (as I remember), so you mustn't use it, that's why you getting an error. –  Ekalips Jan 20 '17 at 15:40
  • @Ekalips any suggestion on what should i replace org.apache.http with? –  Jan 20 '17 at 15:41
  • Use Volley or Retrofit for it. For now it's 2 best libraries to work with network. They can handle loading and sending data in few lines of code. –  Ekalips Jan 20 '17 at 15:47
  • @Ekalips ah, I have came by articles that talks about these library, however I'm not quite sure how do I start. Such as, where to download these libraries, and how to implement... –  Jan 20 '17 at 15:53
  • https://developer.android.com/training/volley/index.html this is volley http://stackoverflow.com/questions/32262829/how-to-upload-file-using-volley-library-in-android about sending files –  Ekalips Jan 20 '17 at 15:57
  • @Ekalips wow, thank you!!! I'll try to implement it via volley instead!!! –  Jan 20 '17 at 15:57

0 Answers0