0

I have a class extends View and I do my drawings there.I open another activity from menu after I finished my drawing. In second activity, there is editText field for username and there is also a save button. I want to make them saved to my SQLite database, first drawing and then the image related to user. How can I do that ? Now this is my code currently and I'm getting an error.

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context com.example.mydrawingapp.View.AppView.getContext()' on a null object reference
        at com.example.mydrawingapp.SecondActivity$1.onClick(SecondActivity.java:31)

My Database Helper class:

   public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "drawingApp.db";
            public static final String TABLE_NAME="saveUser";
    public static final String COL_1 = "ID";
    public static final String COL_2="username";
    public static final String COL_3="image";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null,1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE saveUser (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT,image BLOB)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
       onCreate(db);
    }

    public long addImage(String user, byte[] image){
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("username",user);
        contentValues.put("image",image);
        long res = database.insert("saveUser",null,contentValues);
        database.close();
        return res;
    }
}

This is the code that I have in my Second Activity class:

        public class SecondActivity extends AppCompatActivity {
    private EditText textUsername;
    private Button buttonRegister;
    private String username;
    private AppView appView;
    private DatabaseHelper dbHelper;
    private  byte[] image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        textUsername = (EditText) findViewById(R.id.editText);
        username = textUsername.getText().toString();
        buttonRegister=(Button) findViewById(R.id.saveButton);

        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                appView= new AppView(appView.getContext(),null );
                image = appView.saveImage();
                dbHelper.addImage(username,image);
            }
        });
    }
}

Main Activity:

   public class MainActivity extends AppCompatActivity {
    private AppView appView;
    private AlertDialog.Builder currentAlertDialog;
    private ImageView widthImageView;
    private AlertDialog dialogLineWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        appView = findViewById(R.id.view);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);


        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.clearId:
                appView.clear();
                break;
            case R.id.saveId:
                openLoginDialog();
                break;

            case R.id.lineWidth:
                showLineWidthDialog();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void openLoginDialog() {
        Intent intent = new Intent(this,SecondActivity.class);
        startActivity(intent);
    }

    void showLineWidthDialog() {
        currentAlertDialog = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.width_dialog, null);
        final SeekBar widthSeekBar = view.findViewById(R.id.widthSeekBar);
        Button setLineWidthButton = view.findViewById(R.id.widthDialogButton);
        widthImageView = view.findViewById(R.id.imageViewId);
        setLineWidthButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appView.setLineWidth(widthSeekBar.getProgress());
                dialogLineWidth.dismiss();
                currentAlertDialog = null;

            }
        });


        widthSeekBar.setOnSeekBarChangeListener(widthSeekBarChange);


        currentAlertDialog.setView(view);
        dialogLineWidth = currentAlertDialog.create();
        dialogLineWidth.setTitle("Set Line Width");
        dialogLineWidth.show();
    }

    SeekBar.OnSeekBarChangeListener widthSeekBarChange = new SeekBar.OnSeekBarChangeListener() {
        Bitmap bitmap = Bitmap.createBitmap(400, 100, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);



        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            Paint p = new Paint();
            p.setColor(appView.getDrawingColor());
            p.setStrokeCap(Paint.Cap.ROUND);
            p.setStrokeWidth(progress);
            bitmap.eraseColor(Color.WHITE);
            canvas.drawLine(30, 50, 370, 50, p);
            widthImageView.setImageBitmap(bitmap);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };

}
mohammadReza Abiri
  • 1,759
  • 1
  • 9
  • 20

2 Answers2

1

your context is null so you need initialize that in this way:

   public class SecondActivity extends AppCompatActivity {
private EditText textUsername;
private Button buttonRegister;
private String username;
private AppView appView;
private DatabaseHelper dbHelper;
private  byte[] image;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    textUsername = (EditText) findViewById(R.id.editText);
    username = textUsername.getText().toString();
    buttonRegister=(Button) findViewById(R.id.saveButton);

    buttonRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            appView= new AppView(SecondActivity.this ,null ); // change this line
            image = appView.saveImage();
            dbHelper.addImage(username,image);
        }
    });
}
mohammadReza Abiri
  • 1,759
  • 1
  • 9
  • 20
  • java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference now i'm getting these error because of the line : bitmap.compress(Bitmap.CompressFormat.PNG,0,stream); – pofuduktavsancik May 17 '19 at 13:53
  • Your first problem was fixed ! – mohammadReza Abiri May 17 '19 at 13:56
  • I think now problem is about my bitmap – pofuduktavsancik May 17 '19 at 14:00
  • `public static byte[] getBytes (Bitmap bitmap){ ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100,stream); return stream.toByteArray(); } public static Bitmap getImage(byte[] image){ return BitmapFactory.decodeByteArray(image,0,image.length); } }` – pofuduktavsancik May 17 '19 at 14:10
  • see these link https://stackoverflow.com/questions/34735726/null-pointer-exception-when-trying-to-compress-bitmap https://stackoverflow.com/questions/48033031/im-getting-error-when-im-compress-the-image-using-bitmap-in-android – mohammadReza Abiri May 17 '19 at 14:27
0
buttonRegister.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        appView= new AppView(**appView**.getContext(),null );
        image = appView.saveImage();
        dbHelper.addImage(username,image);
    }

appView<-- this is null at the point of click initialize this first

Vishal
  • 61
  • 1
  • 6
  • java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context com.example.mydrawingapp.View.AppView.getContext()' on a null object reference at com.example.mydrawingapp.SecondActivity$1.onClick(SecondActivity.java:30) it still gives this error – pofuduktavsancik May 17 '19 at 13:57