Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8779429
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T19:47:04+00:00 2026-06-13T19:47:04+00:00

I was following a youtube guide for a Log-In in android. I have reached

  • 0

I was following a youtube guide for a Log-In in android. I have reached thus far and I believe that the youtube guide relies on earlier SDKs to get it to work. For ICS and newer versions, I have read that I need to use Async (I was getting the NetworkOnMainThreadException). I have been working 2 days trying to figure out how to implement this.

This is stuck at the Loading terminal until the app stops working. Is it because I have too much inside the RunInBackground()?

How would I go about getting my methods to work within a proper amount of time.

I appreciate anyones help on this. BTW, I have read a lot of documents that say to implement Async Task, but my question is more towards how would I do this?

**also the back-end: app sends info the index.php on a wamp server and then the php talks to the database.

package com.sokies.my_team;

public class MainActivity extends Activity implements OnClickListener {

    EditText etUser, etPass;
    Button bLogin;

    //Create string variables that will have the input assigned to them
    String username, password;

    //Create a HTTPClient as the form container
    HttpClient httpclient;

    //Use HTTP POST method
    HttpPost httppost;

    //Create an array list for the input data to be sent
    ArrayList<NameValuePair> nameValuePairs;

    //Create a HTTP Response and HTTP Entity
    HttpResponse response;
    HttpEntity entity;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initialise();

    }



    private void initialise() {
        etUser = (EditText) findViewById(R.id.etUser);
        etPass = (EditText) findViewById(R.id.etPass);
        bLogin = (Button) findViewById(R.id.bSubmit);
        //Now to set an onClickListener
        bLogin.setOnClickListener(this);
    }

    public void onClick(View v)  {
        // This is where we will be working now

        new MyAsyncTask().execute();

    }//END onClick()

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }//END convertStreamToString()



    private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
        ProgressDialog mProgressDialog;
        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
        }

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

            //Create new default HTTPClient
            httpclient = new DefaultHttpClient();

            //Create new HTTP POST with URL to php file as parameter
            httppost = new HttpPost("http://10.0.2.2/myteamapp/index.php"); 

            //Assign input text to strings
            username = etUser.getText().toString();
            password = etPass.getText().toString();



            //Next block of code needs to be surrounded by try/catch block for it to work
            try {
                //Create new Array List
                nameValuePairs = new ArrayList<NameValuePair>(2);

                //place them in an array list
                nameValuePairs.add(new BasicNameValuePair("user", "username"));
                nameValuePairs.add(new BasicNameValuePair("pass", "password"));

                //Add array list to http post
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


                //assign executed form container to response
                response = httpclient.execute(httppost); //response from the PHP file

                //check status code, need to check status code 200
                if(response.getStatusLine().getStatusCode() == 200){

                    //assign response entity to http entity
                    entity = response.getEntity();

                    //check if entity is not null
                    if(entity != null){


                        //Create new input stream with received data assigned
                        InputStream instream = entity.getContent();

                        //Create new JSON Object. assign converted data as parameter.
                        JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                        //assign json responses to local strings
                        String retUser = jsonResponse.getString("user");//mySQL table field
                        String retPass = jsonResponse.getString("pass");

                        //Validate login
                        if(username.equals(retUser)&& password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password 

                            //Display a Toast saying login was a success
                            Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();


                        } else {
                            //Display a Toast saying it failed.

                            Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                        }

                    }


                }


            } catch(Exception e){

               // e.printStackTrace();
                //Display toast when there is a connection error
                //Change message to something more friendly
               Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
               Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();

               return null;
            }



            return null;
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T19:47:05+00:00Added an answer on June 13, 2026 at 7:47 pm

    You are trying to perform an operation with UI (in your case it’s showing Toast) from background thread, which is forbidden in android. Try to return a value (f.e., 1 for success and 0 for fail) in doInBackground method and process it in onPostExecute, which is called on UI thread.

    In other words, always perform operations with user interface on main thread: in onPreExecute and onPostExecute methods before and after running background task, respectfully.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Im very new to android/java and have been following a few youtube tutorials and
I'm trying to use Youtube apis in my web application by following this guide
I have done an email approval script following James Ferreira's youtube tutorial here .
I am new to PHP and am following a tutorial on YouTube. I have
i have been following this course in youtube and it was talking about how
I have the following mark-up to load a YouTube video player in a jQuery
I'm looking for a way get the following from a users youtube name or
I am using the following library to stream YouTube videos to an Android application.
I have the following code. It successfully stream the video from YouTube. But when
I have the following HTML scheme: <section id=vids> <ul> <li> <a data-reference=12345 href=http://www.youtube.com/watch?v=12345 rel=external

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.