在android中使用MyApplication类获取JSON数据

时间:2014-01-05 05:20:41

标签: java android json listview android-listview

我正在尝试将MyApplication类用于JSON数据


我在做什么 ::我在listview中显示了一系列元素,我从JSON检索了数据并填充到listview。我把它的快照放在我目前的下面。


enter image description here


我想做什么 ::

  • 假设我使用图中所示的checkbox检查了一些行,现在是 选中的元素我想将它们添加到MyApplication class global memory
  • 然后我想从Main全局内存中获取数据并将其显示出来 listview

ex ::如果我选择Carlbangalore当我点击Button时,我必须获得listview } CarlBangalore显示


我面临的问题 ::点击checkbox后选择Button所需元素后,我收到Log所示的日志错误

  • 注意 ::我不想使用此列表视图中的Intents向nextone发送数据,因为我正在尝试学习使用MyApplication class

MainActivity.java

    public class MainActivity extends Activity {
        // Declare Variables
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        Adapter adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String NAME = "rank";
        Button btn;

        StringBuilder result;

        MyApplication mapp;//get MyApplication reference

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.activity_main);

            mapp=MyApplication.getInstance();


            listview = (ListView) findViewById(R.id.listView_id);
            btn = (Button) findViewById(R.id.button1);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    result = new StringBuilder();
                    for (int i = 0; i < arraylist.size(); i++) {
                        if (adapter.mysparse.get(i) == true) {

                            result.append(arraylist.get(i).get(MainActivity.NAME));
                            result.append("\n");
                        }

                    }
                    Intent n = new Intent(MainActivity.this, DisplayActivity.class);
                    //n.putExtra("buffer", result.toString());
                    startActivity(n);
                }
            });

            // 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(MainActivity.this);
                // Set progressdialog title
                // mProgressDialog.setTitle("Fetching the information");
                // 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 = Parser
                        .getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");

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

                    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(MainActivity.NAME,
                                jsonobject.getString("Person_Name"));
                        Log.d("jsonobject", jsonobject.toString());
                        // 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) {
                // Pass the results into ListViewAdapter.java
                adapter = new Adapter(MainActivity.this, arraylist);

                mapp.setArrayListMapData(arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
    }

**Adapter.java**

public class Adapter extends BaseAdapter implements OnCheckedChangeListener {

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

    public Adapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        mysparse = new SparseBooleanArray(data.size());
    }

    @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 name;
        CheckBox chk;

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

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

        // Locate the TextViews in listview_item.xml
        name = (TextView) itemView.findViewById(R.id.title_textView_id);
        chk = (CheckBox) itemView.findViewById(R.id.checkBox1);

        // Capture position and set results to the TextViews
        name.setText(resultp.get(MainActivity.NAME));

        chk.setTag(position);
        chk.setChecked(mysparse.get(position, false));
        chk.setOnCheckedChangeListener(this);

        return itemView;
    }

    public boolean isChecked(int position) {
        return mysparse.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mysparse.put(position, isChecked);

    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        mysparse.put((Integer) buttonView.getTag(), isChecked);
    }
}

MyApplication.java

public class MyApplication extends Application{

    ArrayList<HashMap<String, String>> arraylist;

    public static MyApplication instance=null;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    public static MyApplication getInstance()
    {
        if(instance==null)
        {
            instance=new MyApplication();
        }
        return instance;
    }

    public void setArrayListMapData(ArrayList<HashMap<String, String>> setData)
    {
        arraylist=setData;
    }

    public ArrayList<HashMap<String, String>> getArrayListMapData()
    {
        return arraylist;

    }


}

Info.java

public class Info {

    String Name = null;

    boolean selected = false;

    public Info(String name, boolean selected) {
        super();
        this.Name = name;

        this.selected = selected;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        this.Name = name;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

}

DisplayActivity.java

public class DisplayActivity extends Activity {

    ListView lv;
    ArrayList<String> myList;
    String myName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        Intent n = getIntent();
        myName = n.getStringExtra("buffer");

        myList = new ArrayList<String>();

        lv = (ListView) findViewById(R.id.listViewData);

        myList.add(myName);

        ArrayAdapter<String> adapter=new ArrayAdapter<String>(DisplayActivity.this,R.layout.custom_single_list,R.id.textView1, myList);

        lv.setAdapter(adapter);

    }

}

日志::

01-05 10:33:33.213: D/jsonobject(409): {"Image_Name":"image.jpg","Person_Name":"salmanKhan","Sl_no":1}
01-05 10:33:33.213: D/jsonobject(409): {"Image_Name":"c92beeaf5ba50e65.jpg","Person_Name":"AmirKhan","Sl_no":2}
01-05 10:33:33.213: D/jsonobject(409): {"Image_Name":"f2d835b73945ded2.jpg","Person_Name":"carl","Sl_no":3}
01-05 10:33:33.232: D/jsonobject(409): {"Image_Name":"deafe45d368c64cf.jpg","Person_Name":"bangalore","Sl_no":4}
01-05 10:33:33.232: D/jsonobject(409): {"Image_Name":"cc542ecaf6d251bd.jpg","Person_Name":"bangalore","Sl_no":5}
01-05 10:33:33.232: D/jsonobject(409): {"Image_Name":"3de14abca184c2d5.jpg","Person_Name":"hi","Sl_no":6}
01-05 10:33:33.232: D/jsonobject(409): {"Image_Name":"f856d9b50d1f32b1.jpg","Person_Name":"SharuknKhan","Sl_no":7}
01-05 10:33:33.232: D/jsonobject(409): {"Image_Name":"246dd313ba3b4a39.jpg","Person_Name":"shimoga","Sl_no":8}
01-05 10:33:33.363: D/dalvikvm(409): GC_FOR_MALLOC freed 3240 objects / 214432 bytes in 115ms
01-05 10:33:33.363: D/jsonobject(409): {"Image_Name":"5e8821af90b717bc.jpg","Person_Name":"manoj","Sl_no":9}
01-05 10:33:33.363: D/jsonobject(409): {"Image_Name":"86e18539867de023.jpg","Person_Name":"SharuknKhan","Sl_no":10}
01-05 10:33:33.363: D/jsonobject(409): {"Image_Name":"f88b905101e94ef9.jpg","Person_Name":"mahesh","Sl_no":11}
01-05 10:33:33.363: D/jsonobject(409): {"Image_Name":"bd793b1f80e238cf.jpg","Person_Name":"suresh","Sl_no":12}
01-05 10:33:33.363: D/jsonobject(409): {"Image_Name":"0eb250bfd8646968.jpg","Person_Name":"suresh","Sl_no":13}
01-05 10:33:33.363: D/jsonobject(409): {"Image_Name":"270c6a4ef1adb6ed.jpg","Person_Name":"amitab","Sl_no":14}
01-05 10:33:33.363: D/jsonobject(409): {"Image_Name":"0d6605d2f1089b73.jpg","Person_Name":"delhi","Sl_no":15}
01-05 10:33:33.363: D/jsonobject(409): {"Image_Name":"fdba14f4f9d4b4b4.jpg","Person_Name":"hydrabad","Sl_no":16}
01-05 10:33:33.373: D/jsonobject(409): {"Image_Name":"04b372a92bb2ee74.jpg","Person_Name":"mysore","Sl_no":17}
01-05 10:33:33.373: D/jsonobject(409): {"Image_Name":"7ae2a4618c0cdbac.jpg","Person_Name":"name123","Sl_no":18}
01-05 10:33:36.973: D/dalvikvm(409): GC_EXTERNAL_ALLOC freed 1554 objects / 275032 bytes in 89ms
01-05 10:33:37.093: D/dalvikvm(409): GC_EXTERNAL_ALLOC freed 135 objects / 7920 bytes in 76ms
01-05 10:48:46.713: D/AndroidRuntime(409): Shutting down VM
01-05 10:48:46.713: W/dalvikvm(409): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-05 10:48:46.733: E/AndroidRuntime(409): FATAL EXCEPTION: main
01-05 10:48:46.733: E/AndroidRuntime(409): java.lang.NullPointerException
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.AbsListView.obtainView(AbsListView.java:1315)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.ListView.makeAndAddView(ListView.java:1727)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.ListView.fillDown(ListView.java:652)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.ListView.fillFromTop(ListView.java:709)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.ListView.layoutChildren(ListView.java:1580)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.AbsListView.onLayout(AbsListView.java:1147)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.view.View.layout(View.java:7035)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.view.View.layout(View.java:7035)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.view.View.layout(View.java:7035)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.view.View.layout(View.java:7035)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.view.View.layout(View.java:7035)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.os.Looper.loop(Looper.java:123)
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.app.ActivityThread.main(ActivityThread.java:4627)
01-05 10:48:46.733: E/AndroidRuntime(409):  at java.lang.reflect.Method.invokeNative(Native Method)
01-05 10:48:46.733: E/AndroidRuntime(409):  at java.lang.reflect.Method.invoke(Method.java:521)
01-05 10:48:46.733: E/AndroidRuntime(409):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-05 10:48:46.733: E/AndroidRuntime(409):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-05 10:48:46.733: E/AndroidRuntime(409):  at dalvik.system.NativeStart.main(Native Method)

{Edit-1 ---- On Raghunandan Answer}

MainActivity.java

public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    Adapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    ArrayList<String> arraylist2;
    static String NAME = "rank";
    Button btn;

    StringBuilder result;

    MyApplication mapp;//get MyApplication reference

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.activity_main);
        arraylist = new ArrayList<HashMap<String, String>>();
        arraylist2 = new ArrayList<String>();
        mapp=MyApplication.getInstance();


        listview = (ListView) findViewById(R.id.listView);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
             // Toast.makeText(MainActivity.this,"///"+arraylist.size(), 1000).show();
                result = new StringBuilder();
                for (int i = 0; i < arraylist.size(); i++) {
                    if (adapter.mysparse.get(i) == true) {

                        result.append(arraylist.get(i).get(MainActivity.NAME));
                        arraylist2.add(arraylist.get(i).get(MainActivity.NAME));
                        result.append("\n");
                    }

                }
                mapp.setArrayListMapData(arraylist2);
                Toast.makeText(MainActivity.this,result, 1000).show();
                Intent n = new Intent(MainActivity.this, DisplayActivity.class);
               // n.putExtra("buffer", arraylist2);
                startActivity(n);
            }
        });

        // 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(MainActivity.this);
            // Set progressdialog title
            // mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array

            try {
            // Retrieve JSON Objects from the given URL address
            String s = getData();
            jsonobject = new JSONObject(s);


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

                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(MainActivity.NAME,
                            jsonobject.getString("Person_Name"));
                    Log.d("jsonobject", jsonobject.toString());
                    // 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) {
            // Pass the results into ListViewAdapter.java
            adapter = new Adapter(MainActivity.this, arraylist);


            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }


        private String getData() {
            String _response = null;
            try
            {
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpGet request = new HttpGet("http://54.218.73.244:7004/DescriptionSortedPrice/");
            HttpResponse response = httpclient.execute(request);
            HttpEntity resEntity = response.getEntity();
             _response =EntityUtils.toString(resEntity);

            }
            catch(Exception e)
            {
                  e.printStackTrace();  
            }

            return _response;
        }

}

DisplayActivity.java

public class DisplayActivity extends Activity {

    ListView lv;
    ArrayList<String> myList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        MyApplication mapp=MyApplication.getInstance();
        myList = mapp.getArrayListMapData();

        lv = (ListView) findViewById(R.id.list);

        ArrayAdapter<String> adapter=new ArrayAdapter<String>(DisplayActivity.this,android.R.layout.simple_expandable_list_item_1, myList);

        lv.setAdapter(adapter);
    }

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

}

second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/transparent" >
    </ListView>

</LinearLayout>

Adapter.java

public class Adapter extends BaseAdapter implements OnCheckedChangeListener {

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

    public Adapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        mysparse = new SparseBooleanArray(data.size());
    }

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

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

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

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView name;
        CheckBox chk;

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

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

        // Locate the TextViews in listview_item.xml
        name = (TextView) itemView.findViewById(R.id.textView1);
        chk = (CheckBox) itemView.findViewById(R.id.checkBox1);

        // Capture position and set results to the TextViews
        name.setText(resultp.get(MainActivity.NAME));

        chk.setTag(position);
        chk.setChecked(mysparse.get(position, false));
        chk.setOnCheckedChangeListener(this);

        return itemView;
    }

    public boolean isChecked(int position) {
        return mysparse.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mysparse.put(position, isChecked);

    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        mysparse.put((Integer) buttonView.getTag(), isChecked);
    }
}

日志::

01-05 12:27:00.763: E/AndroidRuntime(696): FATAL EXCEPTION: main
01-05 12:27:00.763: E/AndroidRuntime(696): java.lang.NullPointerException
01-05 12:27:00.763: E/AndroidRuntime(696):  at com.example.singleitemlistview.Adapter.getView(Adapter.java:64)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.AbsListView.obtainView(AbsListView.java:1315)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.ListView.onMeasure(ListView.java:1109)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.View.measure(View.java:8171)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.RelativeLayout.measureChild(RelativeLayout.java:563)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:378)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.View.measure(View.java:8171)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.View.measure(View.java:8171)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.View.measure(View.java:8171)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.View.measure(View.java:8171)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.os.Looper.loop(Looper.java:123)
01-05 12:27:00.763: E/AndroidRuntime(696):  at android.app.ActivityThread.main(ActivityThread.java:4627)
01-05 12:27:00.763: E/AndroidRuntime(696):  at java.lang.reflect.Method.invokeNative(Native Method)
01-05 12:27:00.763: E/AndroidRuntime(696):  at java.lang.reflect.Method.invoke(Method.java:521)
01-05 12:27:00.763: E/AndroidRuntime(696):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-05 12:27:00.763: E/AndroidRuntime(696):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-05 12:27:00.763: E/AndroidRuntime(696):  at dalvik.system.NativeStart.main(Native Method)
01-05 12:32:00.805: I/Process(696): Sending signal. PID: 696 SIG: 9

1 个答案:

答案 0 :(得分:2)

点击

  Intent n = new Intent(MainActivity.this, DisplayActivity.class);
  //n.putExtra("buffer", result.toString()); // is commented

然后

  Intent n = getIntent();
  myName = n.getStringExtra("buffer");

有一个列表视图DisplayActivity。它需要填充数据。您评论了intent.puExtraCode

01-05 10:48:46.733: E/AndroidRuntime(409): java.lang.NullPointerException
01-05 10:48:46.733: E/AndroidRuntime(409):  at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)

另请参阅ArrayAdapter 2.2 rev1

的源代码
326    private View createViewFromResource(int position, View convertView, ViewGroup parent,
327            int resource) {
328        View view;
329        TextView text;
330
331        if (convertView == null) {
332            view = mInflater.inflate(resource, parent, false);
333        } else {
334            view = convertView;
335        }
336
337        try {
338            if (mFieldId == 0) {
339                //  If no custom field is assigned, assume the whole resource is a TextView
340                text = (TextView) view;
341            } else {
342                //  Otherwise, find the TextView field within the layout
343                text = (TextView) view.findViewById(mFieldId);
344            }
345        } catch (ClassCastException e) {
346            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
347            throw new IllegalStateException(
348                    "ArrayAdapter requires the resource ID to be a TextView", e);
349        }
350
351        T item = getItem(position);
352        if (item instanceof CharSequence) {
353            text.setText((CharSequence)item);
354        } else {
355            text.setText(item.toString()); // text is null
356        }
357
358        return view;
359    }

第355行

 355            text.setText(item.toString()); // text is null

指示适配器中的textview为空。

在这种情况下你应该看看

 ArrayAdapter<String> adapter=new ArrayAdapter<String>(DisplayActivity.this,R.layout.custom_single_list,R.id.textView1, myList);

所以我建议进行以下更改

public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    Adapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    ArrayList<String> arraylist2;
    static String NAME = "rank";
    Button btn;

    StringBuilder result;

    MyApplication mapp;//get MyApplication reference

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.activity_main);
        arraylist = new ArrayList<HashMap<String, String>>();
        arraylist2 = new ArrayList<String>();
        mapp=MyApplication.getInstance();


        listview = (ListView) findViewById(R.id.listView);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
             // Toast.makeText(MainActivity.this,"///"+arraylist.size(), 1000).show();
                result = new StringBuilder();
                for (int i = 0; i < arraylist.size(); i++) {
                    if (adapter.mysparse.get(i) == true) {

                        result.append(arraylist.get(i).get(MainActivity.NAME));
                        arraylist2.add(arraylist.get(i).get(MainActivity.NAME));
                        result.append("\n");
                    }

                }
                mapp.setArrayListMapData(arraylist2);
                Toast.makeText(MainActivity.this,result, 1000).show();
                Intent n = new Intent(MainActivity.this, DisplayActivity.class);
               // n.putExtra("buffer", arraylist2);
                startActivity(n);
            }
        });

        // 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(MainActivity.this);
            // Set progressdialog title
            // mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array

            try {
            // Retrieve JSON Objects from the given URL address
            String s = getData();
            jsonobject = new JSONObject(s);


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

                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(MainActivity.NAME,
                            jsonobject.getString("Person_Name"));
                    Log.d("jsonobject", jsonobject.toString());
                    // 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) {
            // Pass the results into ListViewAdapter.java
            adapter = new Adapter(MainActivity.this, arraylist);


            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }


        private String getData() {
            String _response = null;
            try
            {
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpGet request = new HttpGet("http://54.218.73.244:7004/DescriptionSortedPrice/");
            HttpResponse response = httpclient.execute(request);
            HttpEntity resEntity = response.getEntity();
             _response =EntityUtils.toString(resEntity);

            }
            catch(Exception e)
            {
                  e.printStackTrace();  
            }

            return _response;
        }
        public class Adapter extends BaseAdapter implements OnCheckedChangeListener {

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

            public Adapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
                this.context = context;
                data = arraylist;
                mysparse = new SparseBooleanArray(data.size());
            }

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

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

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

            public View getView(final int position, View convertView, ViewGroup parent) {
                // Declare Variables
                TextView name;
                CheckBox chk;

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

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

                // Locate the TextViews in listview_item.xml
                name = (TextView) itemView.findViewById(R.id.textView1);
                chk = (CheckBox) itemView.findViewById(R.id.checkBox1);

                // Capture position and set results to the TextViews
                name.setText(resultp.get(MainActivity.NAME));

                chk.setTag(position);
                chk.setChecked(mysparse.get(position, false));
                chk.setOnCheckedChangeListener(this);

                return itemView;
            }

            public boolean isChecked(int position) {
                return mysparse.get(position, false);
            }

            public void setChecked(int position, boolean isChecked) {
                mysparse.put(position, isChecked);

            }

            public void toggle(int position) {
                setChecked(position, !isChecked(position));

            }

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                mysparse.put((Integer) buttonView.getTag(), isChecked);
            }
        }
    }

MyApplication类

public class MyApplication extends Application{

    ArrayList<String> arraylist;

    public static MyApplication instance=null;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    public static MyApplication getInstance()
    {
        if(instance==null)
        {
            instance=new MyApplication();
        }
        return instance;
    }

    public void setArrayListMapData(ArrayList<String> setData)
    {
        arraylist=setData;
    }

    public ArrayList<String> getArrayListMapData()
    {
        return arraylist;

    }

}

DisplayActivity

public class DisplayActivity extends Activity {

    ListView lv;
    ArrayList<String> myList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);

        MyApplication mapp=MyApplication.getInstance();
        myList = mapp.getArrayListMapData();

        lv = (ListView) findViewById(R.id.listView1);

        ArrayAdapter<String> adapter=new ArrayAdapter<String>(DisplayActivity.this,android.R.layout.simple_expandable_list_item_1, myList);

        lv.setAdapter(adapter);
    }

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

}

enter image description here

enter image description here

使用ViewHolder模式是一个不错的选择