2015-03-02 85 views
0

我对Android非常陌生,目前我正在制作一个应用程序,用户可以输入一次ID码(用作登录名),并且可以使用其他功能的应用程序。Android - 显示来自MySQL的数据

我目前停留在显示MySQL服务器的数据。使用用户输入的ID(这是唯一的,只有用户的标识),我可以显示用户的信息(通过TextView或其他)。

这是我到目前为止的代码:

public class MainActivity3Activity extends Activity { 


    HttpPost httppost; 
    StringBuffer buffer; 
    HttpResponse response; 
    HttpClient httpclient; 
    List<NameValuePair> nameValuePairs; 
    ProgressDialog dialog = null; 
    TextView tv; 
    TextView tv2; 
    String get; 

private WebView webView; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main_activity3); 

    tv = (TextView)findViewById(R.id.tv); 
    tv2 = (TextView)findViewById(R.id.tv2); 

    webView = (WebView) findViewById(R.id.webView); 
    webView.getSettings().setJavaScriptEnabled(true); 
    webView.loadUrl("http://usamobileapp.pe.hu/webservice/student_info.php"); 

    SharedPreferences preferences = getSharedPreferences("rfid", Context.MODE_PRIVATE); 
    if(preferences.contains("rfid")){ 
     get = preferences.getString("rfid", null); 
    } 

} 

所以我的问题是什么我在这里做什么?我对httpost非常熟悉,但我想知道如何在登录过程中使用先前输入的ID显示用户信息?我听过类似JSON解析的东西,但我不太确定如何使用它。

如何显示与他输入的ID相匹配的用户信息?如何使用TextView进行分页?

感谢您的帮助。

PS。请忽略那里的webview。我只用它作为示例,如果我的应用程序真的连接到我的PHP。

回答

1

要使用实施登录/注册系统REST API MySql你需要一个服务器端的API,例如在PHP中操纵数据库。

你需要的东西一样,在服务器端:

// 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 
     $response["error"] = FALSE; 
     $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"] = TRUE; 
     $response["error_msg"] = "Incorrect email or password!"; 
     echo json_encode($response); 
    } 

和查询数据库的功能:

public function getUserByEmailAndPassword($username, $password) { 
    $query = $this->dbh->prepare("SELECT * FROM users2 WHERE username = :username"); 
    $query->bindParam(':username', $username); 
    $result = $query->execute(); 
    // check for results 
    if ($query->rowCount() > 0) { 
     $result = $query->fetch(PDO::FETCH_ASSOC); 
     $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; 
    } 
} 

Android的 '呼吁' 的PHP脚本:

private static String login_tag = "login"; 
public void loginUser(String username, String password) throws ExecutionException, InterruptedException { 
    // Building Parameters 
    List<NameValuePair> params = new ArrayList<NameValuePair>(); 
    params.add(new BasicNameValuePair("tag", login_tag)); 
    params.add(new BasicNameValuePair("username", username)); 
    params.add(new BasicNameValuePair("password", password)); 
    jsonParser = new DbHandler(activity, this, params).execute(); 
} 

这里是DbHandler:

public DbHandler1(Activity activity, MyCallback dbIntf, List<NameValuePair> params) { 
     this.activity = activity; 
     intf = dbIntf; 
     this.params = params; 
    } 


    public JSONObject makeHttpRequest() { 
     // Making HTTP request 
     try { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(MainActivity.baseUrl); 
      //If database contains greek characters instantiate with UTF-8 Encoding 
      httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); 

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

     } catch (HttpHostConnectException e) { 
      new Handler(Looper.getMainLooper()).post(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(activity, R.string.connection_error, Toast.LENGTH_LONG).show(); 
       } 
      }); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      //If database contains greek characters instantiate with UTF-8 Encoding 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "UTF-8"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 

     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 
    } 


    @Override 
    protected JSONObject doInBackground(Void... params) { 
     jObj = makeHttpRequest(); 
     return jObj; 
    } 

    @Override 
    protected void onPostExecute(JSONObject jsonObject) { 
     super.onPostExecute(jsonObject); 
     try { 
      intf.onRemoteCallComplete(jsonObject); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      e.printStackTrace(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

因此,PHP脚本'捕捉'标签,如果用户存在,它会返回一个JSON响应给设备。例如:

{ 
    "tag": "login", 
    "success": 1, 
    "error": 0, 
} 

从MySql服务器传输的数据必须是JSON编码的。

在Android设备上,您必须阅读JSON响应并采取相应措施。

请看这里了解更多详情。

+1

很大。这更像它。 – 2015-03-02 18:27:43