1

所以我正在开发一个小的 android 应用程序,并且对编码非常陌生。到目前为止,我遵循了一个教程,可以让用户登录/注册,并将该信息存储/检索到 MYSQL 数据库中。问题是我需要添加代码来存储位置,我很困惑。

这是我所拥有的大部分内容,希望能得到一些帮助:

我的数据库设置为:uid - 名称 - 电子邮件 - 密码 - salt - created_at - updated_at - loclat - loclong

主要活动类:

public class DashboardActivity extends Activity {

UserFunctions userFunctions;
Button btnLogout;
Button btnloc;
GPSTracker gps;




@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



         /**
     * Dashboard Screen for the application
     * */
    // Check login status in database
    userFunctions = new UserFunctions();
    if(userFunctions.isUserLoggedIn(getApplicationContext())){

   // user already logged in show databoard
        setContentView(R.layout.dashboard);

        gps = new GPSTracker(DashboardActivity.this);
        if(gps.canGetLocation()){

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            // \n is for new line
            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();

        }else{
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        };


        btnLogout = (Button) findViewById(R.id.btnLogout);

        btnLogout.setOnClickListener(new View.OnClickListener() {


            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                userFunctions.logoutUser(getApplicationContext());
                Intent login = new Intent(getApplicationContext(), LoginActivity.class);
                login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(login);
                // Closing dashboard screen
                finish();
            }
        });

    }else{
        // user is not logged in show login screen
        Intent login = new Intent(getApplicationContext(), LoginActivity.class);
        login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(login);
        // Closing dashboard screen
        finish();
    }
}
}

用户函数java文件:

public class UserFunctions {

private JSONParser jsonParser;

// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "url removed";
private static String registerURL = "url removed";

private static String login_tag = "login";
private static String register_tag = "register";

// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * @param email
 * @param password
 * */
public JSONObject loginUser(String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    // Log.e("JSON", json.toString());
    return json;
}

/**
 * function make Login Request
 * @param name
 * @param email
 * @param password
 * */
public JSONObject registerUser(String name, String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));

    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
    // return json
    return json;
}

/**
 * Function get Login status
 * */
public boolean isUserLoggedIn(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    int count = db.getRowCount();
    if(count > 0){
        // user logged in
        return true;
    }
    return false;
}

/**
 * Function to logout user
 * Reset Database
 * */
public boolean logoutUser(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}

}

JSON文件

public class JSONParser {

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

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // 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();

    } 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 + "n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } 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;

}
}

世界服务

public class LocalWordService extends Service {
  private final IBinder mBinder = new MyBinder();
  private ArrayList<String> list = new ArrayList<String>();

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    Random random = new Random();
    if (random.nextBoolean()) {
      list.add("Linux");
    }
    if (random.nextBoolean()) {
      list.add("Android");
    }
    if (random.nextBoolean()) {
      list.add("iPhone");
    }
    if (random.nextBoolean()) {
      list.add("Windows7");
    }
    if (list.size() >= 20) {
      list.remove(0);
    }
    return Service.START_NOT_STICKY;
  }

  @Override
  public IBinder onBind(Intent arg0) {
    return mBinder;
  }

  public class MyBinder extends Binder {
    public LocalWordService getService() {
      return LocalWordService.this;
    }
  }

  public List<String> getWordList() {
    return list;
  }

} 

Dbase.php 文件:

if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];

// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);

// check for tag type
if ($tag == 'login') {
    // Request type is check Login
    $email = $_POST['email'];
    $password = $_POST['password'];

    // check for user
    $user = $db->getUserByEmailAndPassword($email, $password);
    if ($user != false) {
        // user found
        // echo json with success = 1
        $response["success"] = 1;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        echo json_encode($response);
    } else {
        // user not found
        // echo json with error = 1
        $response["error"] = 1;
        $response["error_msg"] = "Incorrect email or password!";
        echo json_encode($response);
    }
} else if ($tag == 'register') {
    // Request type is Register new user
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    // check if user is already existed
    if ($db->isUserExisted($email)) {
        // user is already existed - error response
        $response["error"] = 2;
        $response["error_msg"] = "User already existed";
        echo json_encode($response);
    } else {
        // store user
        $user = $db->storeUser($name, $email, $password);
        if ($user) {
            // user stored successfully
            $response["success"] = 1;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user failed to store
            $response["error"] = 1;
            $response["error_msg"] = "Error occured in Registartion";
            echo json_encode($response);
        }
    }
} else {
    echo "Invalid Request";
}
} else {
echo "Access Denied";
}
?>

DB_Connect.php

<?php
class DB_Connect {

// constructor
function __construct() {

}

// destructor
function __destruct() {
    // $this->close();
}

// Connecting to database
public function connect() {
    require_once 'include/config.php';
    // connecting to mysql
    $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    // selecting database
    mysql_select_db(DB_DATABASE);

    // return database handler
    return $con;
}

// Closing database connection
public function close() {
    mysql_close();
}

}

?>

DB_Functions.php

<?php

class DB_Functions {

private $db;

//put your code here
// constructor
function __construct() {
    require_once 'DB_Connect.php';
    // connecting to database
    $this->db = new DB_Connect();
    $this->db->connect();
}

// destructor
function __destruct() {

}

/**
 * Storing new user
 * returns user details
 */
public function storeUser($name, $email, $password) {
    $uuid = uniqid('', true);
    $hash = $this->hashSSHA($password);
    $encrypted_password = $hash["encrypted"]; // encrypted password
    $salt = $hash["salt"]; // salt
    $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
    // check for successful store
    if ($result) {
        // get user details 
        $uid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
        // return user details
        return mysql_fetch_array($result);
    } else {
        return false;
    }
}

/**
 * Get user by email and password
 */
public function getUserByEmailAndPassword($email, $password) {
    $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
    // check for result 
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        $result = mysql_fetch_array($result);
        $salt = $result['salt'];
        $encrypted_password = $result['encrypted_password'];
        $hash = $this->checkhashSSHA($salt, $password);
        // check for password equality
        if ($encrypted_password == $hash) {
            // user authentication details are correct
            return $result;
        }
    } else {
        // user not found
        return false;
    }
}

/**
 * Check user is existed or not
 */
public function isUserExisted($email) {
    $result = mysql_query("SELECT email from users WHERE email = '$email'");
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        // user existed 
        return true;
    } else {
        // user not existed
        return false;
    }
}

/**
 * Encrypting password
 * @param password
 * returns salt and encrypted password
 */
public function hashSSHA($password) {

    $salt = sha1(rand());
    $salt = substr($salt, 0, 10);
    $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
    $hash = array("salt" => $salt, "encrypted" => $encrypted);
    return $hash;
}

/**
 * Decrypting password
 * @param salt, password
 * returns hash string
 */
public function checkhashSSHA($salt, $password) {

    $hash = base64_encode(sha1($password . $salt, true) . $salt);

    return $hash;
}

}

?>

对不起,代码墙,但我只是不确定什么是有用的,什么是没有帮助的。如何使用主要活动的 oncreate 将纬度和经度插入数据库?我得到纬度和经度就好了,登录时连接到数据库。

4

1 回答 1

0

我对您的课程进行了一些重要的修改,以使他们更好地工作。

PHP

DB_Functions.php

我添加了一个新功能,以便我们可以对用户表进行更新。

    /**
     * Update user by email and password
     */
    public function updateUserByEmailAndPassword($email, $password, $lon, $lat) {
      $user = $this -> getUserByEmailAndPassword($email, $password);
        if ($user != false) {   
            $unique_id=$user["unique_id"];
            mysql_query("UPDATE users SET loclong='$lon', loclat='$lat', updated_at=now() WHERE unique_id='$unique_id'") or die(mysql_error());
            $affected = mysql_affected_rows();
            if($affected > 0){
             return true;
           } else {
            return false;
           }
        }else{
         return false;
        }
    }

Dbase.php 我添加了一个新标签="update_location" 来接收和管理用户更新的 POST 请求

else if ($tag == 'update_location') { // check for tag type
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];

        // Request lon/lat
        $lon = $_POST['lon'];
        $lat = $_POST['lat'];

        // check for user
        $state = $db->UpdateUserByEmailAndPassword($email, $password, $lon, $lat);
        if ($state != false) {
            $response["success"] = 1;
            $response["success_msg"] = "Geo location data update successfull!";
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Geo location data update failed!";
            echo json_encode($response);
        }
    } 

我还对您的 database.table (users) 做了一些更改,因为经度/纬度不是整数替换

 `loclat` int(11) NOT NULL,
 `loclong` int(11) NOT NULL

`loclat` varchar(11) NOT NULL,
`loclong` varchar(11) NOT NULL,

最多的修改是在 DashboardActivity 中进行的。看看里面,如果你有问题随时问我。

public class DashboardActivity extends Activity {

   public static String USER_FUNCTIONS = "user functions";
   private static String KEY_SUCCESS = "success";

   /**
    * Millisecondes
    */
   private static int POLLING_WAITING_TIME = 5 * 1000;
   UserFunctions mUserFunctions;
   Button btnLogout;
   Button btnloc;
   GPSTracker gps;

   private Handler mHandler;
   private Runnable mRunnable;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.dashboard);

      Bundle extras = getIntent().getExtras();
      if (extras != null) {
         if (extras.containsKey(USER_FUNCTIONS)) {
            mUserFunctions = (UserFunctions) extras.getSerializable(USER_FUNCTIONS);
         }
      }
      toggleActivities();
   }

   @Override
   protected void onResume() {
      super.onResume();
      toggleActivities();
   }

   /**
    * 
    */
   private void toggleActivities() {
      // Check login status in database
      if (mUserFunctions != null && mUserFunctions.isUserLoggedIn(getApplicationContext())) {
         // user already logged in show databoard

         btnLogout = (Button) findViewById(R.id.btnLogout);
         btnLogout.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
               // TODO Auto-generated method stub
               mUserFunctions.logoutUser(getApplicationContext());
               Intent login = new Intent(getApplicationContext(), LoginActivity.class);
               login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
               startActivity(login);
               // Closing dashboard screen
               finish();
            }
         });

      } else {
         // user is not logged in show login screen
         Intent login = new Intent(getApplicationContext(), LoginActivity.class);
         login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         startActivity(login);
         // Closing dashboard screen
         finish();
      }
      // startTimer
      timer();
   }

   /**
    * managed HandlerManger and controls the timer
    */
   private void timer() {
      mRunnable = new HandlerManger();
      mHandler = new Handler();
      mHandler.postDelayed(mRunnable, POLLING_WAITING_TIME);
   }

   /**
    * 
    */
   private void processGPSTracker() {
      if (mUserFunctions == null || !mUserFunctions.isUserLoggedIn(getApplicationContext()))
         return;

      gps = new GPSTracker(DashboardActivity.this);
      if (gps.canGetLocation()) {

         double latitude = gps.getLatitude();
         double longitude = gps.getLongitude();

         JSONObject json = mUserFunctions.updateUserGeoLocation(Double.valueOf(longitude)
               .toString(), Double.valueOf(latitude).toString());

         // check for login response
         try {
            if (json.getString(KEY_SUCCESS) != null && json.getString(KEY_SUCCESS).equals("1")) {
               Log.i("DashboardActivity", "Update on geolocation success");
            } else {
               Log.e("DashboardActivity", "Update on geolocation Failed");
            }
         } catch (JSONException e) {
            e.printStackTrace();
         }

         // \n is for new line
         Toast.makeText(getApplicationContext(),
               "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG)
               .show();

      } else {
         // can't get location
         // GPS or Network is not enabled
         // Ask user to enable GPS/network in settings
         gps.showSettingsAlert();
      }
   }

   /**
    * Timer business logic runner
    * 
    * @author Festus Tamakloe
    */
   private class HandlerManger implements Runnable {

      public void run() {
         processGPSTracker();
      }

   }
}

在 userFunctions 中,我还添加了一种与 http 服务器通信的新方法

 public JSONObject updateUserGeoLocation(String lon, String lat) {
      // Building Parameters
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("tag", LOCATION_UPDATE_TAG));
      params.add(new BasicNameValuePair("email", email));
      params.add(new BasicNameValuePair("password", password));
      params.add(new BasicNameValuePair("lon", lon));
      params.add(new BasicNameValuePair("lat", lat));
      JSONObject json = jsonParser.getJSONFromUrl(LOCATION_UPDATE_URL, params);
      return json;
   }

我希望这可以帮助你

于 2013-03-12T16:19:24.160 回答