1

I have following class in my app i am sending username and password to remote server and on server side its matching values and sending respond. Everything working completely fine. I want to ask how can i start new activity after login successful message. I want new activity start when message disappear. QnActivity is the Activity i want to start and LoActivity is my current activity. I have tried so much but not successful. I've also added

startActivity(new Intent(LoActivity.this, QnActivity.class));

in public void Move_to_next() method but its not working.

Java 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
  • 1
    What does "not successful" mean? Does the application crash, does nothing happen, or does something else happen? "It doesn't work" is not a good description of the problem. – Bryan Herbst Sep 25 '13 at 15:37
  • I dont know how to use Asyncthask. The links prvided by codeMagic are good but asynctask is new for me. so i dont know how to merge my code with asynctask code. Plz anyone help me. – John R Sep 26 '13 at 08:06
  • @Tanis.7x after successful login as others said Move_to_next() never called. and logcat show too much work on main thread as others already know. But i dont know how to use asynctask in my code. – John R Sep 26 '13 at 08:14

3 Answers3

2

You are running a network realted operation on the ui thread. Use a Thread or Asynctask

  response = httpclient.execute(httppost);

You will get NetworkOnMainThreadException post honeycomb if you run network related operaion on the ui thread

And make sure you call Move_to_next() in your code.

To invoke AsyncTask on the ui thread

   new TheTask().execute();

AsyncTask

   class TheTask extends AsyncTask<Void,Void,Void>
   {
       @Override
       protected void onPreExecute()
       {
               super.onPreExecute();
               // dispaly progress dialog 
       } 
       @Override
       protected void doInbackground(Void... params)
       {
           // do network related operation here
           // do not update ui here
          return null; // return result here
       } 
       @Override
       protected void onPostExecute(Void result) // result of background computation received
       {
           super.onPostExecute(result);
            // dimiss dialog
           // update ui here     
       } 
   }  
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Good catch! I didn't notice that the method wasn't called. But I did stop reading when I saw the ugly `NetworkOnMain` coming ;) – codeMagic Sep 25 '13 at 15:45
  • @Raghunandan please tell me how to implement this in my code. – John R Sep 26 '13 at 09:49
  • @JohnR use asynctask i will post a sample. check it understand and then try – Raghunandan Sep 26 '13 at 09:51
  • @JohnR check the post now and this link http://developer.android.com/reference/android/os/AsyncTask.html – Raghunandan Sep 26 '13 at 09:57
  • @Raghunandan sir as suggested by you i make changes in my code. But few errors please check this link. http://stackoverflow.com/questions/19031225/unable-to-launch-activity – John R Sep 26 '13 at 15:35
  • @Raghunandan Is it possible to call one xml from two activites? like i want to create signup activity. – John R Sep 27 '13 at 12:04
  • @JohnR i am not sure i understand your requirement. But for a single activity you need to have setContentView only once for the activity. It s a bad design if you have more than once. So each activity will have a ui set with setcontentView – Raghunandan Sep 27 '13 at 12:06
  • @Raghunandan the link i send you last day i m glad if you help me. Like i have signin.setOnClickListener there. how i add new signup.setOnClickListener there? and what changes i have to made there? – John R Sep 27 '13 at 12:09
  • @Raghunandan if i dont add async task there then i know how to do that but now difficult for me. – John R Sep 27 '13 at 12:10
  • @Raghunandan later i post question and let you inform. I dont know your age but bro. thank you for all your help so nice of you. – John R Sep 27 '13 at 12:55
  • @JohnR glad to help anytime – Raghunandan Sep 27 '13 at 13:04
2

Its hard to say why it isn't working since you haven't told us how it isn't working. However, you should move your network calls to another Thread. Put this in an AsyncTask. Do your network stuff in doInBackground().

Then after the network stuff finishes you can send the result to onPostExecute() and call startActivity() from there if the login is successful.

AsyncTask Docs

AsyncTask example

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • nice you posted the example and the links i was lazy this time din't post the code – Raghunandan Sep 25 '13 at 15:43
  • @codeMagic i have little problem hope you help me. i have one issue when i type password its show that digit or alphabet then convert it into dot. i want i press any digit its not show that digit or alphabet show only dot. – John R Oct 07 '13 at 14:11
  • @JohnR you probably want to look at setting a [Password Input Type](http://developer.android.com/training/keyboard-input/style.html) – codeMagic Oct 07 '13 at 14:19
  • @codeMagic and please check this link. http://stackoverflow.com/questions/19227846/how-to-set-the-value-of-sharedpreferences-in-other-activity – John R Oct 07 '13 at 14:45
2

My guess would be, you never call the method Move_to_next()

I would suggest calling it once you get a good response from the server, but also, you should take @Ragunandan's advice and run the request on a separate thread.

Gil Moshayof
  • 16,633
  • 4
  • 47
  • 58