1

How to merge following code with Async Task. I see lots of tutorials and make changes in code but unable to do completly. This code is completely fine and working proper but some one advise me to make it Async Task so that when login successful message disappear Move_to_next method is called to start new activity. so please someone add async task code in it so that its work proper.

Code-

public class LoActivity extends Activity {

        Intent i;
        Button signin;
        TextView error;
        CheckBox check;
        String name="",pass="";
        byte[] data;
        HttpPost httppost;
        StringBuffer buffer;
        HttpResponse response;
        HttpClient httpclient;
        InputStream inputStream;
        SharedPreferences app_preferences ;
        List<NameValuePair> nameValuePairs;
        EditText editTextId, editTextP;

        @Override
        public void onCreate (Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            signin = (Button) findViewById (R.id.signin);
            editTextId = (EditText) findViewById (R.id.editTextId);
            editTextP = (EditText) findViewById (R.id.editTextP);
            app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
            check = (CheckBox) findViewById(R.id.check);
            String Str_user = app_preferences.getString("username","0" );
            String Str_pass = app_preferences.getString("password", "0");
            String Str_check = app_preferences.getString("checked", "no");
            if(Str_check.equals("yes"))
            {
                editTextId.setText(Str_user);
                editTextP.setText(Str_pass);
                check.setChecked(true);
            }

            signin.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    name = editTextId.getText().toString();
                    pass = editTextP.getText().toString();
                    String Str_check2 = app_preferences.getString("checked", "no");
                    if(Str_check2.equals("yes"))
                    {
                        SharedPreferences.Editor editor = app_preferences.edit();
                        editor.putString("username", name);
                        editor.putString("password", pass);
                        editor.commit();
                    }
                    if(name.equals("") || pass.equals(""))
                    {
                         Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {

                    try {
                        httpclient = new DefaultHttpClient();
                        httppost = new HttpPost("http://abc.com/register.php");
                        // Add your data
                        nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                        nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        // Execute HTTP Post Request
                        response = httpclient.execute(httppost);
                        inputStream = response.getEntity().getContent();

                        data = new byte[256];

                        buffer = new StringBuffer();
                        int len = 0;
                        while (-1 != (len = inputStream.read(data)) )
                        {
                            buffer.append(new String(data, 0, len));
                        }

                        inputStream.close();
                    }

                    catch (Exception e)
                    {
                        Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
                    }
                    if(buffer.charAt(0)=='Y')
                    {
                        Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
                    }
                    }
                }
            });

        check.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                // Perform action on clicks, depending on whether it's now checked
                SharedPreferences.Editor editor = app_preferences.edit();
                if (((CheckBox) v).isChecked())
                {
                     editor.putString("checked", "yes");
                     editor.commit();
                }
                else
                {
                     editor.putString("checked", "no");
                     editor.commit();
                }
        }
        });
        }
         public void Move_to_next()
         {
             startActivity(new Intent(LoActivity.this, QnActivity.class));

         }
    }
John R
  • 2,078
  • 8
  • 35
  • 58

4 Answers4

3

All you need to add asyctask call in your signin button click the code is following

       Context mContext=this;
  String[] result = new String[2];

    signin.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
                    {
                AsyncGetAccessToken aSyncGetToken=new AsyncGetAccessToken();
                aSyncGetToken.execute()}});

Make a private class AsyncTask:

                      private class AsyncGetAccessToken extends AsyncTask<Void, Void, String>
                            {



                                @Override
                                protected String doInBackground(Void... Data) {
                                 name = editTextId.getText().toString();
                                pass = editTextP.getText().toString();
                                String Str_check2 = app_preferences.getString("checked", "no");
                                if(Str_check2.equals("yes"))
                                {
                                    SharedPreferences.Editor editor = app_preferences.edit();
                                    editor.putString("username", name);
                                    editor.putString("password", pass);
                                    editor.commit();
                                }
                                if(name.equals("") || pass.equals(""))
                                {
                                     Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
                                }
                                else
                                {

                                try {
                                    httpclient = new DefaultHttpClient();
                                    httppost = new HttpPost("http://abc.com/register.php");
                                    // Add your data
                                    nameValuePairs = new ArrayList<NameValuePair>(2);
                                    nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                                    nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                    // Execute HTTP Post Request
                                    response = httpclient.execute(httppost);
                                    inputStream = response.getEntity().getContent();

                                    data = new byte[256];

                                    buffer = new StringBuffer();
                                    int len = 0;
                                    while (-1 != (len = inputStream.read(data)) )
                                    {
                                        buffer.append(new String(data, 0, len));
                                    }
                               result[0] = response.getStatusLine().getStatusCode()+"";
            result[1] = buffer .toString();
                                    inputStream.close();
                                }

                                catch (Exception e)
                                {
                                    Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
                                }
                                if(buffer.charAt(0)=='Y')
                                {
                                    Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                                }
                                else
                                {
                                    Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
                                }

                            }


    return result;
}
                                @Override
                                protected void onPreExecute() {       
                                    super.onPreExecute();
                                    showLoading();         
                                }
                         @Override
                         protected void onPostExecute(String result)
                         {
                             super.onPostExecute(result);
                             hideLoading();
                         }


                        }

for stop loading:

    private void hideLoading()

        {

              if (pDialogTh.isShowing()) {
           pDialogTh.cancel();
        }

        }

for start loading :

        private ProgressDialog pDialogTh = null;

        private void showLoading()

        {

                        // if(pDialog==null)
                        pDialogTh = ProgressDialog.show(mContext, "", "Loading...",
                                true, true);
                        pDialogTh.setCancelable(false);
                        if (!pDialogTh.isShowing()) {
                            pDialogTh.show();
                        }


         }
Usman Kurd
  • 7,212
  • 7
  • 57
  • 86
  • protected String doInBackground(String... Data) method required return statement. where i have to write return statement in that method and what i have to return? – John R Sep 26 '13 at 11:33
  • if you don`t want any thing to return just make it void – Usman Kurd Sep 26 '13 at 11:50
  • You can return the response String of Request – Usman Kurd Sep 26 '13 at 12:02
  • Updated Answer have a look now\ – Usman Kurd Sep 26 '13 at 12:06
  • code suggested by you giving 3 errors first on private class AsyncGetAccessToken extends AsyncTask , second on super.onPreExecute(); and third one on super.onPostExecute(result); and its suggested to add @supressedlint at all 3 places. what now i have to do? – John R Sep 26 '13 at 12:42
  • and also response i s of HTTP type variable. so on return statement its also show error. Its saying either to convert method return type http or to convert response variable to string. – John R Sep 26 '13 at 12:44
  • check now solve also your HTTP Issue if any issue do let me know – Usman Kurd Sep 26 '13 at 12:55
  • sb is what type of variable? – John R Sep 26 '13 at 13:03
  • its buffer type if you are getting error then share your error what you are getting – Usman Kurd Sep 26 '13 at 13:10
  • code suggested by you giving 3 errors first on private class AsyncGetAccessToken extends AsyncTask , second on super.onPreExecute(); and third one on super.onPostExecute(result); and its suggested to add @supressedlint at all 3 places. Also where you declared sb? error on mcontext. please help me solve these errors. – John R Sep 26 '13 at 13:21
  • I`ve updated code and sb is buffer replaced sb with buffer now it should work fine as its working fine with me. – Usman Kurd Sep 26 '13 at 13:25
  • only two errors on mcontext and return result. its saying to convert String[] doInBacground. and in mcontext saying to create local variable mcontext. What i do in these cases? – John R Sep 26 '13 at 13:48
  • for context code edited and for result use the following as return statment return result[1]; – Usman Kurd Sep 26 '13 at 13:52
  • 09-24 07:24:40.968: E/AndroidRuntime(16759): FATAL EXCEPTION: AsyncTask #3 09-24 07:24:40.968: E/AndroidRuntime(16759): java.lang.RuntimeException: An error occured while executing doInBackground() 09-24 07:24:40.968: E/AndroidRuntime(16759): at android.os.AsyncTask$3.done(AsyncTask.java:299) 09-24 07:24:40.968: E/AndroidRuntime(16759): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 09-24 07:24:40.968: E/AndroidRuntime(16759): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) – John R Sep 26 '13 at 13:59
1

Try this:

if(name.equals("") || pass.equals(""))
{
 Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}else{
    RequestClient reqClient = new RequestClient(ClassName.this);
    String AppResponse = null;
    AppResponse = reqClient.execute().get()
}

In App response you will get your response change the data type of it as per your requirement.

Create a class RequestClient.java

public class RequestClient extends AsyncTask<String, Void, String>{
Context context;

public RequestClient(Context c) {
    context = c;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client = null;
try {
     client = new DefaultHttpClient();  
     HttpGet get = new HttpGet(aurl[0]);
     HttpResponse responseGet = client.execute(get);  
     HttpEntity resEntityGet = responseGet.getEntity();  
     if (resEntityGet != null) {  
         responseString = EntityUtils.toString(resEntityGet);
         Log.i("GET RESPONSE", responseString);
     }
} catch (Exception e) {
    Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
    Log.d("ANDRO_ASYNC_RESPONSE", responseString);
client.getConnectionManager().shutdown();
 return responseString;

}


@Override
protected void onPostExecute(String response) {
     super.onPostExecute(response); 
    }
}
dd619
  • 5,910
  • 8
  • 35
  • 60
Developer
  • 6,292
  • 19
  • 55
  • 115
1

Im new on android, so in my (little reserchs) ive learn that, if we want make some task that includs network access, or other heavy operation, we need do this on some async task. So in my opinion u can do something like this:

signin.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    ...
                    if(name.equals("") || pass.equals(""))
                    {
                         Toast.makeText(Lo.this, "Blank Field..Please Enter",              Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                       ...
                       YourAsyncClass test = new YourAsyncClass(this);
                       //you can give various string parameters, in this case, u can send the url, make it an constant
                       test.execute(YOUR_URL_LIKE_CONSTANT);
                     }
                     if(buffer.charAt(0)=='Y')
                {
                    Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                }
                ...

And your YourAsynClass may be like this:

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

    ...

    public YourAsynClass () {
        ...
    }

    //this method is executed before the real task
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ...
        //here you can call some load dialog box
    }

     @Override
protected String doInBackground(String... params){
try {
                        httpclient = new DefaultHttpClient();
                        httppost = new HttpPost("http://abc.com/register.php");
                        // Add your data
                        nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                        nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        // Execute HTTP Post Request
                        response = httpclient.execute(httppost);
                        inputStream = response.getEntity().getContent();

                        data = new byte[256];

                        buffer = new StringBuffer();
                        int len = 0;
                        while (-1 != (len = inputStream.read(data)) )
                        {
                            buffer.append(new String(data, 0, len));
                        }

                        inputStream.close();
                    }

                    catch (Exception e)
                    {
                        Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
                    }
                   return buffer.toString();
                }
     @Override
             protected void onPostExecute(String result)
             {
                 super.onPostExecute(result);
                 //u can hide the load dialog here
             }
Cold
  • 787
  • 8
  • 23
1

Try this way

I have edit in your code just copy paste and try

public class LoActivity extends Activity {

    Intent i;
    Button signin;
    TextView error;
    CheckBox check;
    String name = "", pass = "";
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences;
    List<NameValuePair> nameValuePairs;
    EditText editTextId, editTextP;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        signin = (Button) findViewById(R.id.signin);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextP = (EditText) findViewById(R.id.editTextP);
        app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        check = (CheckBox) findViewById(R.id.check);
        String Str_user = app_preferences.getString("username", "0");
        String Str_pass = app_preferences.getString("password", "0");
        String Str_check = app_preferences.getString("checked", "no");
        if (Str_check.equals("yes")) {
            editTextId.setText(Str_user);
            editTextP.setText(Str_pass);
            check.setChecked(true);
        }

        signin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                name = editTextId.getText().toString();
                pass = editTextP.getText().toString();
                String Str_check2 = app_preferences.getString("checked", "no");
                if (Str_check2.equals("yes")) {
                    SharedPreferences.Editor editor = app_preferences.edit();
                    editor.putString("username", name);
                    editor.putString("password", pass);
                    editor.commit();
                }
                if (name.equals("") || pass.equals("")) {
                    Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
                } else {
                    new LoginTask().execute();
                }
            }
        });

        check.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks, depending on whether it's now
                // checked
                SharedPreferences.Editor editor = app_preferences.edit();
                if (((CheckBox) v).isChecked()) {
                    editor.putString("checked", "yes");
                    editor.commit();
                } else {
                    editor.putString("checked", "no");
                    editor.commit();
                }
            }
        });
    }

    public void Move_to_next() {
        startActivity(new Intent(LoActivity.this, QnActivity.class));

    }

    private class LoginTask extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            // Show progress dialog here
        }
        @Override
        protected String doInBackground(Void... arg0) {
            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://abc.com/register.php");
                // Add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                inputStream = response.getEntity().getContent();

                data = new byte[256];

                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = inputStream.read(data))) {
                    buffer.append(new String(data, 0, len));
                }

                inputStream.close();
                return buffer.toString();
            } catch (Exception e) {
                e.printStackTrace();

            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Hide progress dialog here

            if (buffer.charAt(0) == 'Y') {
                Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                Move_to_next();
            } else {
                Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
Biraj Zalavadia
  • 28,348
  • 10
  • 61
  • 77
  • where your call to LoginTask class? – John R Sep 26 '13 at 11:43
  • code suggested by you giving 3 errors first on private class LoginTask extends AsyncTask , second on super.onPreExecute(); and third one on super.onPostExecute(result); and its suggested to add @supressedlint at all 3 places. what now i have to do? – John R Sep 26 '13 at 11:52
  • I added your code and add @supressedlint to solve error but now authentication is not working now. – John R Sep 26 '13 at 12:10
  • saying to add supressedlint. – John R Sep 26 '13 at 12:33
  • in your onclick method if (name.equals("") || pass.equals("")) { Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show(); } else { new LoginTask().execute(); } – Biraj Zalavadia Sep 26 '13 at 12:50
  • code suggested by you giving 3 errors first on private class LoginTask extends AsyncTask , second on super.onPreExecute(); and third one on super.onPostExecute(result); and its suggested to add @supresselint at all 3 places. when i add that and run my app its not working how i solve this problem? – John R Sep 26 '13 at 12:52
  • sorry its not stopped working but shows unsuccessful to login even correct username and password. – John R Sep 26 '13 at 12:55
  • code suggested by you working at some extent you can check this link if you like to help me complete. http://stackoverflow.com/questions/19031225/unable-to-launch-activity?noredirect=1#comment28122058_19031225 – John R Sep 26 '13 at 15:06
  • thank you for your help. its working. I like and upvote your answer bcoz its working. – John R Sep 27 '13 at 12:31
  • Bro. i need little more help? – John R Sep 27 '13 at 12:36
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/38177/discussion-between-biraj-zalavadia-and-john-r) – Biraj Zalavadia Sep 27 '13 at 12:37
  • sure what is the issue – Biraj Zalavadia Sep 27 '13 at 12:38