【问题标题】:NUll pointer exception in asynktask in android [closed]android中异步任务中的NULL指针异常[关闭]
【发布时间】:2014-09-02 20:53:06
【问题描述】:

我正在做一个应用程序,我想在地图上显示手机位置 我成功地将纬度发送到服务器,但是当我尝试从服务器获取数据时,当我将其存储在 hashmap 中时,它显示空指针异常 我的代码是

package com.example.gpstracking;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Supervisornew extends Activity {
    EditText et;
    Button bt;
    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://dyandroidapps.netii.net/android_db/dy.php";

    // JSON Node names
    private static final String TAG_CONTACTS = "products";
    private static final String TAG_LAT = "lat";
    private static final String TAG_LNG = "lng";

    // contacts JSONArray
    // JSONArray contacts = null;
    JSONArray contacts = null;
    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.supervisor);
        et = (EditText) findViewById(R.id.et_supervisor);
        bt = (Button) findViewById(R.id.btn_supervisor);

    }

    public void track(View v) {
        // new LoadAllProducts().execute();
        new GetContacts().execute();
        // new RetrieveTask().execute();
    }

    private class GetContacts extends AsyncTask<Void, ArrayList<String>, Void> {

        /*
         * @Override protected void onPreExecute() { super.onPreExecute();
         * //Showing progress dialog pDialog = new
         * ProgressDialog(Supervisornew.this);
         * pDialog.setMessage("Please wait..."); pDialog.setCancelable(false);
         * pDialog.show();
         * 
         * }
         */

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
            System.out.print(jsonStr);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    contacts = jsonObj.getJSONArray(TAG_CONTACTS);

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String lat = c.getString(TAG_LAT);
                        String lng = c.getString(TAG_LNG);
                        Log.d("response", lat);
                        Log.d("response", lng);//here i m getting values in log

                        HashMap<String, String> map=new HashMap<String,String>();
                        map.put("lat",lat);
                        map.put("lng", lng);
                        contactList.add(map);// i am getting nullpointer excetion



                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }


            return null;
        }

         @Override protected void onPostExecute(Void result) {

}
    }
}

还告诉我在 onpost 执行中做什么以将 arraylist 转移到其他活动 提前致谢…………

【问题讨论】:

标签: android json


【解决方案1】:

您忘记创建contactList 的对象。您正在访问它的引用,这将导致NPE。您应该在 onCreate() 中创建对象,如下所示:

contactList = new ArrayList<HashMap<String, String>>();

【讨论】:

    【解决方案2】:

    在您的代码中首先初始化contactList,然后再使用它,即在onCreate()方法中添加这一行

    contactList = new ArrayList<HashMap<String, String>>();
    

    编辑

    要将arraylist 转移到其他活动,请参见How to pass ArrayList HashMap from one activity to another

    【讨论】:

    • 谢谢老板@shivam verma
    • 你能告诉我如何通过 onpostexecutemethod 将此数组列表传递给其他类以及如何单独检索数据。@Shivam Verma
    • @DEEPAKYADAV 看到这个帖子stackoverflow.com/questions/6355787/…
    • 再次感谢老板@shivam verma
    【解决方案3】:

    其他两个答案为您提供了 Null Pointer 的原因,因此,回答您问题的第二部分,即将 ArrayList 传递给另一个 Activity:

    使用 putExtra(String, Serializable) 在 Intent 中传递值,使用 getSerializableExtra(String) 方法检索数据。

    将ArrayList&lt;HashMap&lt;String, String&gt;&gt; 从活动 A 传递到活动 B

    Intent intent = new Intent(this, B.class);
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("key_name", "key_value");
    ArrayList<HashMap<String, String>> arl = new ArrayList<HashMap<String, String>>();
    arl.add(hm);
    intent.putExtra("arraylist", arl);
    startActivity(intent);
    

    在活动 B 中检索数据

    ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
    

    参考:How to send hashmap value to another activity using an intent

    【讨论】:

    • 谢谢它正在工作@Shivam Verma
    • 我们可以从arraylist中分别取值吗...?
    • 是的。当然。使用 arl.get(位置);这将返回给定位置的 HashMap。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多