Php 错误,我的应用程序每次将数据从应用程序传输到数据库时停止,反之亦然

Php 错误,我的应用程序每次将数据从应用程序传输到数据库时停止,反之亦然,php,android,Php,Android,这是我的一些代码。日志中的错误。提前谢谢 错误: 原因:java.lang.nullpointerexception:尝试对空对象引用调用虚拟方法“java.lang.string.org.json.jsonobject.tostring()” Login.java public class Login extends Activity implements OnClickListener { private EditText user, pass; private Button mSubmi

这是我的一些代码。日志中的错误。提前谢谢

错误: 原因:java.lang.nullpointerexception:尝试对空对象引用调用虚拟方法“java.lang.string.org.json.jsonobject.tostring()”

Login.java

public class Login extends Activity implements OnClickListener {

private EditText user, pass;
private Button mSubmit, mRegister;


private ProgressDialog pDialog;


JSONParser jsonParser = new JSONParser();




private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    // setup input fields
    user = (EditText) findViewById(R.id.username);
    pass = (EditText) findViewById(R.id.password);

    // setup buttons
    mSubmit = (Button) findViewById(R.id.login);
    mRegister = (Button) findViewById(R.id.register);

    // register listeners
    mSubmit.setOnClickListener(this);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    int id = v.getId();
    if (id == R.id.login) {
        new AttemptLogin().execute();
    } else if (id == R.id.register) {
        Intent i = new Intent(this, Register.class);
        startActivity(i);
    } else {
    }
}

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

    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {

        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");

            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);


            Log.d("Login attempt", json.toString());


            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());

                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(Login.this);
                Editor edit = sp.edit();
                edit.putString("username", username);
                edit.commit();

                Intent i = new Intent(Login.this, ReadComments.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    protected void onPostExecute(String file_url) {

        pDialog.dismiss();
        if (file_url != null) {
            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}
公共类登录扩展活动实现OnClickListener{
私人编辑文本用户,通过;
私人按钮mSubmit,mRegister;
私人对话;
JSONParser JSONParser=新的JSONParser();
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记_MESSAGE=“MESSAGE”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//设置输入字段
user=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
//设置按钮
mSubmit=(按钮)findviewbyd(R.id.login);
mRegister=(按钮)findviewbyd(R.id.register);
//注册侦听器
mSubmit.setOnClickListener(这个);
mRegister.setOnClickListener(此);
}
@凌驾
公共void onClick(视图v){
int id=v.getId();
if(id==R.id.login){
新建AttemptLogin().execute();
}else if(id==R.id.register){
意图i=新意图(这是Register.class);
星触觉(i);
}否则{
}
}
类AttemptLogin扩展了AsyncTask{
布尔失败=假;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(Login.this);
setMessage(“正在尝试登录…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…args){
成功;
字符串username=user.getText().toString();
字符串密码=pass.getText().toString();
试一试{
List params=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户名));
添加(新的BasicNameValuePair(“密码”,password));
Log.d(“请求!”,“启动”);
JSONObject json=jsonParser.makeHttpRequest(登录地址,“POST”,
参数);
Log.d(“登录尝试”,json.toString());
success=json.getInt(TAG_success);
如果(成功==1){
Log.d(“登录成功!”,json.toString();
SharedReferences sp=首选项管理器
.getDefaultSharedReferences(Login.this);
Editor edit=sp.edit();
edit.putString(“用户名”,用户名);
edit.commit();
意图i=新意图(Login.this、ReadComments.class);
完成();
星触觉(i);
返回json.getString(TAG_消息);
}否则{
Log.d(“登录失败!”,json.getString(TAG_MESSAGE));
返回json.getString(TAG_消息);
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
受保护的void onPostExecute(字符串文件\u url){
pDialog.disclose();
如果(文件url!=null){
Toast.makeText(Login.this,file_url,Toast.LENGTH_LONG.show();
}
}
}
}

Register.java

public class Register extends Activity implements OnClickListener{

private EditText user, pass;
private Button  mRegister;


private ProgressDialog pDialog;


JSONParser jsonParser = new JSONParser();





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.register);

    user = (EditText)findViewById(R.id.username);
    pass = (EditText)findViewById(R.id.password);


    mRegister = (Button)findViewById(R.id.register);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {


            new CreateUser().execute();

}

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


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setMessage("Creating User...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {

        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");


            JSONObject json = jsonParser.makeHttpRequest(
                   REGISTER_URL, "POST", params);


            Log.d("Registering attempt", json.toString());


            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("User Created!", json.toString());                
                finish();
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}
公共类寄存器扩展活动实现OnClickListener{
私人编辑文本用户,通过;
私人按钮注册器;
私人对话;
JSONParser JSONParser=新的JSONParser();
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记_MESSAGE=“MESSAGE”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
mRegister=(按钮)findviewbyd(R.id.register);
mRegister.setOnClickListener(此);
}
@凌驾
公共void onClick(视图v){
新建CreateUser().execute();
}
类CreateUser扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(Register.this);
setMessage(“正在创建用户…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…args){
成功;
字符串username=user.getText().toString();
字符串密码=pass.getText().toString();
试一试{
List params=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户名));
添加(新的BasicNameValuePair(“密码”,password));
Log.d(“请求!”,“启动”);
JSONObject json=jsonParser.makeHttpRequest(
注册URL,“POST”,参数);
Log.d(“注册尝试”,json.toString());
success=json.getInt(TAG_success);
如果(成功==1){
Log.d(“用户创建的!”,json.toString());
完成();
返回json.getString(TAG_消息);
}否则{
Log.d(“注册失败!”,json.getString(TAG_MESSAGE));
返回json.getString(TAG_消息);
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
受保护的void onPostExecute(字符串文件\u url){
//删除产品后关闭对话框
pDialog.disclose();
如果(文件url!=null){
Toast.makeText(Register.this,file_url,Toast.LENGTH_LONG.show();
}
}
}
}

JSONParser.java

public class JSONParser {

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


public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {


    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);


        HttpResponse httpResponse = httpClient.execute(httpPost);

        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());
        Log.e("log_tag", "Failed data was:\n" + json);
    }


    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        Log.e("log_tag", "Failed data was:\n" + json);
    }


    return jObj;

}

public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {


    try {


        if(method == "POST"){

            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"){

            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());
        Log.e("log_tag", "Failed data was:\n" + json);
    }


    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        Log.e("log_tag", "Failed data was:\n" + json);
    }


    return jObj;

}
公共类JSONParser{
静态输入
<?php


   require("config.inc.php");

   if (!empty($_POST)) {

$query = " 
        SELECT 
            id, 
            username, 
            password
        FROM users 
        WHERE 
            username = :username 
    ";

$query_params = array(
    ':username' => $_POST['username']
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));

}



$validated_info = false;


$row = $stmt->fetch();
if ($row) {


    if ($_POST['password'] === $row['password']) {
        $login_ok = true;
    }
}


if ($login_ok) {
    $response["success"] = 1;
    $response["message"] = "Login successful!";
    die(json_encode($response));
} else {
    $response["success"] = 0;
    $response["message"] = "Invalid Credentials!";
    die(json_encode($response));
 }
 } else {
 ?>
    <h1>Login</h1> 
    <form action="login.php" method="post"> 
        Username:<br /> 
        <input type="text" name="username" placeholder="username" /> 
        <br /><br /> 
        Password:<br /> 
        <input type="password" name="password" placeholder="password"      value="" /> 
        <br /><br /> 
        <input type="submit" value="Login" /> 
    </form> 
    <a href="register.php">Register</a>
<?php
 }

?> 
 require("config.inc.php");


  if (!empty($_POST)) {

if (empty($_POST['username']) || empty($_POST['password'])) {



    $response["success"] = 0;
    $response["message"] = "Please Enter Both a Username and Password.";


    die(json_encode($response));
}



$query        = " SELECT 1 FROM users WHERE username = :user";

$query_params = array(
    ':user' => $_POST['username']
);


try {

    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {



    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));
}


$row = $stmt->fetch();
if ($row) {

    $response["success"] = 0;
    $response["message"] = "I'm sorry, this username is already in use";
    die(json_encode($response));
}


$query = "INSERT INTO users ( username, password ) VALUES ( :user, :pass ) ";


$query_params = array(
    ':user' => $_POST['username'],
    ':pass' => $_POST['password']
);


try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

    $response["success"] = 0;
    $response["message"] = "Database Error2. Please Try Again!";
    die(json_encode($response));
}


$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);




} else {
?>
<h1>Register</h1> 
<form action="register.php" method="post"> 
    Username:<br /> 
    <input type="text" name="username" value="" /> 
    <br /><br /> 
    Password:<br /> 
    <input type="password" name="password" value="" /> 
    <br /><br /> 
    <input type="submit" value="Register New User" /> 
 </form>
  <?php
   }

   ?>