【问题标题】:Android - Display data from MySQLAndroid - 显示来自 MySQL 的数据
【发布时间】:2015-03-02 16:13:17
【问题描述】:

我对 Android 非常陌生,我目前正在制作一个应用程序,用户可以在其中输入一次 ID 号(用作登录),然后他可以使用该应用程序的其余功能。

我目前卡在显示来自 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 显示?

感谢您的帮助。

附言。请忽略那里的webview。如果我的应用真的连接到我的 php,我只会将其用作示例。

【问题讨论】:

    标签: java android mysql json


    【解决方案1】:

    1)make a restful API on your server

    2) 在您的客户端 (android) 上接收 API 元素,我建议 retrofit,它太容易了

    3) 显示您的数据! otto 会有所帮助:)

    想要更多? more,

    这似乎很难,但如果你学习几天,你就会学会它。

    【讨论】:

      【解决方案2】:

      要使用 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 编码的。

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

      点击此处了解更多详情。

      【讨论】:

      • 太棒了。这更像它。
      【解决方案3】:

      您需要在与 UI 不同的线程上执行网络操作。 阅读关于休息Google I/O 2010 - Developing Android REST client application
      documentation
      在客户端,对于休息 api,我喜欢使用 retrofit + gsongroundy
      或者php,使用slim frameworkHow to create REST API for Android app using PHP, Slim and MySQL 很容易创建rest api

      【讨论】:

        猜你喜欢
        • 2012-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 2017-07-15
        • 1970-01-01
        相关资源
        最近更新 更多