• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

How to upload JSON Data and Image to php server Sucessfully

So looking at your screenshot #3, what value do you think is null, and how would you fix this?

Hi can you please check this once . i have solved null pointer exception, but again am getting secret_key not match from response please check this am attaching total activity code.

Code:
package com.example.qrcode;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io_OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import static com.example.qrcode.ApplicationConstant.secret_key;


public class Display extends AppCompatActivity {
    private static final String TAG = Display.class.getSimpleName();
    TextView textview1,textview;
    ImageView image;

    @SuppressLint("SetTextI18n")
    [USER=1021285]@override[/USER]
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_display );

        image = (ImageView) findViewById( R.id.imageView );
        textview1 = (TextView) findViewById( R.id.textview1 );
        textview = (TextView) findViewById( R.id.textview );


        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            Bitmap bmp = (Bitmap) extras.getParcelable( "Bitmap" );
            image.setImageBitmap( bmp );
            //display compressed image size in textview
            long height = bmp.getHeight();
            long width = bmp.getWidth();
            long filesizeinBytes1 = bmp.getByteCount();
            long fileSizeInKB1 = filesizeinBytes1 / 1024;
            textview1.setText( " Height:" + height + "Width" + width + "size in KB:  " + fileSizeInKB1 );
            Log.d( TAG, "Textview message :" + height + " , " + width + " , " + fileSizeInKB1 );

            File destination = new File( Environment.getExternalStorageDirectory(), "temp.jpg" );
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            FileOutputStream fo;
            try {
                fo = new FileOutputStream( destination );
                fo.write( bytes.toByteArray() );
                fo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            SharedPreferences prefs = getSharedPreferences( "json_data_file", MODE_PRIVATE );
            String user_data = prefs.getString( "user_data", null );
            String Question_id = prefs.getString( "Question_id", null );
            String paper_id = prefs.getString( "paper_id", null );
            textview.setText( "user_id = " + user_data + "\n Question_id = " + Question_id + "\n paper_id = " + paper_id );

            String filename = destination.getAbsolutePath();
            // String file= String.format( "%s%s", filename, textview );
            // Log.d( TAG,"file is" +file );
            File file = null;
            try {
                file = new File( Environment.getExternalStorageDirectory(), "Notes" );
                FileWriter writer = new FileWriter( file );
                writer.append( filename );
                writer.append( user_data );
                writer.append( Question_id );
                writer.append( paper_id );
                writer.flush();
                writer.close();
                Log.d( TAG,"file is" +file );
            } catch (IOException e) {
                e.printStackTrace();
            }

            // new uploadFileToServerTask().execute( destination.getAbsolutePath() );
            new uploadFileToServerTask().execute( String.valueOf( file ) );


        }

    }

    private class uploadFileToServerTask extends AsyncTask <String, String, Object> {
        DataOutputStream outputStream = null;
        [USER=1021285]@override[/USER]
        protected String doInBackground(String... args) {
            try {
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                @SuppressWarnings("PointlessArithmeticExpression")
                int maxBufferSize = 1 * 1024 * 1024;
                String result = "";
                String file = args[0];

                java.net.URL url = new URL( ApplicationConstant.BASE_URL );
                Log.d( ApplicationConstant.TAG, "url " + url );
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

          // Allow Inputs &amp; Outputs.
                connection.setDoInput( true );
                connection.setDoOutput( true );
                connection.setUseCaches( false );

                // Set HTTP method to POST.
                connection.setRequestMethod( "POST" );
                connection.setRequestProperty( "Connection", "Keep-Alive" );
                connection.setRequestProperty("Accept", "application/xml");
                connection.setRequestProperty( "Content-Type", "multipart/form-data;boundary=" + boundary );
                //connection.setRequestProperty( "secret_key", secret_key);
                FileInputStream fileInputStream;
                {
                    try {
                        outputStream= new DataOutputStream( connection.getOutputStream() );
                        outputStream.writeBytes( twoHyphens + boundary + lineEnd );
                        outputStream.writeBytes( "Content-Disposition: form-data; name=\"file\";file=\"" + file + "\"" + lineEnd );
                        outputStream.writeBytes( lineEnd );
                        outputStream.writeBytes( twoHyphens + boundary + lineEnd );
                        outputStream.writeBytes( "Content-Disposition: form-data; name=\"secret_key\";Value=\"" +secret_key + "\"" + lineEnd );
                        //outputStream.writeBytes( query );
                        Log.d( ApplicationConstant.TAG, "file " + file );
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }

                    fileInputStream = new FileInputStream( file );

                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min( bytesAvailable, maxBufferSize );

                    buffer = new byte[bufferSize];
                    // Read file
                    // bytesRead = fileInputStream.read( buffer, 0, bufferSize );
                    outputStream.write( buffer, 0, bufferSize );
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min( bytesAvailable, maxBufferSize );
                    bytesRead = fileInputStream.read( buffer, 0, bufferSize );

                    outputStream.writeBytes( lineEnd );
                    outputStream.writeBytes( twoHyphens + boundary + twoHyphens + lineEnd );
                }
                int serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();
                Log.d( "serverResponseCode", "" + serverResponseCode );
                Log.d( "serverResponseMessage", "" + serverResponseMessage );

                //Response from server
                String response = "";
                if (serverResponseCode == HttpURLConnection.HTTP_OK) {
                    InputStream responseStream = new
                            BufferedInputStream( connection.getInputStream());

                    BufferedReader responseStreamReader =
                            new BufferedReader( new InputStreamReader( responseStream ));

                    String line = "";
                    StringBuilder stringBuilder = new StringBuilder();

                    while ((line = responseStreamReader.readLine()) != null) {
                        stringBuilder.append( line ).append( "\n" );
                    }
                    responseStreamReader.close();

                    response = stringBuilder.toString();
                    connection.disconnect();
                    fileInputStream.close();
                    outputStream.flush();
                    outputStream.close();

                    if (serverResponseCode == 200) {

                        return "true";
                    }
                } else {
                    throw new IOException( "Server returned non-OK status: " + serverResponseCode );
                }

                return response;
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (ProtocolException e1) {
                e1.printStackTrace();
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }catch(
                    Exception e)

            {
                e.printStackTrace();
            }
            return"false";
        }

        }

    }
 
Last edited:
Upvote 0
please check i have changed the formate

please see this guys . am getting please send required fields as response ffrom server. what is that am missing.

Code:
        FileInputStream fileInputStream = new FileInputStream( file );

        JSONObject postDataParams = new JSONObject();
        postDataParams.put("secret_key", "hqGM63U2QWIA");
        postDataParams.put("file", fileInputStream);
        Log.e("params",postDataParams.toString());

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        //conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        //os.write( Integer.parseInt( "Content-Disposition: form-data; name=\"file\";file=\"" +file + "\"" +lineEnd ) );
        writer.write(getPostDataString(postDataParams));
        writer.flush();
        writer.close();
        os.close();
        fileInputStream.close();

        int responseCode=conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        Log.d( "serverResponseCode", "" + responseCode );
        Log.d( "serverResponseMessage", "" + serverResponseMessage );

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            BufferedReader in=new BufferedReader(new
                    InputStreamReader(
                    conn.getInputStream()));

            StringBuffer sb = new StringBuffer("");
            String line="";

            while((line = in.readLine()) != null) {

                sb.append(line);
                break;
            }

            in.close();
            return sb.toString();

        }
        else {
            return new String("false : "+responseCode);
        }
    }
    catch(Exception e){
        return new String("Exception: " + e.getMessage());
    }

}
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones