致命异常:主要Android尝试调用虚拟方法' org.json.JSONArray a

时间:2016-06-29 19:31:20

标签: android listview

当我运行我的代码时显示消息很遗憾您的应用已关闭。这是在ProgressDialog解雇后开始发生的。

我认为这里的错误[Searchresult.java]

@Override
    protected void onPostExecute(Void args) {
        // Locate the listview in listview_main.xml

                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapter(Searchresult.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();

        }

这是我的日志猫

Shutting down VM
06-30 05:08:03.882 23680-23680/com.ali.test E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.ali.test, PID: 23680
                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
                                                                     at com.ali.test.Searchresult$DownloadJSON.onPostExecute(Searchresult.java:93)
                                                                     at com.ali.test.Searchresult$DownloadJSON.onPostExecute(Searchresult.java:54)
                                                                     at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                     at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                     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)
06-30 05:08:03.884 1768-2143/system_process W/ActivityManager:   Force finishing activity com.ali.test/.Searchresult

home.jave [主档案]

public class home extends AppCompatActivity {
    EditText search_txt;
    Button search_btn;
    String strbook;

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



    search_txt = (EditText) findViewById(R.id.editText);
    search_btn = (Button) findViewById(R.id.button);

   search_btn.setOnClickListener(listener);
   search_txt.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                    (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Perform action on key press
                search_btn.setOnClickListener(listener);
                return true;
            }
            return false;
        }
    });
}private OnClickListener listener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        strbook = search_txt.getText().toString();

        if (TextUtils.isEmpty(strbook))
        {
            search_txt.setError("Enter name");
        }
        else {
          Intent i = new Intent(home.this, Searchresult.class);

            startActivity(i);
        }
    }
};

}

ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();

public ListViewAdapter(Context context,
                       ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    data = arraylist;
    imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    // Declare Variables
    TextView rank;
    ImageView flag;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.list_item, parent, false);
    // Get the position
    resultp = data.get(position);

    // Locate the TextViews in listview_item.xml
    rank = (TextView) itemView.findViewById(R.id.rank);

    // Locate the ImageView in listview_item.xml
    flag = (ImageView) itemView.findViewById(R.id.flag);

    // Capture position and set results to the TextViews
    rank.setText(resultp.get(Searchresult.RANK));
    // Capture position and set results to the ImageView
    // Passes flag images URL into ImageLoader.class
    imageLoader.DisplayImage(resultp.get(Searchresult.FLAG), flag);
    // Capture ListView item click
   itemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Get the position
            resultp = data.get(position);
            Intent intent = new Intent(context,SingleItemView.class);
            // Pass all data rank
            intent.putExtra("rank", resultp.get(Searchresult.RANK));
            // Pass all data flag
            intent.putExtra("flag", resultp.get(Searchresult.FLAG));
            // Start SingleItemView Class
            context.startActivity(intent);

        }
    });
    return itemView;
}

}

searchresult.java

public class Searchresult extends AppCompatActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String FLAG = "flag";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    listview = (ListView) findViewById(R.id.list);
    // Get the view from listview_main.xml
    setContentView(R.layout.list_item);
    // Execute DownloadJSON AsyncTask
    new DownloadJSON().execute();
}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(Searchresult.this);
        // Set progressdialog title
       // mProgressDialog.setTitle("Android JSON Parse Tutorial");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("worldpopulation");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                map.put("rank", jsonobject.getString("rank"));
                map.put("flag", jsonobject.getString("flag"));
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the listview in listview_main.xml

                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapter(Searchresult.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();

        }


    }
}

1 个答案:

答案 0 :(得分:0)

确保返回的json是您期望的那个。所以在之前的状态,检查你确实有一个jsonobject,然后检查是否有一个带有预期名称的jsonarray,并查看模式。

您可以查看一下Retrofit库,它对于RESTful服务调用来说非常棒。 http://square.github.io/retrofit/

虽然学习曲线很小。