【问题标题】:Android - Error parsing data org.json.jsonexception end of input at character 0Android - 在字符 0 处解析数据 org.json.jsonexception 输入时出错
【发布时间】:2014-08-17 13:15:22
【问题描述】:

我整天都在查看我的代码,但找不到发生这种情况的原因。数据是在数据库中输入的,但是当我提交新数据时,android应用程序总是崩溃。

这里注册.java

public class Register extends Activity implements OnClickListener{

private EditText nama, alamat, noidentitas, notelepon, username, password;
private Button  rgister, bktlogin;


 // Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

private static final String LOGIN_URL = "http://192.168.43.226/jualan/login/register.php";


//ids
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);

    nama = (EditText)findViewById(R.id.et_nama);
    alamat = (EditText)findViewById(R.id.et_alamat);
    noidentitas = (EditText)findViewById(R.id.et_noidentitas);
    notelepon = (EditText)findViewById(R.id.et_notelepon);
    username = (EditText)findViewById(R.id.et_username);
    password = (EditText)findViewById(R.id.et_password);


    rgister = (Button)findViewById(R.id.bt_register);
    rgister.setOnClickListener(this);
    bktlogin = (Button)findViewById(R.id.bktologin);
    bktlogin.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bt_register:
            new CreateUser().execute();

        break;
    case R.id.bktologin:
            Intent ii = new Intent(this, Login.class);
            startActivity(ii);
        break;

    default:
        break;
    }
}

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

     /**
     * Before starting background thread Show Progress Dialog
     * */
    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) {
        // TODO Auto-generated method stub
         // Check for success tag
        int success;
        String nm = nama.getText().toString();
        String almt = alamat.getText().toString();
        String noid = noidentitas.getText().toString();
        String notelp = notelepon.getText().toString();            
        String user = username.getText().toString();
        String pass = password.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("nama", nm));
            params.add(new BasicNameValuePair("alamat", almt));
            params.add(new BasicNameValuePair("noidentitas", noid));
            params.add(new BasicNameValuePair("notelepon", notelp));
            params.add(new BasicNameValuePair("username", user));
            params.add(new BasicNameValuePair("password", pass));

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

            //Posting user data to script 
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);

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

            // json success element
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("User Created!", json.toString());       
                //Intent i = new Intent(Register.this, Login.class);
                //startActivity(i);
                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;

    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    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 = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is 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"){
            // request method is 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 parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

这里是我的 php 代码 register.php

<?php
include('connection.php');

$id = (int)$_POST['id'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$noidentitas = (int)$_POST['noidentitas'];
$notelepon  = (int)$_POST['notelepon'];
$username = $_POST['username'];
$password = $_POST['password'];

$query = 'insert into akun (nama, alamat, noidentitas, notelepon, username, password) values ("'.$nama.'", "'.$alamat.'", "'.$noidentitas.'", "'.$notelepon.'", "'.$username.'", "'.$password.'")';
if($id > 0){
$query = 'update akun set nama = "'.$nama.'", alamat = "'.$alamat.'", noidentitas = "'.$noidentitas.'", notelepon = "'.$notelepon.'", username = "'.$username.'", password = "'.$password.'" where id = '.$id;
$result=mysql_query($query);
}
mysql_query($query) or die(mysql_error());

?>

而logcat的输出是

08-17 20:13:06.215: E/JSON Parser(28309): Error parsing data org.json.JSONException: End of input at character 0 of 
08-17 20:13:06.215: W/dalvikvm(28309): threadid=11: thread exiting with uncaught exception (group=0x4118a2a0)
08-17 20:13:06.215: E/AndroidRuntime(28309): FATAL EXCEPTION: AsyncTask #1
08-17 20:13:06.215: E/AndroidRuntime(28309): java.lang.RuntimeException: An error occured while executing doInBackground()
08-17 20:13:06.215: E/AndroidRuntime(28309):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at java.lang.Thread.run(Thread.java:856)
08-17 20:13:06.215: E/AndroidRuntime(28309): Caused by: java.lang.NullPointerException
08-17 20:13:06.215: E/AndroidRuntime(28309):    at akun.Register$CreateUser.doInBackground(Register.java:143)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at akun.Register$CreateUser.doInBackground(Register.java:1)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-17 20:13:06.215: E/AndroidRuntime(28309):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-17 20:13:06.215: E/AndroidRuntime(28309):    ... 5 more

【问题讨论】:

  • 你能发布你的示例 json 数据吗
  • register.php 没有返回任何json...那它怎么解析呢?
  • 在我在你的doInBackground 方法中进一步String nm = nama.getText().toString(); 之前......你不能这样做。不要在doInBackgroundAsyncTask 中触摸主/UI 线程中的任何内容。该方法在不同的线程上运行。使用onPreExecute()(在主/UI线程上运行)来获取您需要的值。然后重新考虑并重试您的代码。我怀疑在logcat中显示了更多您没有显示的错误。
  • 我是使用 json 的新手,我认为当数据输入到数据库时就完成了。你能告诉我如何在我的 php 代码上解析 json 吗?
  • @Squonk 我认为这没关系。但我无法在我的 php.ini 中解析 json 数据。你能告诉我如何在我的 php 代码中解析 json 吗?感谢之前

标签: java php android mysql json


【解决方案1】:

在 register.php 中更改您的代码

     if($id > 0){
    $query = 'update akun set nama = "'.$nama.'", alamat = "'.$alamat.'", noidentitas = "'.$noidentitas.'", notelepon = "'.$notelepon.'", username = "'.$username.'", password = "'.$password.'" where id = '.$id;
    } else {
    $query = 'insert into akun (nama, alamat, noidentitas, notelepon, username, password) values ("'.$nama.'", "'.$alamat.'", "'.$noidentitas.'", "'.$notelepon.'", "'.$username.'", "'.$password.'")';
    }
    $result=mysql_query($query);   
   if ($result) {     // This validates if Query was successful
 echo  '{"success":1,
          "message":"Registered Successfully"}';

} else {
echo  '{"success":2,
          "message":"Registration failed"}';

}

如果您尝试从 url 获取 json 响应,则不要使用 die mysql 错误。 json 响应必须包含有效的 json 内容。

【讨论】:

  • 非常感谢 Indra,它现在正在工作。我非常非常感谢你。我很抱歉,因为我不明白 json 解析数据。
猜你喜欢
  • 2014-07-11
  • 2014-06-03
  • 2013-08-20
  • 1970-01-01
  • 2017-08-01
  • 2013-02-27
  • 1970-01-01
相关资源
最近更新 更多