【问题标题】:Android: cannot insert data in MYSQLAndroid:无法在 MYSQL 中插入数据
【发布时间】:2014-10-29 13:53:16
【问题描述】:

我正在从网站上尝试这个例子。我在 MYSQL 中插入数据。我面临的问题是,当我输入数据并按下确定按钮时,我的应用程序在几秒钟后崩溃并且没有数据插入到数据库中。我正在使用模拟器。这是我的代码。

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 LOGIN_URL = "http://10.0.2.2:8080/allevents/username.php";


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.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) {
    // TODO Auto-generated method stub

    new CreateUser().execute();

}

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


    boolean failure = false;

    @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 {
            // Building Parameters
            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("User Created!", json.toString());
                finish();
                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) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_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());
    }


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


    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());
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }


    return jObj;

}

我的 PHP 文件是

<?php
$response = array();


if (isset($_POST['username']) && isset($_POST['password'])) {


$username = $_POST['username'];
$password = $_POST['password'];




// include db connect class
require_once __DIR__ . '/db_connect.php';


$db = new DB_CONNECT();


$result = mysql_query("INSERT INTO users(Username,Password) VALUES('$username', '$password')");
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Operation successfull";
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    echo json_encode($response);
}
} else {

$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
</body>
</html>

我的 logcat 的屏幕截图 http://i57.tinypic.com/4exk8.png

【问题讨论】:

  • 查看 LogCat 和服务器日志文件以了解发生了什么。
  • “我的应用程序在几秒钟后崩溃”定义“崩溃”。你的 logcat 显示了什么?
  • 崩溃 -> 应用程序已停止工作
  • :) 我在询问错误日志。从您的 Logcat 复制消息。
  • 我尝试复制我的 logcat,但是当我保存 logcat 时它给了我空文件这里是 logcat i57.tinypic.com/4exk8.png的屏幕截图

标签: php android mysql crash


【解决方案1】:

尝试从 doInBackground 方法中删除这段代码片段并将其放入 onPostExecute() 中。

    Log.d("Login 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("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

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

【讨论】:

    【解决方案2】:

    您无法获取 editTexts 用户并传入您的 AsyncTask doInBackground()。 在您的活动中将它们作为 .execute() 的参数提供给它 (注意:在您的 OnClickListener 中,您必须从头开始获取它们!):

    String[]  myparams = 
    {
        ((EditText)findViewById(R.id.username)).getText().toString(),
        ((EditText)findViewById(R.id.password)).getText().toString()
    };
    new CreateUser().execute(myparams);
    

    现在您可以在 AsyncTask 中提取它们:

    protected String doInBackground(String... pParams)
    {
        String username = pParams[0];
        String password= pParams[1];
    
        //Do what you like.
    }
    

    我认为这就是您的日志屏幕截图中出现 NullPointerException 的原因。 ;)

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 2020-01-10
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多