Java – How do I start a new activity from a button in the alert dialog?

How do I start a new activity from a button in the alert dialog?… here is a solution to the problem.

How do I start a new activity from a button in the alert dialog?

In this app, I created a scanner and the results will be displayed in alertDialog with two buttons; OK and NEXT. NEXT button I want to go to the new activity. The problem is that when the NEXT button is clicked, it crashes.

Please help me…
I’m new here.

  @Override
    public void handleResult(final Result result) {

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Scan Result");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                scannerView.resumeCameraPreview(qrscanner.this);
            }
        });
        builder.setNeutralButton("NEXT", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(qrscanner.this,attend_form.class);
                startActivity(intent);
            }
        });

AlertDialog alert = builder.create();
        alert.show();

This participation form

public class attend_form extends AppCompatActivity {

Toolbar toolbar;
Button btn_get_sign, mClear, mGetSign, mCancel, btn_rega;
RadioGroup battend;

EditText File,Ic;
String file_number,ic_no;
String attendance = "";
AlertDialog.Builder builder;
String url_reg = "http://192.168.1.7/spm/android/attendance/attend.php";

File file;
Dialog dialog;
LinearLayout mContent;
View view;
signature mSignature;
Bitmap bitmap;

 Creating Separate Directory for saving Generated Images
String DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/DigitSign/";
String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String StoredPath = DIRECTORY + pic_name + ".png";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attend_form);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

 Setting ToolBar as ActionBar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

btn_rega = (Button)findViewById(R.id.btn_rega);

final RadioGroup battend = (RadioGroup)findViewById(R.id.attendance);
    final RadioButton attend = (RadioButton)findViewById(R.id.btn_attend);
    final RadioButton absent = (RadioButton)findViewById(R.id.btn_absent);

 Button to open signature panel
    btn_get_sign = (Button) findViewById(R.id.signature);

File = (EditText)findViewById(R.id.file_number);
    Ic = (EditText)findViewById(R.id.ic_no);

builder = new AlertDialog.Builder(attend_form.this);

btn_rega.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

file_number = File.getText().toString();
            ic_no = Ic.getText().toString();
            if (battend.getCheckedRadioButtonId() == attend.getId())
            {
                attendance = "ATTEND";
            }

else if(battend.getCheckedRadioButtonId() == absent.getId())
            {
                attendance = "ABSENT";
            }

if(file_number.equals("") || ic_no.equals(""))
            {
                builder.setTitle("Something were wrong");
                builder.setMessage("Please fill all field");
                displayAlert("input_error");
            }

else
            {

StringRequest stringRequest = new StringRequest(Request.Method.POST, url_reg, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String code = jsonObject.getString("code");
                            String message = jsonObject.getString("message");
                            builder.setTitle("Server Response");
                            builder.setMessage(message);
                            displayAlert(code);
                        }catch (JSONException e)
                        {
                            e.printStackTrace();
                        }

}
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

}
                }){
                    @SuppressWarnings("deprecation")
                    @Override
                    protected Map<String, String> getPostParams() throws AuthFailureError {
                        Map<String,String> params = new HashMap<String, String>();
                        params.put("file_number",file_number);
                        params.put("ic_no",ic_no);
                        params.put("attendance",attendance);
                        return super.getPostParams();
                    }

@Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> params = new HashMap<String, String>();
                        params.put("file_number",file_number);
                        params.put("ic_no",ic_no);
                        params.put("attendance",attendance);
                        return params;
                    }
                };

MySingleton.getInstance(attend_form.this).addToRequestque(stringRequest);

}

}
    });

 Method to create Directory, if the Directory doesn't exists
    file = new File(DIRECTORY);
    if (!file.exists()) {
        file.mkdir();
    }

 Dialog Function
    dialog = new Dialog(attend_form.this);
     Removing the features of Normal Dialogs
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_signature);
    dialog.setCancelable(true);

btn_get_sign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             Function call for Digital Signature
            dialog_action();

}
    });

}

public void displayAlert(final String code)
{
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int which) {

if(code.equals("input_error"))
            {
                File.setText("");
                Ic.setText("");

}
            else if(code.equals("reg_success"))
            {
                finish();

}
            else if(code.equals("reg_failed"))
            {
                File.setText("");
                Ic.setText("");
            }

}
    });

AlertDialog alertDialog = builder.create();
    alertDialog.show();

}

 Function for Digital Signature
public void dialog_action() {

mContent = (LinearLayout) dialog.findViewById(R.id.linearLayout);
    mSignature = new signature(getApplicationContext(), null);
    mSignature.setBackgroundColor(Color.WHITE);
     Dynamically generating Layout through java code
    mContent.addView(mSignature, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    mClear = (Button) dialog.findViewById(R.id.clear);
    mGetSign = (Button) dialog.findViewById(R.id.getsign);
    mGetSign.setEnabled(false);
    mCancel = (Button) dialog.findViewById(R.id.cancel);
    view = mContent;

mClear.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v("log_tag", "Panel Cleared");
            mSignature.clear();
            mGetSign.setEnabled(false);
        }
    });

mGetSign.setOnClickListener(new View.OnClickListener() {

@SuppressWarnings("deprecation")
        public void onClick(View v) {

Log.v("log_tag", "Panel Saved");
            view.setDrawingCacheEnabled(true);
            mSignature.save(view, StoredPath);
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), "Successfully Saved", Toast.LENGTH_SHORT).show();
             Calling the same class
            recreate();

}
    });

mCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v("log_tag", "Panel Canceled");
            dialog.dismiss();
             Calling the same class
            recreate();
        }
    });
    dialog.show();
}

public class signature extends View {

private static final float STROKE_WIDTH = 5f;
    private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
    private Paint paint = new Paint();
    private Path path = new Path();

private float lastTouchX;
    private float lastTouchY;
    private final RectF dirtyRect = new RectF();

public signature(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(STROKE_WIDTH);
    }

public void save(View v, String StoredPath) {
        Log.v("log_tag", "Width: " + v.getWidth());
        Log.v("log_tag", "Height: " + v.getHeight());
        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
        }
        Canvas canvas = new Canvas(bitmap);
        try {
             Output the file
            FileOutputStream mFileOutStream = new FileOutputStream(StoredPath);
            v.draw(canvas);

 Convert the output file to Image such as .png
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
            mFileOutStream.flush();
            mFileOutStream.close();

} catch (Exception e) {
            Log.v("log_tag", e.toString());
        }

}

public void clear() {
        path.reset();
        invalidate();
    }

@Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
    }

@SuppressWarnings("deprecation")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();
        mGetSign.setEnabled(true);

switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(eventX, eventY);
                lastTouchX = eventX;
                lastTouchY = eventY;
                return true;

case MotionEvent.ACTION_MOVE:

case MotionEvent.ACTION_UP:

resetDirtyRect(eventX, eventY);
                int historySize = event.getHistorySize();
                for (int i = 0; i < historySize; i++) {
                    float historicalX = event.getHistoricalX(i);
                    float historicalY = event.getHistoricalY(i);
                    expandDirtyRect(historicalX, historicalY);
                    path.lineTo(historicalX, historicalY);
                }
                path.lineTo(eventX, eventY);
                break;

default:
                debug("Ignored touch event: " + event.toString());
                return false;
        }

invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

lastTouchX = eventX;
        lastTouchY = eventY;

return true;
    }

private void debug(String string) {

Log.v("log_tag", string);

}

private void expandDirtyRect(float historicalX, float historicalY) {
        if (historicalX < dirtyRect.left) {
            dirtyRect.left = historicalX;
        } else if (historicalX > dirtyRect.right) {
            dirtyRect.right = historicalX;
        }

if (historicalY < dirtyRect.top) {
            dirtyRect.top = historicalY;
        } else if (historicalY > dirtyRect.bottom) {
            dirtyRect.bottom = historicalY;
        }
    }

private void resetDirtyRect(float eventX, float eventY) {
        dirtyRect.left = Math.min(lastTouchX, eventX);
        dirtyRect.right = Math.max(lastTouchX, eventX);
        dirtyRect.top = Math.min(lastTouchY, eventY);
        dirtyRect.bottom = Math.max(lastTouchY, eventY);
    }
}
}

The string request class

public class StringRequestClass extends AsyncTask<String, Void, String> {

Your task happens here

EditText File,Ic;
    String file_number,ic_no;
    String attendance = "";
    AlertDialog.Builder builder;
    String url_reg = "http://192.168.1.7/spm/android/attendance/attend.php";

@Override
    protected String doInBackground(String... params) {
        Do your StringRequest here.

if(file_number.equals("") || ic_no.equals(""))
        {
            builder.setTitle("Something were wrong");
            builder.setMessage("Please fill all field");
            displayAlert("input_error");
        }
        return null;
    }

Things to do when your task is complete.
    @Override
    protected void onPostExecute(String result) {
        Do everything you want to do after the StringRequest is completed.

StringRequest stringRequest = new StringRequest(Request.Method.POST, url_reg, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONArray jsonArray = new JSONArray(response);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    String code = jsonObject.getString("code");
                    String message = jsonObject.getString("message");
                    builder.setTitle("Server Response");
                    builder.setMessage(message);
                    displayAlert(code);
                }catch (JSONException e)
                {
                    e.printStackTrace();
                }

}
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

}
        }){

@Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<String, String>();
                params.put("file_number",file_number);
                params.put("ic_no",ic_no);
                params.put("attendance",attendance);
                return params;
            }
        };

MySingleton.getInstance(attend_form.this).addToRequestque(stringRequest);

}

@Override
    protected void onPreExecute() {

super.onPreExecute();
        if(file_number.equals("") || ic_no.equals(""))
        {
            builder.setTitle("Something were wrong");
            builder.setMessage("Please fill all field");
            displayAlert("input_error");
        }
    } //Things to do before the internet-related task

@Override
    protected void onProgressUpdate(Void... values) {}

public void displayAlert(final String code)
    {
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {

if(code.equals("input_error"))
                {
                    File.setText("");
                    Ic.setText("");

}
                else if(code.equals("reg_success"))
                {
                    finish();

}
                else if(code.equals("reg_failed"))
                {
                    File.setText("");
                    Ic.setText("");
                }

}
        });

AlertDialog alertDialog = builder.create();
        alertDialog.show();

}

}

Solution

Try using getContext().

Intent intent = new Intent(getContext(), attend_form.class);
getContext().startActivity(intent);

Related Problems and Solutions