Android的工作室 - 使用抽射从服务器获取JSON数据 [英] Android Studio - Using Volley to get JSON data from the server

查看:367
本文介绍了Android的工作室 - 使用抽射从服务器获取JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好所有你的Andr​​oid codeRS在那里!

这是创建Android Studio中一个登录系统,并且已经给自己买了与我的code麻烦我的第一次尝试。

我的PHP脚本总是返回作为东西JSON和我试图解析JSON在我LoginActivity,登录-method里面,但我发现
creditentials后,下面的错误被转发到服务器和被点击登录按钮:

  I / qtaguid:无法write_ctrl(U 43)解析度= -1错误号= 22
I / qtaguid:去标记插座43失败错误号= -22
W / NetworkManagementSocketTagger:untagSocket(43)失败,错误号-22

它确实是更早的时候,我是做了stringRequest代替jsonRequest,所以一切应该是在服务器端的罚款。因为我很新的Andr​​oid开发,我不能由我自己来这个数字一出来,需要迫切你的帮助。

下面是我没有进口LoginActivity:

 公共类LoginActivity扩展AppCompatActivity实现View.OnClickListener {    //定义视图
    私人的EditText editTextEmail,editTextPassword;
    私人按钮buttonLogin;
    私人进度进展情况;
    私人UserLocalStore userLocalStore;    私人布尔的loggedIn = FALSE;
    私人最终字符串标记=;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);        getSupportActionBar()隐藏()。 //隐藏操作栏登录活动        的setContentView(R.layout.activity_login); //设置内容视图        //初始化意见        //领域的EditText
        editTextEmail =(EditText上)findViewById(R.id.editTextEmail);
        editTextPassword =(EditText上)findViewById(R.id.editTextPassword);        // 纽扣
        buttonLogin =(按钮)findViewById(R.id.buttonLogin);        //其他
        进度=(进度)findViewById(R.id.progressBar);        //此方法将设置守望的EditTextFields
        //该方法将手表设置为EditTextFields值。
        //如果没有在EditTextField输入,登录按钮被禁用。
        //相应地,如果有在字段文本,登录按钮被激活。
        守望者(editTextEmail,editTextPassword,buttonLogin);
        //在键式监听器
        buttonLogin.setOnClickListener(本);    }    //观察者方法来检查的EditText字段的值
    公共无效守望者(最后的EditText EDITTEXT,最终的EditText editPassword,最终Button按钮)
    {
        editText.addTextChangedListener(新TextWatcher(){
            公共无效afterTextChanged(编辑S){                如果(editText.length()== 0&放大器;&放大器; editPassword.length()== 0)//如果文本字段的长度等于0
                    button.setEnabled(假); //禁用发送按钮
                其他
                    button.setEnabled(真); //否则启用            }            公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数后INT){
            }            公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数){
            }
        });        如果(editText.length()== 0安培;&安培; editPassword.length()== 0)
            button.setEnabled(假); //禁止在应用程序启动
    }    @覆盖
    保护无效onResume(){
        super.onResume();        共享preferences共享preferences = getShared preferences(Config.SHARED_ preF_NAME,Context.MODE_PRIVATE);        的loggedIn =共享preferences.getBoolean(Config.LOGGEDIN_SHARED_ preF,FALSE);        //如果变量的loggedIn的值为true
        如果(!的loggedIn){            //我们将开始课程活动
            意向意图=新意图(LoginActivity.this,CourseActivity.class);
            startActivity(意向);
        }
    }    私人无效登录(){        //从编辑文本获取的值
        。最后弦乐电子邮件= editTextEmail.getText()的toString()修剪();
        最终的字符串密码= editTextPassword.getText()的toString()修剪()。        //创建一个JSON对象请求
        JsonObjectRequest jsonObjectRequest =新JsonObjectRequest(Request.Method.POST,Config.LOGIN_URL,空,新Response.Listener<&JSONObject的GT;(){            @覆盖
            公共无效onResponse(JSONObject的响应){
                Log.d(TAG,response.toString());                //这条线不会打印出来
                的System.out.println(响应);                尝试{                    字符串json_status = response.getString(状态);
                    字符串消息= response.getString(信息);                    如果(json_status.equalsIgnoreCase(Config.LOGIN_SUCCESS)){
                        的System.out.println(消息);
                    }                }赶上(JSONException E){
                    Toast.makeText(getApplicationContext(),错误:+ e.getMessage(),Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        },
                新Response.ErrorListener(){
                    @覆盖
                    公共无效onErrorResponse(VolleyError错误){
                        //你可以在这里处理错误,如果你想
                    }
                }){
            @覆盖
            保护地图<字符串,字符串> getParams()方法抛出AuthFailureError {
                地图<字符串,字符串> PARAMS =新的HashMap<>();                //添加参数要求
                params.put(Config.KEY_EMAIL,电子邮件);
                params.put(Config.KEY_PASSWORD,密码);                //返回参数
                返回PARAMS;            }
        };        //添加字符串要求到队列
        请求队列请求队列= Volley.newRequestQueue(本);
        requestQueue.add(jsonObjectRequest);    }    @覆盖
    公共无效的onClick(视图v){        开关(v.getId()){
            //如果被点击登录按钮
            案例R.id.buttonLogin:
                登录();点击登录按钮后//开始登录方法                // startActivity(新意图(这一点,MainActivity.class));
                打破;
        }
    }
}

这是我的PHP:

 < PHP
require_once(dbconnect.php);// POST变量
$ post_email = $ _ POST [电子邮件];
$ post_password = $ _ POST ['密码'];// prepare SQL查询
$语句= $ pdo-> prepare(SELECT * FROM用户WHERE =电子邮件:电子邮件);
$ stmt->执行(阵列(
    :电子邮件'=> $ post_email,
  ));$行= $ stmt->取(PDO :: FETCH_ASSOC);
如果($ stmt-> rowCount时()> 0&放大器;&安培; password_verify($ post_password,$行['密码'])及和放大器;!$行['角色'] ='工作人员'){      $ USER =阵列(); //创建为用户信息的数组      $用户['身份证'] = $行['身份证'];
      $用户['名'] = $行[名称];
      $用户[电子邮件] = $行[电子邮件];
      $用户['密码'] = $行['密码'];
      $用户['角色'] = $行['角色'];      //回声json_en code([消息=>中成功]);
      回声json_en code([状态=>中成功,消息=>中成功登录]); //格式化数组JSON}其他{    回声json_en code([状态=>中的错误,消息=>中不正确的creditentials]);
}


解决方案

您可能没有传递参数,可以我通常使用这个语法:

  //从编辑文本的值
 。最后弦乐电子邮件= editTextEmail.getText()的toString()修剪();
 最终的字符串密码= editTextPassword.getText()的toString()修剪()。 地图<弦乐,对象> PARAMS =新ArrayMap&所述;>(2);
 //添加参数要求
 params.put(Config.KEY_EMAIL,电子邮件);
 params.put(Config.KEY_PASSWORD,密码);    //创建一个JSON对象请求
    JsonObjectRequest jsonObjectRequest =新JsonObjectRequest(Request.Method.POST,网址,新的JSONObject(PARAMS)
            新Response.Listener<&JSONObject的GT;()
            {
             @覆盖
             公共无效onResponse(JSONObject的响应)
             {
              Log.d(TAG,response.toString());
              // 其他的东西 ...
             }
            },
            新Response.ErrorListener()
            {
                @覆盖
                公共无效onErrorResponse(VolleyError错误)
                {
                    //你可以在这里处理错误,如果你想
                }
            });    //添加字符串要求到队列
    请求队列请求队列= Volley.newRequestQueue(本);
    requestQueue.add(jsonObjectRequest);

此外,您可能要处理一个Singleton类中的所有请求抽射,看看这个<一个href=\"http://stackoverflow.com/questions/28172496/android-volley-how-to-isolate-requests-in-another-class/30604191#30604191\">SO问题。

希望这有助于以任何方式:)

Hello to all of you Android coders out there!

This is my first attempt to create a login system in Android Studio and already got myself into trouble with my code.

My PHP script always returns something as JSON and I'm trying to parse that JSON in my LoginActivity, inside the login -method, but I'm getting the following error after creditentials were forwarded to the server and the login button was clicked:

I/qtaguid﹕ Failed write_ctrl(u 43) res=-1 errno=22
I/qtaguid﹕ Untagging socket 43 failed errno=-22
W/NetworkManagementSocketTagger﹕ untagSocket(43) failed with errno -22

It did work earlier, when I was doing a stringRequest instead of jsonRequest, so everything should be fine on the server side. Since I'm very new to Android development, I'm unable to figure this one out by myself and need desperately your help.

Here's my LoginActivity without the imports:

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    // Define Views
    private EditText editTextEmail, editTextPassword;
    private Button buttonLogin;
    private ProgressBar progress;
    private UserLocalStore userLocalStore;

    private boolean loggedIn = false;
    private final String TAG = "";

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

        getSupportActionBar().hide(); // Hides the Action Bar for Login Activity

        setContentView(R.layout.activity_login); // Sets the Content View

        // Initializing Views

        // EditText fields
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        // Buttons
        buttonLogin = (Button) findViewById(R.id.buttonLogin);

        // Other
        progress = (ProgressBar) findViewById(R.id.progressBar);

        // This method will set watcher for the EditTextFields
        // The method will watch the value set to the EditTextFields.
        // If there is nothing inputted in the EditTextField, "Login" button is disabled.
        // Correspondingly, if there are text in the field, "Login" button is enabled.
        watcher(editTextEmail, editTextPassword, buttonLogin);


        // On-Click listeners
        buttonLogin.setOnClickListener(this);

    }

    // Watcher method to check the value of EditText field
    public void watcher(final EditText editText, final EditText editPassword, final Button button)
    {
        editText.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {

                if (editText.length() == 0 && editPassword.length() == 0) // If length of the text field is equal to 0
                    button.setEnabled(false); // Disable the "Send" button
                else
                    button.setEnabled(true);  // Otherwise enable

            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
        });

        if(editText.length() == 0 && editPassword.length() == 0)
            button.setEnabled(false); //disable at app start
    }

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

        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

        loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);

        // If the value of loggedIn variable is true
        if(!loggedIn) {

            // We will start the Courses activity
            Intent intent = new Intent(LoginActivity.this, CourseActivity.class);
            startActivity(intent);
        }
    }

    private void login() {

        // Get the values from the edit texts
        final String email = editTextEmail.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();

        // Creating a JSON Object request
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());

                // This line will not print out
                System.out.println(response);

                try {

                    String json_status = response.getString("status");
                    String message = response.getString("message");

                    if(json_status.equalsIgnoreCase(Config.LOGIN_SUCCESS)) {
                        System.out.println(message);
                    }

                } catch (JSONException e) {
                    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // You can handle the error here if you want
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();

                // Adding parameters to request
                params.put(Config.KEY_EMAIL, email);
                params.put(Config.KEY_PASSWORD, password);

                // Return parameters
                return params;

            }
        };

        // Adding the string request to the queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonObjectRequest);

    }

    @Override
    public void onClick(View v) {

        switch(v.getId()) {
            // If button Login was clicked
            case R.id.buttonLogin:
                login(); // Start login method after "Login" button is clicked

                // startActivity(new Intent(this, MainActivity.class));
                break;
        }
    }
}

And here's my PHP:

<?php
require_once("dbconnect.php");

// POST Variables
$post_email = $_POST['email'];
$post_password = $_POST['password'];

// Prepare the SQL query
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(array(
    ':email' => $post_email,
  ));

$row = $stmt->fetch(PDO::FETCH_ASSOC);


if($stmt->rowCount() > 0 && password_verify($post_password, $row['password']) && $row['role'] != 'staff') {

      $user = array(); // Create an array for the user information

      $user['id'] = $row['id'];
      $user['name'] = $row['name'];
      $user['email'] = $row['email'];
      $user['password'] = $row['password'];
      $user['role'] = $row['role'];

      // echo json_encode(["message" => "success"]);
      echo json_encode(["status" => "success", "message" => "Successfully logged in"]); // Format the array to JSON

} else {

    echo json_encode(["status" => "error", "message" => "Incorrect creditentials"]);
}

解决方案

You might not be passing the params, I usually use this syntax:

 // Get the values from the edit texts
 final String email = editTextEmail.getText().toString().trim();
 final String password = editTextPassword.getText().toString().trim();

 Map<String, Object> params = new ArrayMap<>(2);
 // Adding parameters to request
 params.put(Config.KEY_EMAIL, email);
 params.put(Config.KEY_PASSWORD, password);

    // Creating a JSON Object request
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
            new Response.Listener<JSONObject>()
            {
             @Override
             public void onResponse(JSONObject response)
             {
              Log.d(TAG, response.toString());
              // other stuff ...
             }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) 
                {
                    // You can handle the error here if you want
                }
            }); 

    // Adding the string request to the queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonObjectRequest);

Also, you might want to handle all the volley requests in a Singleton class, have a look at this SO question.

Hope this helps in any way :)

这篇关于Android的工作室 - 使用抽射从服务器获取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆