-1

In my Android Studio Project I've a LauncherActivity. There you can type in a Username and a Password. When you press the Register-Button, the LauncherActivity.class file now sends the Serialnumber and the Macaddress od the phone together with the Username and the Password to a php-webservice which inserts the received data into a MySQL-Database.

Now when somebody is already registered, the App should skip the LauncherActivity and open directly the MainActivity.

Here is a picture, how the App should look like!

I've googled for a solution the whole day but i couldn't find a answer due to that issue. It would be great if somebody could help me.

Post Edit: Here's some code:

LauncherActivity.class

package friendlyreminder.praktikum.roupitz21.at;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.*;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


public class Launcher extends Activity {

    //Progress Dialog
    private ProgressDialog pDialog;

    final JSONParser jsonParser = new JSONParser();
    TextView tvHelp;
    EditText etUsername, etPassword, etPassword2;
    Button bRegister;

    //URL to create a new User
    private static final String url_create_user = "http://192.168.1.233/php_mysql/db_new.php";
    private static final String url_detail_user = "http://192.168.1.233/php_mysql/db_readall.php";

    //JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);

        tvHelp = (TextView) findViewById(R.id.tvHelp);
        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etPassword2 = (EditText) findViewById(R.id.etPassword2);
        bRegister = (Button) findViewById(R.id.bRegister);

        //Help-Link
        tvHelp.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent redirect = new Intent(getApplicationContext(),Help.class);
                startActivity(redirect);
            }
        });

        //Register-Button
        bRegister.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //Get Username
                String username = etUsername.getText().toString();
                //Get Password
                String password = etPassword.getText().toString();
                //Get Password2
                String password2 = etPassword2.getText().toString();

                if (username.equals("") || password.equals("") || password2.equals("")) {
                    String error404 = "You need to type in a Username/ Password/ Default Password";
                    Intent i = new Intent(getApplicationContext(), ErrorActivity.class);
                    i.putExtra("error", error404);
                    startActivity(i);
                    finish();

                } else if (password2.equals("root1234")) {
                    //creating new users in background thread
                    new CreateNewUser().execute();

                } else {
                    String error440 = "The Default Password you typed in wasn't correct. Please try again! If you forgot the Default Password, contact the Administrator.";
                    Intent i = new Intent(getApplicationContext(), ErrorActivity.class);
                    i.putExtra("error", error440);
                    startActivity(i);
                    finish();
                }
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewUser extends AsyncTask<String, String, String> {

        //Before starting background thread Show Progress Dialog
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Launcher.this);
            pDialog.setMessage("Creating new User...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        //Creating new User
        @Override
        protected String doInBackground(String... args) {

/*
//          Get IMEI
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String IMEI = tm.getDeviceId();
*/

            //Get serialnumber
            String serialnumber;
            if (!Objects.equals(Build.SERIAL, Build.UNKNOWN)) serialnumber = Build.SERIAL;
            else
                serialnumber = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
            //Get Macaddress
            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            WifiInfo wInfo = wifiManager.getConnectionInfo();
            String macaddress = wInfo.getMacAddress();
            //Get Username
            String username = etUsername.getText().toString();
            //Get Password
            String password = etPassword.getText().toString();

            //Building Parameters
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("serialnumber", serialnumber));
            params.add(new BasicNameValuePair("macaddress", macaddress));
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            //getting JSON Object
            //Note that create user urls accepts Post method
            JSONObject json = jsonParser.makeHttpRequest(url_create_user,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    //successful created User
                    Intent i = new Intent(getApplicationContext(), Main.class);
                    startActivity(i);
                    //closing this screen
                    finish();
                } else {
                    //String Definition
                    String error444 = "Failed to create User. Maybe the User exists already, please try another one!";
                    //New Intent
                    Intent i = new Intent(getApplicationContext(), ErrorActivity.class);
                    //String to Intent
                    i.putExtra("error", error444);
                    //Start ErrorActivity
                    startActivity(i);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            //dismiss the dialog once done
            pDialog.dismiss();
        }
    }
}

LauncherActivity.xml

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tvWelcome"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/welcome"
            android:textSize="@dimen/abc_text_size_display_1_material"
            android:layout_gravity="center_horizontal"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="30dp" />

        <TextView
            android:id="@+id/tvWarning"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/warning"
            android:layout_below="@+id/tvWelcome"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="30dp" />

        <EditText
            android:id="@+id/etUsername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/username"
            android:layout_marginTop="60dp"
            android:layout_below="@+id/tvWarning"
            android:layout_alignParentStart="true"
            android:inputType="textPersonName" />

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password"
            android:inputType="textPassword"
            android:layout_marginTop="25dp"
            android:layout_below="@+id/etUsername"
            android:layout_alignParentStart="true" />

        <EditText
            android:id="@+id/etPassword2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password2"
            android:inputType="textPassword"
            android:layout_marginTop="25dp"
            android:layout_below="@+id/etPassword"
            android:layout_alignParentStart="true" />

        <Button
            android:id="@+id/bRegister"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/register"
            android:layout_below="@+id/etPassword2"
            android:layout_toEndOf="@+id/tvWelcome"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp" />

        <TextView
            android:id="@+id/tvHelp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/help"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dp" />

    </RelativeLayout>

</ScrollView>

JSONParser.class

package friendlyreminder.praktikum.roupitz21.at;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by Jakob on 21.07.2015.
 */
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}
mpromonet
  • 11,326
  • 43
  • 62
  • 91
roupitz21
  • 3
  • 5
  • http://stackoverflow.com/questions/12359599/how-to-implement-login-in-an-android-application – bGorle Jul 27 '15 at 16:33
  • I want to send the serialnumber of the phone to the php-webservice, then the webservice should search in the database if the serialnumber is already reigistered, if not, you should be redirected to the LauncherActivity. Otherwise you should be redirected to the MainActivity. – roupitz21 Jul 27 '15 at 16:41

2 Answers2

0

A simple solution (not the best) is to always start the MainActivity first and check in the OnCreate if the user is registered like that:

   @Override
    protected void onCreate(Bundle savedInstanceState) {


 if (!user already register) {
            Intent launcher = new Intent(this, LauncherActivity.class);
            startActivity(launcher);
            finish();
     }
{

So when the user is not registered the LauncherActivity starts.

-1

If it was me I would use API keys for authentication. I would rather store an API key in a database that can only be used by the device it was given to than a username and password combo that anyone can use anywhere.

You could have a database or some local storage on the Android device that holds an API key. When the app starts it will check to see if there is an API key there. If not it means they need to login. This is when you show the login screen. They type in their credentials and when they hit login it send their information and their device's information to the server.

If authenticated, the server will return an API key for the device to use. The Android device will then store this API key in its local memory and it will now know it's logged in and will use the API key to access information from the web service.

compman2408
  • 2,369
  • 1
  • 15
  • 15
  • Why was this answer downvoted? If you downvote an answer at least leave a comment to say what's wrong with the answer. – compman2408 Jul 27 '15 at 17:06
  • I'm sorry, I'm new here and i think that one went automaticly. Actually I'm gona try out your solution. The only thing is, that when you deinstall the app the stored API key is gone, so you must loggin once more. If the App compares the serialnumber from the phone with the database you only have to register once and then you are logged in forevver even when you reinstall the app on your smartphone. Does this nake sense? ;D – roupitz21 Jul 27 '15 at 23:11
  • That makes sense, however that is a very bad security practice. If an app is uninstalled it should not keep the user "logged in" which is what the idea you suggested would do and should force the user to login again after re-installing the app.For example, if you have a phone with the app on it and you login, decide you don't want the phone anymore and sell it to me, even if you factory reset the device I can just reinstall the app and, according to the web service, I am you and have access to all your information. – compman2408 Jul 29 '15 at 03:12
  • So the Passwort, which was defined by the User at the Register, should be checked after a reinstallation. Then I can save the Password in a Shared Preferences and the User allways keeps logged in. Is this a possible solution? – roupitz21 Jul 29 '15 at 12:31
  • Yes the password should be checked after reinstallation. However neither the username or password should be saved, even in the shared preferences. The shared preferences are stored in a non-encrypted file. That's why you should only use the username and password to get an API key and the key is what gets stored. Check out this link for more info... – compman2408 Jul 30 '15 at 04:46
  • http://stackoverflow.com/questions/19799416/how-do-popular-apps-authenticate-user-requests-from-their-mobile-app-to-their-se – compman2408 Jul 30 '15 at 04:46