在Android的使用MyApplication的类JSON数据 [英] Using MyApplication class in android for JSON data
问题描述
我想使用所有MyApplication类JSON数据
我在做什么 ::我在列表视图
显示元素的列表,我从检索到的数据JSON
并填充到列表视图
。我已经把它的快照低于我在present。
我所试图做的:
- 假设我检查使用
复选框中的某些行如图
,现在
选定的元素我想将它们添加到MyApplication的类
这是
一个全局内存
。 - 然后,我想从全球主要内存中的数据并显示它
在列表视图
前的 ::如果我选择了卡尔
和班加罗尔
当我点击按钮
我得卡尔的
和列表视图
班加罗尔
显示
我现在面临的问题是什么 ::选择复选框
所需的元素后,当我点击按钮
我得到的错误日志中所示登录
- 注意 ::我不想从这个列表视图利用发送意图数据nextone,因为我想学习使用
MyApplication的类
MainActivity.java
公共类MainActivity延伸活动{
//声明变量
的JSONObject的JSONObject;
JSONArray jsonarray;
ListView控件列表视图;
转接适配器;
ProgressDialog mProgressDialog;
ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;
静态字符串NAME =等级;
按钮BTN; StringBuilder的结果; 所有MyApplication MAPP; //获取所有MyApplication参考 @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
//从listview_main.xml视图
的setContentView(R.layout.activity_main); MAPP = MyApplication.getInstance();
列表视图=(ListView控件)findViewById(R.id.listView_id);
BTN =(按钮)findViewById(R.id.button1);
btn.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根 结果=新的StringBuilder();
的for(int i = 0; I< arraylist.size();我++){
如果(adapter.mysparse.get(我)==真){ result.append(arraylist.get(I)获得(MainActivity.NAME));
result.append(\\ n);
} }
意图N =新意图(MainActivity.this,DisplayActivity.class);
//n.putExtra(\"buffer,result.toString());
startActivity(N);
}
}); //执行DownloadJSON的AsyncTask
新DownloadJSON()执行();
} // DownloadJSON的AsyncTask
私有类DownloadJSON扩展的AsyncTask<太虚,太虚,太虚> { @覆盖
在preExecute保护无效(){
super.on preExecute();
//创建一个progressdialog
mProgressDialog =新ProgressDialog(MainActivity.this);
//设置progressdialog称号
// mProgressDialog.setTitle(读取信息);
//设置progressdialog消息
mProgressDialog.setMessage(正在加载...);
mProgressDialog.setIndeterminate(假);
//显示progressdialog
mProgressDialog.show();
} @覆盖
保护无效doInBackground(虚空...... PARAMS){
//创建一个数组
ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>(); //从给定的URL地址JSON对象
的JSONObject =分析器
.getJSONfromURL(http://54.218.73.244:7004/DescriptionSortedPrice/); 尝试{
//找到在JSON数组名
jsonarray = jsonobject.getJSONArray(餐馆); 的for(int i = 0; I< jsonarray.length();我++){
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
的JSONObject = jsonarray.getJSONObject(ⅰ);
// Retrive JSON对象
map.put(MainActivity.NAME,
jsonobject.getString(PERSON_NAME));
Log.d(JSONObject的,jsonobject.toString());
//设置JSON对象到数组
arraylist.add(地图);
}
}赶上(JSONException E){
Log.e(错误,e.getMessage());
e.printStackTrace();
}
返回null;
} @覆盖
保护无效onPostExecute(无效参数){
//将结果传递到ListViewAdapter.java
适配器=新的适配器(MainActivity.this,ArrayList的); mapp.setArrayListMapData(数组列表);
//适配器设置到ListView
listview.setAdapter(适配器);
//关闭progressdialog
mProgressDialog.dismiss();
}
}
}** ** Adapter.java公共类适配器扩展了BaseAdapter实现OnCheckedChangeListener { //声明变量
上下文语境;
LayoutInflater吹气;
ArrayList的<&HashMap的LT;字符串,字符串>>数据;
HashMap的<字符串,字符串> resultp =新的HashMap<字符串,字符串>();
SparseBooleanArray mysparse; 公共适配器(上下文的背景下,ArrayList的<&HashMap的LT;字符串,字符串>>的ArrayList){
this.context =背景;
数据=数组列表;
mysparse =新SparseBooleanArray(data.size());
} @覆盖
公众诠释的getCount(){
返回data.size();
} @覆盖
公共对象的getItem(INT位置){
返回null;
} @覆盖
众长getItemId(INT位置){
返回0;
} 公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){
//声明变量
TextView的名称;
复选框CHK; 吹气=(LayoutInflater)上下文
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 查看ItemView控件= inflater.inflate(R.layout.single_item,父母,假);
//获取位置
resultp = data.get(位置); //定位listview_item.xml的TextViews
名字=(TextView中)itemView.findViewById(R.id.title_textView_id);
CHK =(复选框)itemView.findViewById(R.id.checkBox1); //捕捉位置,并设置结果向TextViews
name.setText(resultp.get(MainActivity.NAME)); chk.setTag(位置);
chk.setChecked(mysparse.get(位置,FALSE));
chk.setOnCheckedChangeListener(本); 返回ItemView控件;
} 公共布尔器isChecked(INT位置){
返回mysparse.get(位置,FALSE);
} 公共无效setChecked(INT位置,布尔器isChecked){
mysparse.put(位置,器isChecked); } 公共无效切换(INT位置){
setChecked(位置,器isChecked(位置)!); } @覆盖
公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
// TODO自动生成方法存根
mysparse.put((整数)buttonView.getTag(),器isChecked);
}
}
MyApplication.java
公共类MyApplication的扩展应用{ ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的; 公共静态所有MyApplication例如= NULL; @覆盖
公共无效的onCreate(){
// TODO自动生成方法存根
super.onCreate();
} 公共静态的getInstance所有MyApplication()
{
如果(例如== NULL)
{
例如=新所有MyApplication();
}
返回实例;
} 公共无效setArrayListMapData(ArrayList的<&HashMap的LT;字符串,字符串>>使用setData)
{
ArrayList的使用setData =;
} 公众的ArrayList<&HashMap的LT;字符串,字符串>> getArrayListMapData()
{
返回数组列表; }
}
Info.java
公共类信息{ 字符串名称= NULL; 布尔选择= FALSE; 公共信息(字符串名称,布尔选择){
超();
this.Name =名称; this.selected =选择;
} 公共字符串的getName(){
返回名称;
} 公共无效setname可以(字符串名称){
this.Name =名称;
} 公共布尔isSelected(){
返回所选择的;
} 公共无效的setSelected(布尔选择){
this.selected =选择;
}}
DisplayActivity.java
公共类DisplayActivity延伸活动{ LV的ListView;
ArrayList的<串GT; myList中;
串MYNAME; @覆盖
保护无效的onCreate(捆绑savedInstanceState){
// TODO自动生成方法存根
super.onCreate(savedInstanceState);
的setContentView(R.layout.second); 意向N = getIntent();
MYNAME = n.getStringExtra(缓冲区); myList中=新的ArrayList<串GT;(); LV =(ListView控件)findViewById(R.id.listViewData); myList.add(MYNAME); ArrayAdapter<串GT;适配器=新ArrayAdapter<串GT;(DisplayActivity.this,R.layout.custom_single_list,R.id.textView1,myList中); lv.setAdapter(适配器); }}
日志:
十月一日至5日:33:33.213:D / JSONObject的(409):{IMAGE_NAME:image.jpg的,PERSON_NAME:萨尔曼·汗,Sl_no :1}
01-05 10:33:33.213:D / JSONObject的(409):{IMAGE_NAME:c92beeaf5ba50e65.jpg,PERSON_NAME:AmirKhan,Sl_no:2}
十月一日至五日:33:33.213:D / JSONObject的(409):{IMAGE_NAME:f2d835b73945ded2.jpg,PERSON_NAME:卡尔,Sl_no:3}
十月一日至五日:33:33.232:D / JSONObject的(409):{IMAGE_NAME:deafe45d368c64cf.jpg,PERSON_NAME:班加罗尔,Sl_no:4}
十月一日至五日:33:33.232:D / JSONObject的(409):{IMAGE_NAME:cc542ecaf6d251bd.jpg,PERSON_NAME:班加罗尔,Sl_no:5}
十月一日至五日:33:33.232:D / JSONObject的(409):{IMAGE_NAME:3de14abca184c2d5.jpg,PERSON_NAME:喜,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:希莫加,Sl_no:8}
十月一日至五日:33:33.363:D / dalvikvm(409):GC_FOR_MALLOC释放3240对象/在115ms 214432字节
十月一日至五日:33:33.363:D / JSONObject的(409):{IMAGE_NAME:5e8821af90b717bc.jpg,PERSON_NAME:马诺,Sl_no:9}
十月一日至五日:33:33.363:D / JSONObject的(409):{IMAGE_NAME:86e18539867de023.jpg,PERSON_NAME:SharuknKhan,Sl_no:10}
十月一日至五日:33:33.363:D / JSONObject的(409):{IMAGE_NAME:f88b905101e94ef9.jpg,PERSON_NAME:马赫什,Sl_no:11}
01-05 10:33:33.363:D / JSONObject的(409):{IMAGE_NAME:bd793b1f80e238cf.jpg,PERSON_NAME:苏雷什,Sl_no:12}
十月一日至五日:33:33.363:D / JSONObject的(409):{IMAGE_NAME:0eb250bfd8646968.jpg,PERSON_NAME:苏雷什,Sl_no:13}
01-05 10:33:33.363:D / JSONObject的(409):{IMAGE_NAME:270c6a4ef1adb6ed.jpg,PERSON_NAME:amitab,Sl_no:14}
十月一日至五日:33:33.363:D / JSONObject的(409):{IMAGE_NAME:0d6605d2f1089b73.jpg,PERSON_NAME:德里,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:迈索尔,Sl_no:17}
01-05 10:33:33.373:D / JSONObject的(409):{IMAGE_NAME:7ae2a4618c0cdbac.jpg,PERSON_NAME:name123,Sl_no:18}
十月一日至五日:33:36.973:D / dalvikvm(409):GC_EXTERNAL_ALLOC释放1554对象/在89ms 275032字节
十月一日至五日:33:37.093:D / dalvikvm(409):GC_EXTERNAL_ALLOC释放135对象/在76ms 7920个字节
十月一日至五日:48:46.713:D / AndroidRuntime(409):关闭VM
十月一日至五日:48:46.713:W / dalvikvm(409):主题ID = 1:螺纹未捕获的异常退出(组= 0x4001d800)
十月一日至五日:48:46.733:E / AndroidRuntime(409):致命异常:主要
十月一日至五日:48:46.733:E / AndroidRuntime(409):显示java.lang.NullPointerException
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.AbsListView.obtainView(AbsListView.java:1315)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.ListView.makeAndAddView(ListView.java:1727)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.ListView.fillDown(ListView.java:652)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.ListView.fillFromTop(ListView.java:709)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.ListView.layoutChildren(ListView.java:1580)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.AbsListView.onLayout(AbsListView.java:1147)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.view.View.layout(View.java:7035)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.view.View.layout(View.java:7035)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.FrameLayout.onLayout(FrameLayout.java:333)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.view.View.layout(View.java:7035)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.view.View.layout(View.java:7035)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.FrameLayout.onLayout(FrameLayout.java:333)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.view.View.layout(View.java:7035)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.os.Handler.dispatchMessage(Handler.java:99)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.os.Looper.loop(Looper.java:123)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.app.ActivityThread.main(ActivityThread.java:4627)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在java.lang.reflect.Method.invokeNative(本机方法)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在java.lang.reflect.Method.invoke(Method.java:521)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:868)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
十月一日至五日:48:46.733:E / AndroidRuntime(409):在dalvik.system.NativeStart.main(本机方法)
{编辑-1 ----在Raghunandan回答}
MainActivity.java
公共类MainActivity延伸活动{
//声明变量
的JSONObject的JSONObject;
JSONArray jsonarray;
ListView控件列表视图;
转接适配器;
ProgressDialog mProgressDialog;
ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;
ArrayList的<串GT; arraylist2;
静态字符串NAME =等级;
按钮BTN; StringBuilder的结果; 所有MyApplication MAPP; //获取所有MyApplication参考 @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
//从listview_main.xml视图
的setContentView(R.layout.activity_main);
ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>();
arraylist2 =新的ArrayList<串GT;();
MAPP = MyApplication.getInstance();
列表视图=(ListView控件)findViewById(R.id.listView);
BTN =(按钮)findViewById(R.id.button1);
btn.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根
// Toast.makeText(MainActivity.this,///+ arraylist.size(),1000).show();
结果=新的StringBuilder();
的for(int i = 0; I< arraylist.size();我++){
如果(adapter.mysparse.get(我)==真){ result.append(arraylist.get(I)获得(MainActivity.NAME));
arraylist2.add(arraylist.get(I)获得(MainActivity.NAME));
result.append(\\ n);
} }
mapp.setArrayListMapData(arraylist2);
Toast.makeText(MainActivity.this,因此,1000).show();
意图N =新意图(MainActivity.this,DisplayActivity.class);
// n.putExtra(缓冲,arraylist2);
startActivity(N);
}
}); //执行DownloadJSON的AsyncTask
新DownloadJSON()执行();
} // DownloadJSON的AsyncTask
私有类DownloadJSON扩展的AsyncTask<太虚,太虚,太虚> { @覆盖
在preExecute保护无效(){
super.on preExecute();
//创建一个progressdialog
mProgressDialog =新ProgressDialog(MainActivity.this);
//设置progressdialog称号
// mProgressDialog.setTitle(读取信息);
//设置progressdialog消息
mProgressDialog.setMessage(正在加载...);
mProgressDialog.setIndeterminate(假);
//显示progressdialog
mProgressDialog.show();
} @覆盖
保护无效doInBackground(虚空...... PARAMS){
//创建一个数组 尝试{
//从给定的URL地址JSON对象
字符串s =的getData();
JSONObject的=新的JSONObject(S);
//找到在JSON数组名
jsonarray = jsonobject.getJSONArray(餐馆); 的for(int i = 0; I< jsonarray.length();我++){
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
的JSONObject = jsonarray.getJSONObject(ⅰ);
// Retrive JSON对象
map.put(MainActivity.NAME,
jsonobject.getString(PERSON_NAME));
Log.d(JSONObject的,jsonobject.toString());
//设置JSON对象到数组
arraylist.add(地图);
}
}赶上(JSONException E){
Log.e(错误,e.getMessage());
e.printStackTrace();
}
返回null;
} @覆盖
保护无效onPostExecute(无效参数){
//将结果传递到ListViewAdapter.java
适配器=新的适配器(MainActivity.this,ArrayList的);
//适配器设置到ListView
listview.setAdapter(适配器);
//关闭progressdialog
mProgressDialog.dismiss();
}
}
私人字符串的getData(){
字符串_response = NULL;
尝试
{
HttpClient的HttpClient的=新DefaultHttpClient();
httpclient.getParams()的setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1)。
HTTPGET请求=新HTTPGET(http://54.218.73.244:7004/DescriptionSortedPrice/);
HTT presponse响应= httpclient.execute(请求);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity); }
赶上(例外五)
{
e.printStackTrace();
} 返回_response;
}}
DisplayActivity.java
公共类DisplayActivity延伸活动{ LV的ListView;
ArrayList的<串GT; myList中;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.second); 所有MyApplication MAPP = MyApplication.getInstance();
myList中= mapp.getArrayListMapData(); LV =(ListView控件)findViewById(R.id.list); ArrayAdapter<串GT;适配器=新ArrayAdapter<串GT;(DisplayActivity.this,android.R.layout.simple_expandable_list_item_1,myList中); lv.setAdapter(适配器);
} @覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
}}
second.xml
<?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:方向=垂直> < ListView控件
机器人:ID =@ + ID /列表
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:分=@机器人:彩色/透明>
< /&的ListView GT;< / LinearLayout中>
Adapter.java
公共类适配器扩展了BaseAdapter实现OnCheckedChangeListener { //声明变量
上下文语境;
LayoutInflater吹气;
ArrayList的<&HashMap的LT;字符串,字符串>>数据;
HashMap的<字符串,字符串> resultp =新的HashMap<字符串,字符串>();
SparseBooleanArray mysparse; 公共适配器(上下文的背景下,ArrayList的<&HashMap的LT;字符串,字符串>>的ArrayList){
this.context =背景;
数据=数组列表;
mysparse =新SparseBooleanArray(data.size());
} @覆盖
公众诠释的getCount(){
返回data.size();
} @覆盖
公共对象的getItem(INT位置){
返回的位置;
} @覆盖
众长getItemId(INT位置){
返回的位置;
} 公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){
//声明变量
TextView的名称;
复选框CHK; 吹气=(LayoutInflater)上下文
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 查看ItemView控件= inflater.inflate(R.layout.single_item,父母,假);
//获取位置
resultp = data.get(位置); //定位listview_item.xml的TextViews
名字=(TextView中)itemView.findViewById(R.id.textView1);
CHK =(复选框)itemView.findViewById(R.id.checkBox1); //捕捉位置,并设置结果向TextViews
name.setText(resultp.get(MainActivity.NAME)); chk.setTag(位置);
chk.setChecked(mysparse.get(位置,FALSE));
chk.setOnCheckedChangeListener(本); 返回ItemView控件;
} 公共布尔器isChecked(INT位置){
返回mysparse.get(位置,FALSE);
} 公共无效setChecked(INT位置,布尔器isChecked){
mysparse.put(位置,器isChecked); } 公共无效切换(INT位置){
setChecked(位置,器isChecked(位置)!); } @覆盖
公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
// TODO自动生成方法存根
mysparse.put((整数)buttonView.getTag(),器isChecked);
}
}
日志:
十二月一日至五日:27:00.763:E / AndroidRuntime(696):致命异常:主要
12月1日至五日:27:00.763:E / AndroidRuntime(696):显示java.lang.NullPointerException
12月1日至五日:27:00.763:E / AndroidRuntime(696):在com.example.singleitemlistview.Adapter.getView(Adapter.java:64)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.AbsListView.obtainView(AbsListView.java:1315)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.ListView.onMeasure(ListView.java:1109)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.View.measure(View.java:8171)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.RelativeLayout.measureChild(RelativeLayout.java:563)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.RelativeLayout.onMeasure(RelativeLayout.java:378)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.View.measure(View.java:8171)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.View.measure(View.java:8171)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.View.measure(View.java:8171)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.View.measure(View.java:8171)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.ViewRoot.performTraversals(ViewRoot.java:801)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.os.Handler.dispatchMessage(Handler.java:99)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.os.Looper.loop(Looper.java:123)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在android.app.ActivityThread.main(ActivityThread.java:4627)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在java.lang.reflect.Method.invokeNative(本机方法)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在java.lang.reflect.Method.invoke(Method.java:521)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:868)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12月1日至五日:27:00.763:E / AndroidRuntime(696):在dalvik.system.NativeStart.main(本机方法)
12月1日至五日:32:00.805:I /流程(696):发送信号。 PID:696 SIG:9
当您点击
意图N =新意图(MainActivity.this,DisplayActivity.class);
//n.putExtra(\"buffer,result.toString()); //被注释掉
然后
意图N = getIntent();
MYNAME = n.getStringExtra(缓冲区);
有一个列表视图 DisplayActivity
。它需要数据来填充。你的评论在 intent.puExtra code
十月一日至5日:48:46.733:E / AndroidRuntime(409):显示java.lang.NullPointerException
十月一日至五日:48:46.733:E / AndroidRuntime(409):在android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
也期待在源$ C $ C ArrayAdapter
2.2 REV1
326私人查看createViewFromResource(INT位置,查看convertView,ViewGroup中父母,
327 INT资源){
328浏览视图。
329 TextView的文本;
330
如果331(convertView == NULL){
332查看= mInflater.inflate(资源,家长,FALSE);
333}其他{
334查看= convertView;
335}
336
337尝试{
如果338(mFieldId == 0){
339 //如果没有自定义字段分配,假定整个资源是一个TextView
340文本=(TextView的)视图。
341}其他{
342 //否则,找到布局中的TextView场
343文本=(TextView的)view.findViewById(mFieldId);
344}
345}赶上(抛出ClassCastException E){
346 Log.e(ArrayAdapter,你必须为一个TextView提供一个资源ID);
347抛出新IllegalStateException异常(
348ArrayAdapter需要的资源ID是一个TextView,E);
349}
350
351ŧ项目=的getItem(位置);
如果352(项目的instanceof的CharSequence){
353 text.setText((CharSequence的)项目);
354}其他{
355 text.setText(item.toString()); // text为null
356}
357
358返回查看;
359}
355线是
355 text.setText(item.toString()); // text为null
这表明在您的适配器的TextView为null。
在这种情况下,你应该看看
ArrayAdapter<串GT;适配器=新ArrayAdapter<串GT;(DisplayActivity.this,R.layout.custom_single_list,R.id.textView1,myList中);
所以,我建议如下修改
公共类MainActivity延伸活动{
//声明变量
的JSONObject的JSONObject;
JSONArray jsonarray;
ListView控件列表视图;
转接适配器;
ProgressDialog mProgressDialog;
ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;
ArrayList的<串GT; arraylist2;
静态字符串NAME =等级;
按钮BTN; StringBuilder的结果; 所有MyApplication MAPP; //获取所有MyApplication参考 @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
//从listview_main.xml视图
的setContentView(R.layout.activity_main);
ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>();
arraylist2 =新的ArrayList<串GT;();
MAPP = MyApplication.getInstance();
列表视图=(ListView控件)findViewById(R.id.listView);
BTN =(按钮)findViewById(R.id.button1);
btn.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根
// Toast.makeText(MainActivity.this,///+ arraylist.size(),1000).show();
结果=新的StringBuilder();
的for(int i = 0; I< arraylist.size();我++){
如果(adapter.mysparse.get(我)==真){ result.append(arraylist.get(I)获得(MainActivity.NAME));
arraylist2.add(arraylist.get(I)获得(MainActivity.NAME));
result.append(\\ n);
} }
mapp.setArrayListMapData(arraylist2);
Toast.makeText(MainActivity.this,因此,1000).show();
意图N =新意图(MainActivity.this,DisplayActivity.class);
// n.putExtra(缓冲,arraylist2);
startActivity(N);
}
}); //执行DownloadJSON的AsyncTask
新DownloadJSON()执行();
} // DownloadJSON的AsyncTask
私有类DownloadJSON扩展的AsyncTask<太虚,太虚,太虚> { @覆盖
在preExecute保护无效(){
super.on preExecute();
//创建一个progressdialog
mProgressDialog =新ProgressDialog(MainActivity.this);
//设置progressdialog称号
// mProgressDialog.setTitle(读取信息);
//设置progressdialog消息
mProgressDialog.setMessage(正在加载...);
mProgressDialog.setIndeterminate(假);
//显示progressdialog
mProgressDialog.show();
} @覆盖
保护无效doInBackground(虚空...... PARAMS){
//创建一个数组 尝试{
//从给定的URL地址JSON对象
字符串s =的getData();
JSONObject的=新的JSONObject(S);
//找到在JSON数组名
jsonarray = jsonobject.getJSONArray(餐馆); 的for(int i = 0; I< jsonarray.length();我++){
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
的JSONObject = jsonarray.getJSONObject(ⅰ);
// Retrive JSON对象
map.put(MainActivity.NAME,
jsonobject.getString(PERSON_NAME));
Log.d(JSONObject的,jsonobject.toString());
//设置JSON对象到数组
arraylist.add(地图);
}
}赶上(JSONException E){
Log.e(错误,e.getMessage());
e.printStackTrace();
}
返回null;
} @覆盖
保护无效onPostExecute(无效参数){
//将结果传递到ListViewAdapter.java
适配器=新的适配器(MainActivity.this,ArrayList的);
//适配器设置到ListView
listview.setAdapter(适配器);
//关闭progressdialog
mProgressDialog.dismiss();
}
}
私人字符串的getData(){
字符串_response = NULL;
尝试
{
HttpClient的HttpClient的=新DefaultHttpClient();
httpclient.getParams()的setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1)。
HTTPGET请求=新HTTPGET(http://54.218.73.244:7004/DescriptionSortedPrice/);
HTT presponse响应= httpclient.execute(请求);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity); }
赶上(例外五)
{
e.printStackTrace();
} 返回_response;
}
公共类适配器扩展了BaseAdapter实现OnCheckedChangeListener { //声明变量
上下文语境;
LayoutInflater吹气;
ArrayList的<&HashMap的LT;字符串,字符串>>数据;
HashMap的<字符串,字符串> resultp =新的HashMap<字符串,字符串>();
SparseBooleanArray mysparse; 公共适配器(上下文的背景下,ArrayList的<&HashMap的LT;字符串,字符串>>的ArrayList){
this.context =背景;
数据=数组列表;
mysparse =新SparseBooleanArray(data.size());
} @覆盖
公众诠释的getCount(){
返回data.size();
} @覆盖
公共对象的getItem(INT位置){
返回的位置;
} @覆盖
众长getItemId(INT位置){
返回的位置;
} 公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){
//声明变量
TextView的名称;
复选框CHK; 吹气=(LayoutInflater)上下文
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 查看ItemView控件= inflater.inflate(R.layout.single_item,父母,假);
//获取位置
resultp = data.get(位置); //定位listview_item.xml的TextViews
名字=(TextView中)itemView.findViewById(R.id.textView1);
CHK =(复选框)itemView.findViewById(R.id.checkBox1); //捕捉位置,并设置结果向TextViews
name.setText(resultp.get(MainActivity.NAME)); chk.setTag(位置);
chk.setChecked(mysparse.get(位置,FALSE));
chk.setOnCheckedChangeListener(本); 返回ItemView控件;
} 公共布尔器isChecked(INT位置){
返回mysparse.get(位置,FALSE);
} 公共无效setChecked(INT位置,布尔器isChecked){
mysparse.put(位置,器isChecked); } 公共无效切换(INT位置){
setChecked(位置,器isChecked(位置)!); } @覆盖
公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
// TODO自动生成方法存根
mysparse.put((整数)buttonView.getTag(),器isChecked);
}
}
}
MyApplication的类
公共类MyApplication的扩展应用{ ArrayList的<串GT; ArrayList的; 公共静态所有MyApplication例如= NULL; @覆盖
公共无效的onCreate(){
// TODO自动生成方法存根
super.onCreate();
} 公共静态的getInstance所有MyApplication()
{
如果(例如== NULL)
{
例如=新所有MyApplication();
}
返回实例;
} 公共无效setArrayListMapData(ArrayList的<串GT;使用setData)
{
ArrayList的使用setData =;
} 公众的ArrayList<串GT; getArrayListMapData()
{
返回数组列表; }}
DisplayActivity
公共类DisplayActivity延伸活动{ LV的ListView;
ArrayList的<串GT; myList中;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_display); 所有MyApplication MAPP = MyApplication.getInstance();
myList中= mapp.getArrayListMapData(); LV =(ListView控件)findViewById(R.id.listView1); ArrayAdapter<串GT;适配器=新ArrayAdapter<串GT;(DisplayActivity.this,android.R.layout.simple_expandable_list_item_1,myList中); lv.setAdapter(适配器);
} @覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.display,菜单);
返回true;
}}
捕捉
使用ViewHolder模式是一个不错的选择。
I am trying to use MyApplication class for JSON data
What I am doing:: I am displaying a list of elements in listview
, I have retrieved data from JSON
and populated into listview
. I have put the snapshot of it below which I have at present.
What I am trying to do::
- Suppose I check some rows using the
checkbox
shown in figure, now the selected elements I want to add them toMyApplication class
which is aglobal memory
. - Then I want to get the data from Main global memory and display it in
the
listview
ex:: If I select Carl
and bangalore
When I click Button
I must get the listview
of Carl
and Bangalore
displayed
What problem i am facing:: After selecting the checkbox
of required elements when i click Button
i am getting log errors as shown in the Log
- Note:: I dont want to send data using Intents from This listview to nextone, as i am trying to learn the use of
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);
}
}
Log::
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);
}
}
Log::
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
When you click
Intent n = new Intent(MainActivity.this, DisplayActivity.class);
//n.putExtra("buffer", result.toString()); // is commented
Then
Intent n = getIntent();
myName = n.getStringExtra("buffer");
There is a listview DisplayActivity
. Its needs data to populate. You commented the 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)
Also look at the source code of 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 }
Line 355 is
355 text.setText(item.toString()); // text is null
Indicating that the textview in your adapter is null.
in which case you should look at
ArrayAdapter<String> adapter=new ArrayAdapter<String>(DisplayActivity.this,R.layout.custom_single_list,R.id.textView1, myList);
So i suggest the following changes
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 class
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;
}
}
Snaps
Using ViewHolder pattern is a good choice
这篇关于在Android的使用MyApplication的类JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!