在MySQL数据库中搜索字符串并将其与Android中的字符串进行比较

时间:2015-07-27 16:27:25

标签: java php android mysql android-studio

在我的Android Studio项目中,我有一个LauncherActivity。在那里,您可以输入用户名和密码。当你按下Register-Button时,LauncherActivity.class文件现在将手机的Serialnumber和Macaddress以及用户名和密码发送到php-webservice,后者将接收的数据插入到MySQL-Database中。

现在当有人注册时,应用程序应跳过LauncherActivity并直接打开MainActivity。

Here是一张图片,应用程序应该是什么样子!

我一整天都在搜索解决方案,但由于这个问题,我找不到答案。如果有人可以帮助我会很棒。

发布编辑: 这是一些代码:

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;

    }
}

2 个答案:

答案 0 :(得分:0)

一个简单的解决方案(不是最好的)是始终首先启动MainActivity并检查OnCreate是否用户注册如下:

   @Override
    protected void onCreate(Bundle savedInstanceState) {


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

因此,当用户未注册时,LauncherActivity将启动。

答案 1 :(得分:-1)

如果是我,我会使用API​​密钥进行身份验证。我宁愿将API密钥存储在一个数据库中,该数据库只能由它所使用的设备使用,而不是任何人都可以在任何地方使用的用户名和密码组合。

您可以在Android设备上拥有一个包含API密钥的数据库或某个本地存储。当应用程序启动时,它将检查是否有API密钥。如果不是,则意味着他们需要登录。这是当您显示登录屏幕时。他们输入凭据,当他们登录时,会将他们的信息和设备的信息发送到服务器。

如果经过身份验证,服务器将返回供设备使用的API密钥。然后,Android设备会将此API密钥存储在其本地内存中,现在它将知道它已登录,并将使用API​​密钥从Web服务访问信息。