1

I want to send an imageview android image to my server url and store it into my server database(phpmyadmin). when i m trying to insert simple string then it works , but when it is image view then it does not..please help.. this is my code

public class AddnewActivity extends Activity {

      ImageView iv;

    public static final int PHOTO_PICKER_ID = 0;
    EditText name;
    EditText comments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addnew);
        // Show the Up button in the action bar.
        setupActionBar();
        iv=(ImageView) findViewById(R.id.imageView1);

        ImageButton imgb= (ImageButton) findViewById(R.id.imageButton1);
        imgb.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
            try{
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Complete action using"), PHOTO_PICKER_ID);
            }
            catch(Exception e){}

            }
        });



        Button save=(Button) findViewById(R.id.button1);
        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            try{


                Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);   
                ByteArrayOutputStream stream=new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
                byte[] imageByteArray=stream.toByteArray();

                String img_str = Base64.encodeToString(imageByteArray, 0);


            name=(EditText) findViewById(R.id.editText1);   
            String nm=name.getText().toString();
            comments=(EditText) findViewById(R.id.editText2);   
            String com=comments.getText().toString();

            if("".equals(nm) || "".equals(com)){

            Toast.makeText(getApplicationContext(), "Empty field detected", Toast.LENGTH_SHORT).show(); 
            }
            else{

                try {
                    JSONObject json = new JSONObject();
                    json.put("name", nm);
                    json.put("comments", com);
                    json.put("img", img_str);

                    HttpClient client = new DefaultHttpClient();
                    String url = "http://myservername/parser/json_req.php";

                    HttpPost request = new HttpPost(url);
                    request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
                    request.setHeader("json", json.toString());
                    HttpResponse response = client.execute(request);
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        InputStream instream = entity.getContent();


                        Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_SHORT).show(); 
                    }
                name.setText(null);
                comments.setText(null);    


                } catch (Throwable t) {

                    Toast.makeText(getApplicationContext(),  "Request failed: " + t.toString(), Toast.LENGTH_SHORT).show(); 
                }


            }

            }catch(Exception e){}   

            }
        });

    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }








      @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            Uri currImageURI = null;
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    currImageURI = data.getData();
                }
                if (currImageURI == null) {
                    String filePath = Environment.getExternalStorageDirectory()
                            + "";
                    filePath = filePath + File.separator + "temp_img.jpg";
                    File f = new File(filePath);

                    currImageURI = Uri.fromFile(f);
                }

                ContentResolver cr = getContentResolver();
                Bitmap bitmap;
                try {
                    bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr,currImageURI);
                    iv.setImageBitmap(bitmap);
                } catch (Exception e) {
                    Log.e("Camera", e.toString());
                }
            }
        }

















    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.addnew, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
1
  • Could u post the error which you are you getting. Commented Nov 28, 2013 at 5:33

2 Answers 2

1

You must use multipart entity to upload images. like as follows :-

public void postPicture(String path, File file) throws ParseException, IOException, XmlParseException {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost(path);
        MultipartEntity mpEntity = new MultipartEntity();
        FileBody cbFile = new FileBody(file, "image/png");
        cbFile.getMediaType();
        mpEntity.addPart("userfile", cbFile);
        httppost.setEntity(mpEntity);
        HttpResponse response = httpclient.execute(httppost);
    }

Here is simple tutorial for it

http://useandgain.blogspot.in/2012/06/uploading-image-from-androidjava-using.html

Sign up to request clarification or add additional context in comments.

1 Comment

Network call should not be made on UI thread.Use AsyncTask to call HttpResponse response = httpclient.execute(httppost);
0

use the code below, first you have to compress the photo and then convert bitmap(photo) into base64 and finally send it to server.

public String webServiceCall(String photo) {

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    nameValuePairs
            .add(new BasicNameValuePair("photo",  photo));
    String jsonresponse = getData(nameValuePairs);
    return jsonresponse;
}

public String getData(ArrayList<NameValuePair> params) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),
                10000);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        Log.d("In request :", params.toString());

        HttpResponse httpResponse = httpClient.execute(httpPost);
        Log.d("Response Output", httpResponse.toString());

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
        Log.d("Response Output", is.toString());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        jsonResponse = sb.toString();
        Log.e("JSON reading ", jsonResponse);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    return jsonResponse;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.