Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/180.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android Studio-使用截取从服务器获取JSON数据_Java_Android_Json_Android Volley - Fatal编程技术网

Java Android Studio-使用截取从服务器获取JSON数据

Java Android Studio-使用截取从服务器获取JSON数据,java,android,json,android-volley,Java,Android,Json,Android Volley,这是我第一次尝试在androidstudio中创建登录系统,我的代码已经让我陷入了麻烦 我的PHP脚本总是以JSON的形式返回一些东西,我试图在login-method中的LoginActivity中解析JSON,但是我得到了 将creditentials转发到服务器并单击登录按钮后出现以下错误: I/qtaguid﹕ Failed write_ctrl(u 43) res=-1 errno=22 I/qtaguid﹕ Untagging socket 43 failed errno=-22 W

这是我第一次尝试在androidstudio中创建登录系统,我的代码已经让我陷入了麻烦

我的PHP脚本总是以JSON的形式返回一些东西,我试图在login-method中的LoginActivity中解析JSON,但是我得到了 将creditentials转发到服务器并单击登录按钮后出现以下错误:

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
它在我之前做stringRequest而不是jsonRequest时确实起了作用,所以服务器端的一切都应该很好。因为我对安卓系统的开发还很陌生,所以我自己无法解决这个问题,迫切需要你的帮助

以下是我在没有导入的情况下的登录活动:

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;
        }
    }
}
公共类LoginActivity扩展AppCompatActivity实现View.OnClickListener{
//定义视图
私人编辑邮件,编辑密码;
私人按钮按钮;
私人进度条进度;
私有UserLocalStore UserLocalStore;
私有布尔loggedIn=false;
私有最终字符串标记=”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getSupportActionBar().hide();//隐藏登录活动的操作栏
setContentView(R.layout.activity_login);//设置内容视图
//初始化视图
//编辑文本字段
editTextEmail=(EditText)findViewById(R.id.editTextEmail);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
//钮扣
buttonLogin=(按钮)findViewById(R.id.buttonLogin);
//其他
进度=(ProgressBar)findViewById(R.id.ProgressBar);
//此方法将为EditTextFields设置监视程序
//该方法将监视设置到EditTextFields的值。
//如果EditTextField中没有输入任何内容,“登录”按钮将被禁用。
//相应地,如果字段中有文本,“登录”按钮被启用。
观察者(editTextEmail、editTextPassword、buttonLogin);
//单击侦听器
buttonLogin.setOnClickListener(此);
}
//用于检查EditText字段值的Watcher方法
公共无效观察程序(最终编辑文本编辑文本、最终编辑文本编辑密码、最终按钮)
{
editText.addTextChangedListener(新的TextWatcher(){
公共无效后文本已更改(可编辑){
if(editText.length()==0&&editPassword.length()==0)//如果文本字段的长度等于0
button.setEnabled(false);//禁用“发送”按钮
其他的
button.setEnabled(true);//否则启用
}
更改前文本之前的公共void(字符序列s、int start、int count、int after){
}
public void onTextChanged(字符序列、int start、int before、int count){
}
});
if(editText.length()==0&&editPassword.length()==0)
button.setEnabled(false);//在应用程序启动时禁用
}
@凌驾
受保护的void onResume(){
super.onResume();
SharedReferences SharedReferences=GetSharedReferences(Config.SHARED\u PREF\u NAME,Context.MODE\u PRIVATE);
loggedIn=SharedReferences.getBoolean(Config.loggedIn\u SHARED\u PREF,false);
//如果loggedIn变量的值为true
如果(!loggedIn){
//我们将开始课程活动
意向意向=新意向(LoginActivity.this、CourseActivity.class);
星触觉(意向);
}
}
私有void登录(){
//从编辑文本中获取值
最终字符串email=editTextEmail.getText().toString().trim();
最终字符串密码=editTextPassword.getText().toString().trim();
//创建JSON对象请求
JsonObjectRequest JsonObjectRequest=新JsonObjectRequest(Request.Method.POST,Config.LOGIN\u URL,null,new Response.Listener()){
@凌驾
公共void onResponse(JSONObject响应){
Log.d(TAG,response.toString());
//这行不能打印出来
System.out.println(响应);
试一试{
String json_status=response.getString(“status”);
字符串消息=response.getString(“消息”);
if(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(截击错误){
//如果需要,可以在此处处理错误
}
}) {
@凌驾
受保护的映射getParams()引发AuthFailureError{
Map params=新的HashMap();
//向请求添加参数
参数put(Config.KEY_EMAIL,EMAIL);
参数put(Config.KEY_PASSWORD,PASSWORD);
//返回参数
返回参数;
}
};
//将字符串请求添加到队列
RequestQueue RequestQueue=Volley.newRequestQueue(this);
add(jsonObjectRequest);
}
@凌驾
公共void onClick(视图v){
开关(v.getId()){
//如果单击了按钮登录
案例R.id.buttonLogin:
login();//单击“登录”按钮后启动登录方法
//startActivity(新意图(this,MainActivity.class));
打破
}
}
}
和h
<?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"]);
}
 // 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);