0

I am developing an app in which there is login screen visible to user in which I have to send three details like mobile,password,and isfirstLogin to server if user is first time login then show some activity and if Flase then show login activity. kindly help how can I archeive this problem.

public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://577.168.0.110:8080/ireward/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_loginBtn;
public ProgressDialog m_PDialog;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public Snackbar m_SnackBar;
public LinearLayout m_MainLayout;
public AppCompatButton m_RegisterBtn;
public CLoginSessionManagement m_oLoginSession;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    m_Main = inflater.inflate(R.layout.login_screen, container, false);
    ((AppCompatActivity) getActivity()).getSupportActionBar().hide();
    m_oLoginSession = new CLoginSessionManagement(getActivity());
    Toast.makeText(getActivity(), "User Login Status: " + m_oLoginSession.isLogin(), Toast.LENGTH_LONG).show();


    init();
    return m_Main;
}

public void init() {
    m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);

    m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
    m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);

    m_loginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
    m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
    m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
        }
    });
    m_loginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new LoginAttempt().execute();
        }
    });
}

private class LoginAttempt extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        m_PDialog = new ProgressDialog(getActivity());
        m_PDialog.setMessage("Please wait while Registering...");
        m_PDialog.setCancelable(false);
        m_PDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        getLoginDetails();// getting login details from editText...........
        InputStream inputStream = null;
        m_oJsonsResponse = new CJsonsResponse();
        isFirstLogin = true;
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(s_szLoginUrl);
            String json = "";
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("agentCode", s_szMobileNumber);
            jsonObject.put("pin", s_szPassword);
            jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content
            //  httpPost.setHeader("Accept", "application/json");   ///not required
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            // 9. receive response as inputStream
            inputStream = entity.getContent();
            System.out.print("InputStream...." + inputStream.toString());
            System.out.print("Response...." + httpResponse.toString());

            StatusLine statusLine = httpResponse.getStatusLine();
            System.out.print("statusLine......" + statusLine.toString());
            ////Log.d("resp_body", resp_body.toString());
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                // 10. convert inputstream to string
                if (inputStream != null) {
                    s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
                    //String resp_body =
                    EntityUtils.toString(httpResponse.getEntity());
                }
            } else
                s_szresult = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        System.out.println("s_szResult....." + s_szresult);
        System.out.println("password......" + s_szPassword);
        // 11. return s_szResult
        return s_szresult;
    }

    @Override
    protected void onPostExecute(String response) {
        super.onPostExecute(response);
        m_PDialog.dismiss();

        try {
            m_oResponseobject = new JSONObject(response);// getting response from server
            new Thread() {// making child thread...
                public void run() {
                    Looper.prepare();
                    try {
                        if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
                            m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
                        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
                            m_SnackBar = Snackbar.make(m_MainLayout, "Please enter valid mobile number", Snackbar.LENGTH_SHORT);
                            m_SnackBar.show();
                        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
                            m_SnackBar = Snackbar.make(m_MainLayout, "Please enter Password", Snackbar.LENGTH_SHORT);
                            m_SnackBar.show();
                        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
                            m_SnackBar = Snackbar.make(m_MainLayout, "Invalid Password", Snackbar.LENGTH_SHORT);
                            m_SnackBar.show();
                        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
                            m_SnackBar = Snackbar.make(m_MainLayout, "You are bloacked", Snackbar.LENGTH_SHORT);
                            m_SnackBar.show();
                        }

                        Looper.loop();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.start();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getLoginDetails() {
        s_szMobileNumber = m_InputMobile.getText().toString();
        s_szPassword = m_InputPassword.getText().toString();
    }
}

}

Nitin
  • 163
  • 2
  • 11
  • 2
    put a flag in sharedPreferences. when you launch app check that flag if false then show login screen and in success login case update sharedpref value of that flag with true. and if already true then go to other screen – Khizar Hayat Mar 22 '16 at 04:03
  • ok ill send you in few mintues – Khizar Hayat Mar 22 '16 at 04:10
  • check this link http://stackoverflow.com/questions/13184261/login-and-logout-sessions-android – Khizar Hayat Mar 22 '16 at 04:15
  • if it not helps you let me know then – Khizar Hayat Mar 22 '16 at 04:15
  • There are a few things that need to be explained for the correct answer. Is login device dependent - meaning do you want to inform the server that this user is logging in for the first time using this device. This is being asked because using shared preferences you can only know about the login status of that device. If you want to know if the user is logging in for the first time, no matter from where then you have to put this information in your database. – Rishabh Lashkari Mar 22 '16 at 05:02
  • yes like same as you said rishabh what is the solution – Nitin Mar 22 '16 at 05:49

3 Answers3

0

In SplashActivity or startActivity you have to check

        String PREFS_NAME = "Start_Page";
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME,
                                    MODE_PRIVATE);
        strFirstTime = prefs.getString("Authentication", "NO Authentication");

         if (strFirstTime.equals("NO Authentication") ) 
            {
              Show Login page
        }
        else
        {
         // Intent for open HomePage
        }

        in Login page, after loging successfully done write below code

        SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
                            editor.putString("Authentication",et_email_add.getText().toString());
                            editor.commit();

call intent for homepage

Ajay Pandya
  • 2,417
  • 4
  • 29
  • 65
sarika kate
  • 489
  • 2
  • 7
0

Once after successful login save the username and password in shared preferences and in splash screen or run a Asynctask to check login service when app is launched.

Sanjeev
  • 292
  • 2
  • 5
  • 24
0

To achieve this you have to maintain preference and check each time when your app starts.

There are lot of tutorial and answer available for How to use Shared preferences example , Android Shared preferences example

Community
  • 1
  • 1
Ajay Pandya
  • 2,417
  • 4
  • 29
  • 65