0

Mail is successfully sending without Asynctask. But I need to show a progress dialog while sending the mail, so I implemented Asynctask to send the mail and while sending show the progress dialog. But after mail is successfully sent, the app gets crashed if I use Asynctask. What's the issue?

I implemented the mail sending feature without Asynctask and it was working well. But I need to show the progress dialog while sending the mail, so implemented Asynctask, but app is crashing after mail is successfully sent. or else please suggest any possible way that will help me to show a progress dialog while sending the mail cause that is my main goal. Any possible solution is most welcome.


    WebView webView, webView1, webView2;
    WebViewClient webViewClient;
    EditText uid, concern, rno;
    TextView contact, reel, raise, hostel;
    ImageView AIML, BD, CC, IOT, CSE;
    AsyncTask mytask;
    public Session session;
    public String username;
    public String password;
    public String subject;
    public String messageToSend;

    public String[] blocks = {"D1  ", "D2  ", "D3  ", "D4  ", "D5  "};
    public String[] floors = {"1st floor  ", "2nd floor  ", "3rd floor  ", "4th floor  ", "5th floor  "};
    public String itemblock;
    public String itemfloor;
    AutoCompleteTextView autoCompleteTextViewblock, autoCompleteTextViewfloor;
    ArrayAdapter<String> adapterItems;

    public NotesFragment(){
    }



    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {



        View v= inflater.inflate(R.layout.fragment_notes, container, false);

        AIML = v.findViewById(R.id.AIML);
        BD = v.findViewById(R.id.BD);
        CC = v.findViewById(R.id.CC);
        IOT = v.findViewById(R.id.IOT);
        CSE = v.findViewById(R.id.CSE);
        contact = v.findViewById(R.id.contact);
        reel = v.findViewById(R.id.reel);
        uid = v.findViewById(R.id.uid);
        rno = v.findViewById(R.id.roomno);
        concern =v.findViewById(R.id.concern);
        raise = v.findViewById(R.id.raise);
        hostel = v.findViewById(R.id.hostel);
        autoCompleteTextViewblock = v.findViewById(R.id.sblock);
        autoCompleteTextViewfloor = v.findViewById(R.id.sfloor);
        ProgressDialog progressDialog = new ProgressDialog(getActivity());



        //selecting block
        adapterItems = new ArrayAdapter<String>(getActivity(), R.layout.list_item,blocks);
        autoCompleteTextViewblock.setAdapter(adapterItems);
        autoCompleteTextViewblock.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                itemblock = adapterView.getItemAtPosition(i).toString();
//                Toast.makeText(getActivity(), "Block: "+itemblock, Toast.LENGTH_SHORT).show();
            }

        });
        //

        // selecting floors
        adapterItems = new ArrayAdapter<String>(getActivity(), R.layout.list_item,floors);
        autoCompleteTextViewfloor.setAdapter(adapterItems);
        autoCompleteTextViewfloor.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                itemfloor = adapterView.getItemAtPosition(i).toString();
//                Toast.makeText(getActivity(), "Floor: "+itemfloor, Toast.LENGTH_SHORT).show();
            }

        });
        //


        //open cuims
        contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goLink("https://uims.cuchd.in/uims/");
            }
        });

        //hosetel
        hostel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), hostel.class));
                getActivity().finish();
            }
        });


        //issue raiser
        raise.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {



                username = "my email";
                password = "my password";
                String messageToSendone = itemblock;
                String messageToSendtwo = itemfloor;
                String messageToSendthree = rno.getText().toString();
                String messageToSendfour = concern.getText().toString();

                StringBuilder all = new StringBuilder();
                        all.append(messageToSendone);
                        all.append(messageToSendtwo);
                        all.append(messageToSendthree+" is facing issue of:  ");
                        all.append(messageToSendfour);
                        messageToSend = all.toString();


                subject = uid.getText().toString();

                if (TextUtils.isEmpty(subject)){
                    uid.setError("Please enter your registered CU mail ID!");
                    return;
                }

                if (TextUtils.isEmpty(messageToSendone)){
                    autoCompleteTextViewblock.setError("Please select the block no.");
                    return;
                }
                if (TextUtils.isEmpty(messageToSendtwo)){
                    autoCompleteTextViewfloor.setError("Please select the floor!");
                    return;
                }

                if (TextUtils.isEmpty(messageToSendthree)){
                    rno.setError("Please enter your room no.!");
                    return;
                }
                if (messageToSendthree.length() < 3) {
                    rno.setError("Please enter valid room no.!");
                    return;
                }
                if (messageToSendthree.length() > 4) {
                    rno.setError("Please enter valid room no.!");
                    return;
                }




                if (TextUtils.isEmpty(messageToSendfour)){
                    concern.setError("Please enter your issue!");
                    return;
                }





//                Properties properties = new Properties();
//                properties.put("mail.smtp.auth", "true");
//                properties.put("mail.smtp.starttls.enable", "true");
//                properties.put("mail.smtp.host", "smtp.gmail.com");
//                properties.put("mail.smtp.port", "587");
//                properties.put("mail.smtp.socketFactory.port", "587");
//                properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//                session = Session.getInstance(properties,
//                        new javax.mail.Authenticator() {
//                            @Override
//                            protected PasswordAuthentication getPasswordAuthentication() {
//                                return new PasswordAuthentication(username, password);
//                            }
//                        });

                mytask = new Mytask().execute();





//                void startAsynTask(View v){
//                    Mytask task = new Mytask();
//                    task.execute();
//                }






//                progressDialog.setTitle("Processing");
//                progressDialog.setMessage("Calm down, your issue is being raised...");
////                progressDialog.show();
//
//                try {
//
//                    Message message = new MimeMessage(session);
//                    message.setFrom(new InternetAddress(username));
//                    message.setRecipients(Message.RecipientType.TO,
//                            InternetAddress.parse("20BCS6515@cuchd.in"));
//                    message.setSubject(subject);
//                    message.setText(messageToSend);
//                    Transport.send(message);
//
//
//                    Toast.makeText(getActivity(), "Concern Raised Successfully", Toast.LENGTH_LONG).show();
//
//                }
//                catch (MessagingException e) {
//                    throw new RuntimeException(e);
//                }
////                progressDialog.dismiss();
            }
        });

//        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//        StrictMode.setThreadPolicy(policy);






        //stay nerd card
        webView = v.findViewById(R.id.wb);
        webView.loadUrl("https://sites.google.com/d/1r16RJHz0_2FwcYyP5V0pnrr_3pombkrA/p/1T5T_7ckEO9cSJK2TnV41PNBJXQlHzp3x/edit");
        webView.setBackgroundColor(0);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return false;
            }
        });



        //INTERNET ERROR MSG
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                view.loadUrl("file:///android_asset/nerd.html");

            }
        });




        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.getSettings().setAllowFileAccess(true);
//        webView.setVerticalScrollBarEnabled(false);
//        webView.getSettings().setUseWideViewPort(true);




        //shottbyparth
        webView2 = v.findViewById(R.id.wb2);
        webView2.loadUrl("https://sites.google.com/view/shottbyparth");
        webView2.setBackgroundColor(0);

        //keep in app
        webView2.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return true;
            }
        });



        //INTERNET ERROR MSG
        webView2.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                view.loadUrl("file:///android_asset/partherror.html");

            }
        });




        WebSettings webSettings2 = webView2.getSettings();
        webSettings2.setJavaScriptEnabled(true);
        webView2.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView2.getSettings().setAllowFileAccess(true);
//        webView2.setVerticalScrollBarEnabled(false);
//        webView2.getSettings().setUseWideViewPort(true);






        //magic happens compiler
        webView1 = v.findViewById(R.id.wb1);


        webView1.loadUrl("https://www.tutorialspoint.com/online_cpp_compiler.php");
        webView1.setBackgroundColor(0);

        //keep in app
        webView1.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return false;
            }

        });


        //back button
        webView1.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if(keyEvent.getAction() == keyEvent.ACTION_DOWN){
                    if(keyCode == KeyEvent.KEYCODE_BACK){
                        if(webView1 != null){
                            if(webView1.canGoBack()){
                                webView1.goBack();
                            }else {
                                getActivity().onBackPressed();
                            }

                        }
                    }
                }
                return true;
            }
        });




        webView1.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                view.loadUrl("file:///android_asset/compiler.html");

            }
        });

        //hiding web element with error message

        webView1.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                view.loadUrl("javascript:(function() { " +
                        "document.getElementById('north').style.display='none';})()");
            }
        });






        WebSettings webSettings1 = webView1.getSettings();
        webSettings1.setJavaScriptEnabled(true);





        webView1.setVerticalScrollBarEnabled(true);
        webView1.setHorizontalScrollBarEnabled(true);
        webView1.setScrollbarFadingEnabled(false);
        webView1.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
//        webView1.requestFocus();








        //reel
        reel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goLink("https://sites.google.com/view/shottbyparth");

            }
        });







        //notes
        AIML.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goLink("https://drive.google.com/drive/folders/1bolCGvvV9dKUFH8Uooe3DQGsP4gL1Vwu?usp=share_link");

            }
        });

        BD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "Content coming soon...", Toast.LENGTH_SHORT).show();
            }
        });

        CC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "Content coming soon...", Toast.LENGTH_SHORT).show();
            }
        });

        IOT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "Content coming soon...", Toast.LENGTH_SHORT).show();
            }
        });

        CSE.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "Content coming soon...", Toast.LENGTH_SHORT).show();
            }
        });


        contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goLink("https://uims.cuchd.in/uims/");
            }
        });

        return v;
    }




    
    //asynctask class
    public class Mytask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog dialogue;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            dialogue = new ProgressDialog(getActivity());
            dialogue.setTitle("Processing");
            dialogue.setMessage("Calm down, your issue is being raised...");
            dialogue.setIndeterminate(true);
            dialogue.setCancelable(false);
            dialogue.show();

        }
        @Override
        protected Void doInBackground(Void... params) {


            Properties properties = new Properties();
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.starttls.enable", "true");
            properties.put("mail.smtp.host", "smtp.gmail.com");
            properties.put("mail.smtp.port", "587");
            properties.put("mail.smtp.socketFactory.port", "587");
            properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            session = Session.getInstance(properties,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });



            try {
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(username));
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse("20BCS6515@cuchd.in"));
                message.setSubject(subject);
                message.setText(messageToSend);
                Transport.send(message);


                Toast.makeText(getActivity(), "Concern Raised Successfully", Toast.LENGTH_LONG).show();

            }
            catch (MessagingException e) {
                throw new RuntimeException(e);
            }
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {

            if(dialogue.isShowing()){
                dialogue.dismiss();}


//            Toast.makeText(getActivity(), "Concern Raised Successfully", Toast.LENGTH_LONG).show();

//                        startActivity(new Intent(getActivity(), NotesFragment.class));



        }
    }






    private void goLink(String s) {
        Uri uri = Uri.parse(s);
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }



}```

I implemented the mail sending feature without Asynctask and it was working well. But I need to show the progress dialog while sending the mail, so implemented Asynctask, but app is crashing after mail is successfully sent. or else please suggest any possible way that will help me to show a progress dialog while sending the mail cause that is my main goal. Any possible solution is most welcome.
  • 1
    Use Logcat to examine the stack trace associated with your crash: https://commonsware.com/Jetpack/pages/chap-debug-001.html. Note that `AsyncTask` has been deprecated for a few years. – CommonsWare Feb 10 '23 at 22:04
  • You are making a Toast from the background thread https://stackoverflow.com/questions/3134683/how-do-you-display-a-toast-from-a-background-thread-on-android – Robert Feb 10 '23 at 22:18
  • when I turn off the internet and trying to send the mail, the app is crashing. Hoe to handle it? I guess I need to do somthing inside else{ //Handle failure...} part. Please help me! – thebitanpaul Feb 11 '23 at 13:03
  • sir please help me! how to handle the crash that is happening when internet connection lost and user tries to send the mail. – thebitanpaul Feb 14 '23 at 14:53

1 Answers1

0

Toast needs to happen on the main thread. Move it from doInBackground to onPostExecute.

Toast.makeText(getActivity(), "Concern Raised Successfully", Toast.LENGTH_LONG).show();

You'll need to change the result type to Boolean or Exception to handle both success and failure.

private class MyTask extends AsyncTask<Void, Void, Exception> {

    protected Exception doInBackground(Void... ignore) {
        try {
            // ...
            return null;
        } catch (Exception e) {
            return e;
        }
    }

    protected void onPostExecute(Exception e) {
        if (e == null) {
            // Handle success...
        } else {
            // Handle failure...
        }
    }
}
Eugen Pechanec
  • 37,669
  • 7
  • 103
  • 124
  • you really saved me, this worked pretty well. But when I turn off the internet and trying to send the mail, the app is crashing. Hoe to handle it? I guess I need to do somthing inside else{ //Handle failure...} part. Please help me! – thebitanpaul Feb 11 '23 at 08:56
  • please help me sir, the app is still crashing if I trun of the internet and try to send the mail. I need your help! @EugenPechanec – thebitanpaul Feb 11 '23 at 16:41
  • sir please help me! how to handle the crash that is happening when internet connection lost and user tries to send the mail. – thebitanpaul Feb 14 '23 at 14:52