java NullPointerException:尝试在空对象引用上调用虚拟方法“org.json.JSONObject org.json.JSONArray.getJSONObject(int)”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38666708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
提问by Abhishek Rai
i want help in creating a php file for database to attach it to my server and use it for json parsing.also i dont know how to create a specific json relating to a php file. i just want to create an app to fetch text data from server. ** Any info on how to create a php n its json will be very helpful.**
我需要帮助为数据库创建一个 php 文件以将其附加到我的服务器并将其用于 json 解析。我也不知道如何创建与 php 文件相关的特定 json。我只想创建一个应用程序来从服务器获取文本数据。** 有关如何创建 php 及其 json 的任何信息都将非常有帮助。**
This is my MainActivity.javaclass
这是我的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 = "\n" +
"http://file-manager.000webhost.com/file-manager/index.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 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);
}
}
This is my ParserJson.javaclass
这是我的ParserJson.java类
public class ParseJSON extends ActionBarActivity implements View.OnClickListener{
private String myJSONString;
private static final String JSON_ARRAY ="result";
private static final String ID = "id";
private static final String USERNAME= "name";
private JSONArray users = null;
private int TRACK = 0;
private EditText editTextId;
private EditText editTextUserName;
private EditText editTextPassword;
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);
editTextUserName = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
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 =new JSONArray(JSON_ARRAY);
users = jsonObject.getJSONArray(JSON_ARRAY);
// JSONObject jsonObject =users.getJSONObject(0);
} 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));
editTextUserName.setText(jsonObject.getString(USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
if(v == btnNext){
moveNext();
}
if(v == btnPrev){
movePrev();
}
}
}
This is my php file stored in public html folder of file manager.i also dont know where to store this file which tells about my database. The name of my php file is mark42.phpbut it is saving as index.php.
这是我的 php 文件存储在文件管理器的公共 html 文件夹中。我也不知道在哪里存储这个文件,它告诉我我的数据库。我的 php 文件的名称是mark42.php但它保存为index.php。
<?php
define('HOST','mysql9.000webhost.com');
define('USER','**********');
define('PASS','******');
define('DB','a4023522_db');$con = mysqli_connect(HOST,USER,PASS,DB); $sql = "select * from mark42";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'name'=>$row[1]));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
This is my logcat error, app crashes when I press the parsejsonbutton.
这是我的 logcat 错误,当我按下parsejson按钮时应用程序崩溃。
FATAL EXCEPTION: main Process: test.nic.com.nicpro, PID: 6506
java.lang.RuntimeException: Unable to start activity ComponentInfo{test.nic.com.nicpro/test.nic.com.nicpro.ParseJSON}: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
at test.nic.com.nicpro.ParseJSON.showData(ParseJSON.java:94)
at test.nic.com.nicpro.ParseJSON.onCreate(ParseJSON.java:62)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)?
at android.app.ActivityThread.-wrap11(ActivityThread.java)?
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)?
at android.os.Handler.dispatchMessage(Handler.java:102)?
at android.os.Looper.loop(Looper.java:148)?
at android.app.ActivityThread.main(ActivityThread.java:5417)?
at java.lang.reflect.Method.invoke(Native Method)?
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)?
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)?
回答by Jeeter
JSONObject jsonObject = users.getJSONObject(TRACK)
is throwing a NullPointerException
. That means that your line:
正在扔一个NullPointerException
. 这意味着您的线路:
users = jsonObject.getJSONArray(JSON_ARRAY);
is setting users
to null
. Double check that the array actually exists in your object, and that you haven't accidentally used the wrong key
设置users
为null
. 仔细检查数组是否确实存在于您的对象中,并且您没有意外使用错误的键
回答by mkazin
You need to learn how to use the debugger.
您需要学习如何使用调试器。
Put a breakpoint on:
设置断点:
JSONObject jsonObject = new JSONObject(myJSONString);
Then run your program in debug mode.
然后在调试模式下运行你的程序。
When it stops on that line, hover your mouse on myJSONString and see what the value is. It's a safe bet it's not what you're expecting.
当它停在那条线上时,将鼠标悬停在 myJSONString 上并查看值是什么。可以肯定,这不是您所期望的。