跟踪json对象,如果为空或null或空格

时间:2016-04-08 10:34:01

标签: php android json

每当登录详细信息不正确但无法以正确的方式执行此操作时,我都会尝试向其发送消息。我不知道要测量什么以及如何测量JSON数组的JSON对象,因为我可以触发Toast通知用户无效的登录详细信息。

这是我的PHP代码

<?php
require 'connection.php';
header('Content-Type: application/json');
 try{
    $resultset ="";
    $username = filter_input(INPUT_POST, 'name');
    $pssword =  filter_input(INPUT_POST, 'password');

    if($username == "" ){
        $results = "Invalid Entry";
        echo json_encode(array("user_data"=>$results));
    }else{
        $stmt = $db->prepare('SELECT * '
                        . 'FROM users1 '
                        . 'WHERE name = :uname AND password = :password ');
        $stmt->bindParam(':uname', $username);
        $stmt->bindParam(':password', $pssword);
        $stmt->execute();

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

        if($results > 0 ){
            echo json_encode(array("user_data"=>$results) );
        } else{
            echo json_encode(array("user_data"=>$results));
    }
 }
 }catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
$stmt = NULL;
$results = NULL;
exit();
?> 

如果有效登录详细信息,我会得到以下结果

{"user_data":{"id":"1","name":"jimmyjanea","password":"23456","email":"dd@ww.com"}}

及以下是无效登录详细信息的结果

{"user_data":false}

请参阅我的java代码&#34; Main.java&#34;

package com.example.enan.register_login;

public class Main extends AppCompatActivity implements View.OnClickListener {
EditText name, password;
String Name, Password;
Context ctx=this;
String NAME=null, PASSWORD=null, EMAIL=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    name = (EditText) findViewById(R.id.main_name);
    password = (EditText) findViewById(R.id.main_password);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

public void main_register(View v){
    startActivity(new Intent(this, Register.class));
}
public void main_login(View v){
    Name = name.getText().toString();
    Password = password.getText().toString();

    if(name.getText().length()==0){
        Toast.makeText(getApplicationContext(),
                "Please Enter your name", Toast.LENGTH_LONG).show();
        Intent intent = getIntent();
        startActivity(intent);
        name.requestFocus();
    }else if(password.getText().length()==0){
        Toast.makeText(getApplicationContext(),
                "Please Enter your password", Toast.LENGTH_LONG).show();
        Intent intent = getIntent();
        startActivity(intent);
        password.requestFocus();
    }else{
        Intent intent = getIntent();
        startActivity(intent);
        BackGround b = new BackGround();
        b.execute(Name, Password);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.main_login:
            break;
    }
}

class BackGround extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        String name = params[0];
        String password = params[1];
        String data="";
        int tmp;

        try {
            URL url = new URL("http://10.0.2.2/BirdBreedingManagement/scripts/login.php");
            String urlParams = "name="+name+"&password="+password;

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(urlParams.getBytes());
            os.flush();
            os.close();

            InputStream is = httpURLConnection.getInputStream();
            while((tmp=is.read())!=-1){
                data+= (char)tmp;
            }

            is.close();
            httpURLConnection.disconnect();

            return data;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "Exception: "+e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "Exception: "+e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String s) {
        String err=null;
        int istat;

        try {
            istat = 0;
            JSONObject root = new JSONObject(s);
            JSONObject user_data = root.getJSONObject("user_data");

            NAME = user_data.getString("name");
            PASSWORD = user_data.getString("password");
            EMAIL = user_data.getString("email");

            if(root.length()>=1){
                Toast.makeText(getApplicationContext(),
                        "login successful", Toast.LENGTH_LONG).show();

                Intent i = new Intent(ctx, Home.class);
                i.putExtra("name", NAME);
                i.putExtra("password", PASSWORD);
                i.putExtra("email", EMAIL);
                i.putExtra("err", err);
                startActivity(i);
            }else{
                Toast.makeText(getApplicationContext(),
                        "Invalid Login Detais", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            err = "Exception: "+e.getMessage();
        }
    }
}
}

我是android编程的新手,我真的需要帮助来学习这门语言来构建这个应用程序。

3 个答案:

答案 0 :(得分:0)

在代码中添加一些日志,例如Log.d("TEST-JSON","response:"+s);

代码中的示例

protected void onPostExecute(String s) {
        String err=null;
        int istat;

        try {
            istat = 0;
            Log.d("TEST-JSON","response:"+s);
            JSONObject root = new JSONObject(s);
            JSONObject user_data = root.getJSONObject("user_data");

            NAME = user_data.getString("name");
            PASSWORD = user_data.getString("password");
            EMAIL = user_data.getString("email");

            if(root.length()>=1){
                Toast.makeText(getApplicationContext(),
                        "login successful", Toast.LENGTH_LONG).show();

                Intent i = new Intent(ctx, Home.class);
                i.putExtra("name", NAME);
                i.putExtra("password", PASSWORD);
                i.putExtra("email", EMAIL);
                i.putExtra("err", err);
                startActivity(i);
            }else{
                Toast.makeText(getApplicationContext(),
                        "Invalid Login Detais", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            err = "Exception: "+e.getMessage();
        }
    }

修改

处理基本回复:

@Override
protected void onPostExecute(String s) {
        String err=null;
        int istat;

        try {
            istat = 0;
            Log.d("TEST-JSON","response:"+s);
            JSONObject root = new JSONObject(s);
            boolean user_data = root.getBoolean("user_data");


            if(user_data){
                Toast.makeText(getApplicationContext(),
                        "login successful", Toast.LENGTH_LONG).show();


            }else{
                Toast.makeText(getApplicationContext(),
                        "Invalid Login Detais", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            err = "Exception: "+e.getMessage();
        }
    }

编辑2

Use optJSONObject()返回按名称映射的值(如果存在且是JSONObject),否则返回null。

boolean user_data_aux;
JSONObject user_data = root.optJSONObject("user_data");
if(user_data==null){

    user_data_aux = root.getBoolean("user_data");

}
else{

    //MANAGE YOUR JSON OBJECT
    // DO NOT FORGET ASSIGN A VALUE TO user_data_aux WITH THE DATA OF YOUR JSON OBJECT

}

if(user_data_aux){
Toast.makeText(getApplicationContext(),
        "login successful", Toast.LENGTH_LONG).show();
        //MANAGE LOGIN


}else{
    Toast.makeText(getApplicationContext(),
            "Invalid Login Detais", Toast.LENGTH_LONG).show();
}

答案 1 :(得分:0)

使用下面的代码进行吐司

        try {
            istat = 0;
            Log.d("TEST-JSON","response:"+s);
            JSONObject root = new JSONObject(s);
try{

         JSONObject user_data_json = root.getJSONObject("user_data");
 NAME = user_data.getString("name");
            PASSWORD = user_data.getString("password");
            EMAIL = user_data.getString("email");

            if(root.length()>=1){
                Toast.makeText(getApplicationContext(),
                        "login successful", Toast.LENGTH_LONG).show();

                Intent i = new Intent(ctx, Home.class);
                i.putExtra("name", NAME);
                i.putExtra("password", PASSWORD);
                i.putExtra("email", EMAIL);
                i.putExtra("err", err);
                startActivity(i);
            }
}catch(Exception e)
{

}
try{
            boolean user_data_bol = root.getBoolean("user_data");
   if(user_data){



            }else{
                Toast.makeText(getApplicationContext(),
                        "Invalid Login Detais", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            err = "Exception: "+e.getMessage();
        }
}
catch(Exception e)
{

}

答案 2 :(得分:0)

Try 
Before parse the jsonobject give the condition receive string s is null or
not


  @Override
    protected void onPostExecute(String s) {
        String err=null;
        int istat;
        if(s!=null && !s.equals(""))  //check condition like this
        {
        try {
            istat = 0;
            JSONObject root = new JSONObject(s);
            JSONObject user_data = root.getJSONObject("user_data");

            NAME = user_data.getString("name");
            PASSWORD = user_data.getString("password");
            EMAIL = user_data.getString("email");

            if(root.length()>=1){
                Toast.makeText(getApplicationContext(),
                        "login successful", Toast.LENGTH_LONG).show();

                Intent i = new Intent(ctx, Home.class);
                i.putExtra("name", NAME);
                i.putExtra("password", PASSWORD);
                i.putExtra("email", EMAIL);
                i.putExtra("err", err);
                startActivity(i);
            }else{
                Toast.makeText(getApplicationContext(),
                        "Invalid Login Detais", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            err = "Exception: "+e.getMessage();
        }
     }
    }