2

In my code i am having two images and two edittext fields to send to the database using php file.Here in my code i am able to insert 2 images along with the edittext fileds without any problem. Now whats my problem is when a user enters two edittext fields and selects only one image to insert, it is throwing NullPointerException.Here with this code i have to select 2 images mandatorily..how can i make that one optional.?I mean user can select one/two image based on his requirement.But if i select only one image,it is throwing null pointer exception.please help me..!!

MainActivity.java

package com.example.test;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

public class MainActivity extends Activity implements View.OnClickListener {

    private Button buttonUpload;
    private Button buttonChoose;
    private Button buttonChoose1;

    private EditText edithouse;
    private EditText editbuild;
    private ImageView imageView;
    private ImageView imageView1;

    public static final String KEY_IMAGE = "image";
    public static final String KEY_IMAGE1 = "image1";
    public static final String KEY_TEXT = "house";
    public static final String KEY_TEXT1 = "build";
    public static final String UPLOAD_URL = "http://oursite/PhotoUploadWithText/upload.php";

    private int PICK_IMAGE_REQUEST = 1;
    private int PICK_IMAGE_REQUEST1 = 2;

    private Bitmap bitmap;
    private Bitmap bitmap1;

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

        buttonUpload = (Button) findViewById(R.id.save);
        buttonChoose = (Button) findViewById(R.id.choose);
        buttonChoose1 = (Button) findViewById(R.id.choose1);

        edithouse = (EditText) findViewById(R.id.houseno);
        editbuild = (EditText) findViewById(R.id.buildno);
        imageView = (ImageView) findViewById(R.id.imageViews);
        imageView1 = (ImageView) findViewById(R.id.imageViews1);

        buttonChoose.setOnClickListener(this);
        buttonChoose1.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
          private void showFileChooser1() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST1);
        }

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

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);
               // imageView1.setImageBitmap(bitmap1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (requestCode == PICK_IMAGE_REQUEST1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //imageView.setImageBitmap(bitmap);
                imageView1.setImageBitmap(bitmap1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    public String getStringImage1(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }


    public void uploadImage(){
        final String house = edithouse.getText().toString().trim();
        final String build = editbuild.getText().toString().trim();
        final String image = getStringImage(bitmap);
        final String image1 = getStringImage1(bitmap1);
        class UploadImage extends AsyncTask<Void,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this,"Please wait...","uploading",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                HashMap<String,String> param = new HashMap<String,String>();
                param.put(KEY_TEXT,house);
                param.put(KEY_TEXT1,build);
                param.put(KEY_IMAGE,image);
                param.put(KEY_IMAGE1,image1);
                String result = rh.sendPostRequest(UPLOAD_URL, param);
                return result;
            }
        }
        UploadImage u = new UploadImage();
        u.execute();
    }


    @Override
    public void onClick(View v) {
        if(v == buttonChoose){
            showFileChooser();
        }
        if(v == buttonUpload){
            uploadImage();
        }
        if(v == buttonChoose1){
            showFileChooser1();
        }
    }
}

upload.php

<?php

    if($_SERVER['REQUEST_METHOD']=='POST'){
        $image = $_POST['image'];
        $house = $_POST['house '];
        $image1 = $_POST['image1'];
        $build = $_POST['build '];

        require_once('dbConnect.php');

        $sql ="SELECT id FROM uploads ORDER BY id ASC";

        $res = mysqli_query($con,$sql);

         $id = uniqid();

        while($row = mysqli_fetch_array($res)){
                $id = $row['id'];
        }

        $path = "uploads/".uniqid().".png";
                $path1 = "uploads/".uniqid().".png";

        $actualpath  = "$path";
        $actualpath1  = "$path1";

        $sql = "INSERT INTO uploads (image,house,image1,build) VALUES ('$actualpath','$house','$actualpath1','$build')";

        if(mysqli_query($con,$sql)){
            file_put_contents($path,base64_decode($image));
                        file_put_contents($path1,base64_decode($image1));
            echo "Successfully Uploaded";
        }

        mysqli_close($con);
    }else{
        echo "Error";
    }
?>

Here is the error.. Logcat

02-17 17:28:33.261: E/AndroidRuntime(14710): FATAL EXCEPTION: main
02-17 17:28:33.261: E/AndroidRuntime(14710): java.lang.NullPointerException
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.example.test.MainActivity.getStringImage1(MainActivity.java:118)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.example.test.MainActivity.uploadImage(MainActivity.java:129)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.example.test.MainActivity.onClick(MainActivity.java:168)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.view.View.performClick(View.java:4191)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.view.View$PerformClick.run(View.java:17229)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.os.Handler.handleCallback(Handler.java:615)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.os.Handler.dispatchMessage(Handler.java:92)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.os.Looper.loop(Looper.java:137)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.app.ActivityThread.main(ActivityThread.java:4960)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at java.lang.reflect.Method.invokeNative(Native Method)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at java.lang.reflect.Method.invoke(Method.java:511)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at dalvik.system.NativeStart.main(Native Method)

2 Answers 2

1

When you call public void uploadImage() check

String image = null;
String image1 = null;
    if(bitmap != null)
        image = getStringImage(bitmap);
    if(bitmap1 != null)
        image1 = getStringImage1(bitmap1);

also Check

if(image != null)
    param.put(KEY_IMAGE,image);
if(image1 != null)
    param.put(KEY_IMAGE1,image1);

String result = rh.sendPostRequest(UPLOAD_URL, param);

and then also in php check if

KEY_IMAGE

and

KEY_IMAGE1

exists then do whatever you want to do, otherwise php will throw an error for undefined index.

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

3 Comments

In doInBackground(Void... params) method..if i use param.put(KEY_IMAGE,image); ..it is asking to change modifier of image and image1 to final..But in uploadImage() method if i declare as final.inside if statement it is throwing error..
make image and image1 global varibales
Glad i could help, Happy coding :)
1

You are selecting one image and uploading two in uploadimage method...

just use below code it will work for you..

String image1 = "";
     if(bitmap1!=null)
     image1 = getStringImage1(bitmap1);

1 Comment

In doInBackground(Void... params) method..if i use param.put(KEY_IMAGE1,image1); ..it is asking to change modifier of image1 to final..But in uploadImage() method if i declare as final.inside if statement it is throwing errors for image1

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.