无法登录,json获得成功= 0

时间:2016-03-17 03:53:38

标签: php android json login android-asynctask


谁能帮我 ?为什么我成功= 0?甚至认为我输入正确的'id'和'密码'!!
logcat:
03-17 10:21:58.773 2973-3063 /? D / JSON解析器:0
03-17 10:21:58.773 2973-3063 /? I / JSON解析器:{“成功”:0,“消息”:“用户名或密码无效”}}

非常感谢!!

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    private EditText user,pass;
    private Button login;
    ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = "http://domain/login_mobile.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        user = (EditText) findViewById(R.id.edUsername);
        pass = (EditText) findViewById(R.id.edPassword);
        login = (Button) findViewById(R.id.btnLogin);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Login().execute(user.getText().toString(),pass.getText().toString());
            }
        });
    }
    class Login extends AsyncTask<String , String , String>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Sedang proses .....");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            int success=0;
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            String id_anggota = params[0];
            String password_anggota = params[1];
            param.add(new BasicNameValuePair("id_anggota",id_anggota));
            param.add(new BasicNameValuePair("password_anggota",password_anggota));

            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL,"POST",param);
            try{
                success = json.getInt(TAG_SUCCESS);
                //Log.d("MESSAGE",msg);
                if(success == 1){
                    Log.d("Attempt","Success");
                }else
                    Log.d("JSON Parser",String.valueOf(success));
                    Log.i("JSON Parser",json.toString());
            }catch (JSONException e){
                e.printStackTrace();
            }
            return TAG_MESSAGE;
        }

        @Override
        protected void onPostExecute(String s) {
            pDialog.dismiss();
            if(s != null){
                Toast.makeText(getApplicationContext(),"WORKING",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getApplicationContext(),"NOT WORKING",Toast.LENGTH_LONG).show();
            }
        }
    }
}

json解析器代码:

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;




public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // fungsi ambil json dari url
    // lewat method HTTP POST atau GET
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // membuat request HTTP
        try {

            // cek untuk method request
            if (method == "POST") {
                // jika request method adalah POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

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

            } else if (method == "GET") {
                // jika request method adalah GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

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

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 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 {
            // try parse the string into JSON object and REMOVE invisible character (<br>,<html>)
            jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
        } catch (JSONException e) {
            Log.i("JSON Parser",json.toString());
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

php代码:

<?php 
    $con = mysqli_connect("localhost","qwerty","","asdffgg");

    if (isset($_POST['id_anggota']) && isset($_POST['password_anggota'])) { 
        $password=mysqli_real_escape_string($con,$_POST["password_anggota"]); 
        $id=mysqli_real_escape_string($con,$_POST["id_anggota"]); 
        $query = " SELECT * FROM anggota WHERE id_anggota = '$id' AND password_anggota='$password'"; 
        $$result=mysqli_query($con,$query); 
        $row = mysqli_fetch_array($result); 
        if ($row == 1) { 
            $response["success"] = 1; 
            $response["message"] = "You have been sucessfully login"; 
            echo json_encode($response); 
        } else{ 
            $response["success"] = 0; 
            $response["message"] = "invalid username or password "; 
            echo json_encode($response);
        } 
    } else{ 
        $response["success"] = 0;
        $response["message"] = " One or both of the fields are empty "; 
        echo json_encode($response);
    }
    mysqli_close($con);     
?>

1 个答案:

答案 0 :(得分:0)

尝试计算查询结果计数。如果记录存在,则计数为1,否则为零。

        return NonDisclosure.objects.filter(user__user=self.request.user)