【问题标题】:JSON Parsing error at the runtime运行时 JSON 解析错误
【发布时间】:2018-03-08 01:28:39
【问题描述】:

我是学生,我正在学习 android,出现以下错误,我无法找到该错误的解决方案,请帮助我解决该错误。谢谢...

java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.sumit.json1/com.sumit.json1.ParseJSON}: 
java.lang.NullPointerException: Attempt to invoke virtual method 
'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object 
reference.

没有连接到数据库的问题。我的 php 代码 托管在 hosts.in

<?
//these are the server details
//the username is root by default in case of xampp
//password is nothing by default
//and lastly we have the database named android. if your database name is 
different you have to change it 
$servername = "mysql.hostinger.in";
$username = "username";
$password = "*********";
$database = "database_name";


//creating a new connection object using mysqli 
$conn = new mysqli($servername, $username, $password, $database);

//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message 
causing the error 
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

//if everything is fine

//creating an array for storing the data 
$heroes = array(); 

//this is our sql query 
$sql = "SELECT id, name, email, username, password, gender, lat, lon FROM 
appusers;";

//creating an statment with the query
$stmt = $conn->prepare($sql);

//executing that statment
$stmt->execute();

//binding results for that statment 
$stmt->bind_result($id, $name, $email, $username, $password, $gender, $lat, 
$lon);

//looping through all the records
while($stmt->fetch()){

//pushing fetched data in an array 
$temp = [
'id'=>$id,
'name'=>$name,
'email'=>$email,
'username'=>$username,
'password'=>$password,
'gender'=>$gender,
'lat'=>$lat,
'lon'=>$lon
 ];

 //pushing the array inside the hero array 
 array_push($heroes, $temp);
}

//displaying the data in json format 
echo json_encode($heroes);

为了解析 json,我的 android 代码是 ParseJSON.java

public class ParseJSON extends ActionBarActivity implements 
 View.OnClickListener{

private String myJSONString;

private static final String JSON_ARRAY ="heroes";
private static final String ID = "id";
private static final String NAME= "name";
private static final String EMAIL = "email";
private static final String USERNAME= "username";
private static final String PASSWORD = "password";
private static final String GENDER = "gender";
private static final String LAT = "lat";
private static final String LON = "lon";

private JSONArray users = null;

private int TRACK = 0;

private EditText editTextId;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextUserName;
private EditText editTextPassword;
private EditText editTextGender;
private EditText editTextLat;
private EditText editTextLon;

Button btnPrev;
Button btnNext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_parse_json);

    Intent intent = getIntent();
    myJSONString = intent.getStringExtra(MainActivity.MY_JSON);


    editTextId = (EditText) findViewById(R.id.editTextID);
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextUserName = (EditText) findViewById(R.id.editTextUsername);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    editTextGender = (EditText) findViewById(R.id.editTextGender);
    editTextLat = (EditText) findViewById(R.id.editTextLat);
    editTextLon = (EditText) findViewById(R.id.editTextLon);

    btnPrev = (Button) findViewById(R.id.buttonPrev);
    btnNext = (Button) findViewById(R.id.buttonNext);

    btnPrev.setOnClickListener(this);
    btnNext.setOnClickListener(this);

    extractJSON();

    showData();
}



private void extractJSON(){
    try {
        JSONObject jsonObject = new JSONObject(myJSONString);
        users = jsonObject.getJSONArray(JSON_ARRAY);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private void moveNext(){
    if(TRACK<users.length()){
        TRACK++;
    }
    showData();
}

private void movePrev(){
    if(TRACK>0){
        TRACK--;
    }
    showData();
}

private void showData(){
    try {
        JSONObject jsonObject = users.getJSONObject(TRACK);

        editTextId.setText(jsonObject.getString(ID));
        editTextName.setText(jsonObject.getString(NAME));
        editTextEmail.setText(jsonObject.getString(EMAIL));
        editTextUserName.setText(jsonObject.getString(USERNAME));
        editTextPassword.setText(jsonObject.getString(PASSWORD));
        editTextGender.setText(jsonObject.getString(GENDER));
        editTextLat.setText(jsonObject.getString(LAT));
        editTextLon.setText(jsonObject.getString(LON));
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_parse_json, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    if(v == btnNext){
        moveNext();
    }
    if(v == btnPrev){
        movePrev();
    }
}
}

在我的 android 项目中 MainActivity.java 如果有任何错误请帮我解决

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

private TextView textViewJSON;
private Button buttonGet;
private Button buttonParse;

public static final String MY_JSON ="MY_JSON";

private static final String JSON_URL = "http://mydatabasedb.16mb.com/JSON1/send-data1.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textViewJSON = (TextView) findViewById(R.id.textViewJSON);
    textViewJSON.setMovementMethod(new ScrollingMovementMethod());
    buttonGet = (Button) findViewById(R.id.buttonGet);
    buttonParse = (Button) findViewById(R.id.buttonParse);
    buttonGet.setOnClickListener(this);
    buttonParse.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    if(v==buttonGet){
        getJSON(JSON_URL);
    }

    if(v==buttonParse){
        showParseActivity();
    }
}

private void showParseActivity() {
    Intent intent = new Intent(this, ParseJSON.class);
    intent.putExtra(MY_JSON,textViewJSON.getText().toString());
    startActivity(intent);
}


private void getJSON(String url) {
    class GetJSON extends AsyncTask<String, Void, String>{
        ProgressDialog loading;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(MainActivity.this, "Please Wait...",null,true,true);
        }

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

            String uri = params[0];

            BufferedReader bufferedReader = null;
            try {
                URL url = new URL(uri);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();

                bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                String json;
                while((json = bufferedReader.readLine())!= null){
                        sb.append(json+"\n");
                }

                return sb.toString().trim();

            }catch(Exception e){
                return null;
            }

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            textViewJSON.setText(s);
        }
    }
    GetJSON gj = new GetJSON();
    gj.execute(url);
}
}

【问题讨论】:

  • users = jsonObject.getJSONArray(JSON_ARRAY);
  • 在上面一行我得到了错误

标签: java php android arrays json


【解决方案1】:
users = jsonObject.getJSONArray(JSON_ARRAY);

这会尝试在“heroes”键处解析一个列表,但 JSON 文档中没有“heroes”键。您正在编码一个列表,而不是一个对象。

在浏览器中打开返回 JSON 的 URL,问题应该很明显了。

【讨论】:

  • 先生需要对代码进行哪些更改??你能帮我编辑上面的代码吗,因为这是我的第一个 json 应用程序,所以我没有那么多知识。谢谢...
  • 你必须让 PHP 和 Java 在 JSON 模型上达成一致。由于我不知道哪个应该是正确的,所以我无法告诉您要更改什么。此外,该站点不存在,因此我们为您编写代码。
  • [link]mydatabasedb.16mb.com/JSON1/send-data1.php这是我的json输出字符串
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
相关资源
最近更新 更多