越来越JSON结果变成ListView控件时发生错误 [英] Errors when getting JSON result into ListView

查看:314
本文介绍了越来越JSON结果变成ListView控件时发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新4:问题就迎刃而解了检查我的回答以下

我想从PHP Webservice的retreive JSON结果,并保存到ListView的,但我得到了一个错误

我不知道什么是我的错,你可以帮我请

我是从以下特拉维斯本教程(mybringback)

<一个href=\"http://www.mybringback.com/tutorial-series/13239/android-mysql-php-json-part-6-json-parsing-and-android-design/\" rel=\"nofollow\">http://www.mybringback.com/tutorial-series/13239/android-mysql-php-json-part-6-json-parsing-and-android-design/

他的方法(仅适用于本部分)不需要任何参数,以获得帖子(它实际上是workis用他的PHP法)
但是我的Web服务方法需要2个参数(kioskid(设备ID)的accessToken),它保存在共享preferense

UPDATE1:

我修改了Android code也卸载旧的和beginig(登录等)开始,直到我得到EventListActivity但是,没有列表显示和我在日志只拿到一次错误线(在没有错误信息该设备)

UPDATE2:修改code和分离后的 UpdateJSON()并试图让JSON响应 doInBackground()

更新3:我添加JSONParse类线

我说我在 setListAdapter(适配器)的方法中的 updateList()的得到的NullPointerException一个新的错误消息

这是错误日志:

  03-26 16:58:38.397:E / AndroidRuntime(16196):致命异常:主要
03-26 16:58:38.397:E / AndroidRuntime(16196):工艺:com.test.event,PID:16196
03-26 16:58:38.397:E / AndroidRuntime(16196):显示java.lang.NullPointerException
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93)
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.widget.ListView.setAdapter(ListView.java:480)
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.app.ListActivity.setListAdapter(ListActivity.java:265)
03-26 16:58:38.397:E / AndroidRuntime(16196):在com.de coder.tapway.event1.EventListActivity.updateList(EventListActivity.java:140)
03-26 16:58:38.397:E / AndroidRuntime(16196):在com.de coder.tapway.event1.EventListActivity.access 3(EventListActivity.java:136)
03-26 16:58:38.397:E / AndroidRuntime(16196):在com.de coder.tapway.event1.EventListActivity $ LoadEvents.onPostExecute(EventListActivity.java:221)
03-26 16:58:38.397:E / AndroidRuntime(16196):在com.de coder.tapway.event1.EventListActivity $ LoadEvents.onPostExecute(EventListActivity.java:1)
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.os.AsyncTask.finish(AsyncTask.java:632)
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.os.AsyncTask.access $ 600(AsyncTask.java:177)
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:645)
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.os.Handler.dispatchMessage(Handler.java:102)
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.os.Looper.loop(Looper.java:136)
03-26 16:58:38.397:E / AndroidRuntime(16196):在android.app.ActivityThread.main(ActivityThread.java:5050)
03-26 16:58:38.397:E / AndroidRuntime(16196):在java.lang.reflect.Method.invokeNative(本机方法)
03-26 16:58:38.397:E / AndroidRuntime(16196):在java.lang.reflect.Method.invoke(Method.java:515)
03-26 16:58:38.397:E / AndroidRuntime(16196):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779)
03-26 16:58:38.397:E / AndroidRuntime(16196):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-26 16:58:38.397:E / AndroidRuntime(16196):在dalvik.system.NativeStart.main(本机方法)

这是我想要得到它的JSON结果PHP函数(Yii框架)

 公共职能actionEventList(){
        如果(使用isset($ _ POST ['kioskid'])及和放大器;使用isset($ _ POST ['的accessToken'])){
            $响应=阵列();            $亭=亭::模型() - GT; findByAttributes(阵列('kioskid'=&GT; $ _ POST ['kioskid']'的accessToken'=&GT; $ _ POST ['的accessToken']));
            如果($亭=== NULL){
                $响应['状态'] ='0';
                $响应['消息'] ='无效亭;
            }其他{
                $事件=事件::模型() - GT; findAllByAttributes(阵列('createdby'=&GT; $ kiosk-&GT;用户ID,状态= GT;'A'));
                $名单=阵列();
                的foreach($事件作为$行){
                    $名单[] =阵列('ID'=&GT; $行向&GT; ID,'名'=&GT; $行向&GT; eventName的);
                }
                $响应['状态'] ='1';
                $响应['名单'] = $名单;
            }
            $这个 - &GT; _sendResponse(200,CJSON :: EN code($响应));
        }其他{
            $这 - &GT; _sendResponse(400);
        }
    }

这是我的Java code在安卓(更新)

最重要的方法就是 updateJSONdata()从服务器中检索最近发生的事件

然后我把里面的那个方法 doInBackground()

 公共类EventListActivity扩展ListActivity {    //进度对话框
    私人ProgressDialog pDialog;
    //服务器上进行测试:
    私有静态最后弦乐EVENT_LIST_URL =htt​​p://www.XXX.com/XXX/XXX/eventList;    // JSON IDS:
    私有静态最后弦乐TAG_STATUS =身份;
    私有静态最后弦乐TAG_EVENT_LIST =清单;
    私有静态最后弦乐TAG_EVENT_ID =ID;
    私有静态最后弦乐TAG_EVENT_NAME =名;
    私有静态最后弦乐TAG_MESSAGE =消息;    //我们的所有活动中的数组
    私人JSONArray jaEvents = NULL;    //管理所有我们的活动在列表中。
    私人的ArrayList&LT;&HashMap的LT;字符串,字符串&GT;&GT; arrayEventList;
    // $ P $共享做好准备preferences文件名
    私有静态最后弦乐preFS_NAME =com.MyApp.event;    私人共享preferences共享preF;    字符串的accessToken,用户名,kioskid,spKioskid,密码;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);
        的setContentView(R.layout.event_list_layout);        //设置共享preferences文件
        this.shared preF = getShared preferences(preFS_NAME,0);        //从previous活动数据
        this.accesstoken =共享pref.getString(的accessToken,NULL);
        this.kioskid = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);        Toast.makeText(EventListActivity.this的onCreate \\ n+ kioskid,Toast.LENGTH_LONG).show();
        Toast.makeText(EventListActivity.this的onCreate \\ n+的accessToken,Toast.LENGTH_LONG).show();    }    @覆盖
    保护无效onResume(){
        super.onResume();
        //分配从共享preferences数据
        this.accesstoken =共享pref.getString(的accessToken,NULL);
        this.kioskid = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
        Toast.makeText(EventListActivity.this,onResume \\ n+ kioskid,Toast.LENGTH_LONG).show();
        Toast.makeText(EventListActivity.this,onResume \\ n+的accessToken,Toast.LENGTH_LONG).show();
        //加载通过的AsyncTask的评论
        新LoadEvents()执行();
    }
    / **
     *从服务器检索最近发生的事件。
     * /
    公共无效updateJSONdata(){        arrayEventList =新的ArrayList&LT;&HashMap的LT;字符串,字符串&GT;&GT;();        JSONParser jParser =新JSONParser();        JSONObject的jsonObj = jParser.getJSONFromUrl(EVENT_LIST_URL);        尝试{            jaEvents = jsonObj.getJSONArray(TAG_EVENT_LIST);            //通过所有事件根据JSON对象返回的循环
            的for(int i = 0; I&LT; jaEvents.length();我++){
                JSONObject的C = jaEvents.getJSONObject(I)                //获取每个标签的内容
                字符串事件ID = c.getString(TAG_EVENT_ID);
                串eventName的= c.getString(TAG_EVENT_NAME);                //创建新的HashMap
                HashMap的&LT;字符串,字符串&GT;地图=新的HashMap&LT;字符串,字符串&GT;();                map.put(TAG_EVENT_ID,事件ID);
                map.put(TAG_EVENT_NAME,eventName的);                arrayEventList.add(地图);
            }
        }赶上(JSONException E){
            e.printStackTrace();
        }
    }    / **
     *插入解析的数据到ListView中。
     * /
    私人无效updateList(){
        ListAdapter适配器=新SimpleAdapter(这一点,arrayEventList,
                R.layout.single_event_layout,新的String [] {TAG_EVENT_ID,TAG_EVENT_NAME},新的INT [] {R.id.event_id,R.id.event_name});        setListAdapter(适配器);        ListView控件LV = getListView();
        lv.setOnItemClickListener(新OnItemClickListener(){            @覆盖
            公共无效onItemClick(适配器视图&LT;&GT;母公司,观景,
                    INT位置,长的id){
                // 做一点事
            }
        });
    }    公共类LoadEvents扩展的AsyncTask&LT;字符串,字符串,字符串&GT; {        JSONParser jParser =新JSONParser();        //检查成功标记
        INT状态;
        字符串的accessToken;
        串kioskid;
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(EventListActivity.this);
            pDialog.setMessage(加载活动...);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真);
            pDialog.show();
        }        @覆盖
        保护字符串doInBackground(字符串...为arg0){
            this.accesstoken =共享pref.getString(的accessToken,NULL);
            this.kioskid = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);            尝试{
                //建筑参数注销
                清单&LT;&的NameValuePair GT; PARAMS =新的ArrayList&LT;&的NameValuePair GT;();
                params.add(新BasicNameValuePair(的accessToken的accessToken));
                params.add(新BasicNameValuePair(kioskid,kioskid));
                Log.d(!要求,启动);                //通过HTT prequest获得产品的详细信息
                JSONObject的JSON = jParser.makeHtt prequest(EVENT_LIST_URL,POST,则params);                //检查你的日志,JSON响应
                Log.d(装载仪活动学尝试,json.toString());                //分配状态JSON身份标签
                状态= json.getInt(TAG_STATUS);
                如果(状态== 1){
                    在控制台成功消息+ JSON响应消息//打印
                    Log.d(活动成功加载,json.toString());
                    updateJSONdata();                    返回json.getString(TAG_MESSAGE);
                }其他{
                    在控制台失败消息+ JSON响应消息//打印
                    Log.d(Faild装载仪活动!,json.getString(TAG_MESSAGE));                    返回json.getString(TAG_MESSAGE);                }
            }赶上(JSONException E){
                e.printStackTrace();
            }
            返回null;        }        @覆盖
        保护无效onPostExecute(字符串结果){
            super.onPostExecute(结果);
            pDialog.dismiss();
            updateList();
        }
    }
}

更新3

JSONParser类

 公共类JSONParser {
    静态InputStream为= NULL;
    静态的JSONObject jObj = NULL;
    静态JSON字符串=;    //构造
    公共JSONParser(){    }    公众的JSONObject getJSONFromUrl(字符串URL){
        //使HTTP请求
        尝试{
            //构建客户端和HTTP请求。
            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            HttpPost httpPost =新HttpPost(URL);            //执行POST请求,并在本地存储的响应。
            HTT presponse HTT presponse = httpClient.execute(httpPost);            //从响应中提取数据。
            HttpEntity httpEntity = HTT presponse.getEntity();            //打开与数据内容的InputStream。
            是= httpEntity.getContent();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        尝试{
            //创建一个BufferedReader通过InputStream的解析。
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);            //声明一个字符串生成器,以帮助解析。
            StringBuilder的SB =新的StringBuilder();
            //声明一个字符串JSON对象数据存储在字符串形式。
            串线= NULL;            //生成字符串,直到空。
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }            //关闭输入流。
            is.close();
            //字符串生成器的数据转换为实际的字符串。
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,错误转换结果+ e.toString());
        }        //尝试分析字符串到一个JSON对象
        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误解析数据+ e.toString());
        }        //返回JSON字符串
        返回jObj;
    }    //函数得到JSON的网址
    //通过HTTP POST或GET mehtod
    公众的JSONObject makeHtt prequest(字符串loginUrl,字符串的方法,
            清单&LT;&的NameValuePair GT; PARAMS){
        //使HTTP请求
        尝试{
            //检查请求的方法
            如果(方法==POST){
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                HttpPost httpPost =新HttpPost(loginUrl);
                httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));
                HTT presponse HTT presponse = httpClient.execute(httpPost);                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();
            }其他
                //检查请求的方法
                如果(方法==GET){
                    DefaultHttpClient的HttpClient =新DefaultHttpClient();
                    字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
                    loginUrl + =? +中的paramString;
                    HTTPGET HTTPGET =新HTTPGET(loginUrl);
                    HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                    HttpEntity httpEntity = HTT presponse.getEntity();
                    是= httpEntity.getContent();
            }        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        尝试{
                读者的BufferedReader =新的BufferedReader(
                    新InputStreamReader的(是ISO-8859-1),8);
                StringBuilder的SB =新的StringBuilder();
                串线= NULL;                而((行= reader.readLine())!= NULL){
                    sb.append(行+\\ n);
                }
                is.close();
                JSON = sb.toString();
            }赶上(IOException异常五){
                Log.d(缓冲区错误,错误转换Reesult+ e.toString());
            }        //试图解析字符串JSON对象
        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误解析数据+ e.toString());
        }        //返回JSON字符串
        返回jObj;
    }}

single_event_layout.xml

 &LT;?XML版本=1.0编码=UTF-8&GT?;
&LT; LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:背景=@绘制/梯度
    机器人:方向=垂直&GT;    &LT;的LinearLayout
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_margin =5DP
    机器人:背景=@绘制/ post_border_style
    机器人:方向=垂直&GT;    &LT;的LinearLayout
        机器人:ID =@ + ID /箱
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_margin =2DP
        机器人:背景=@绘制/ post_background_style
        机器人:方向=横向&GT;        &LT; ImageView的
            机器人:ID =@ + ID / imageView1
            机器人:layout_width =100dp
            机器人:layout_height =100dp
            机器人:SRC =@绘制/ tapway_event_logo/&GT;        &LT;的LinearLayout
            机器人:ID =@ + ID /箱
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_margin =2DP
            机器人:方向=垂直
            机器人:填充=5DP&GT;            &LT;的TextView
                机器人:ID =@ + ID /事项标识
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:layout_gravity =底
                机器人:paddingBottom会=2DIP
                机器人:paddingLeft =5DP
                机器人:paddingTop =6DIP
                机器人:文字颜色=#333
                机器人:TEXTSIZE =16SP
                机器人:文字样式=大胆/&GT;            &LT;的TextView
                机器人:ID =@ + ID / EVENT_NAME
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:paddingBottom会=2DIP
                机器人:paddingLeft =8DP
                机器人:文字颜色=#888&GT;
            &LT; / TextView的&GT;
        &LT; / LinearLayout中&GT;
    &LT; / LinearLayout中&GT;
&LT; / LinearLayout中&GT;

event_list_layout.xml

 &LT;?XML版本=1.0编码=UTF-8&GT?;
&LT;的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:背景=@绘制/梯度&GT;    &LT;的LinearLayout
        机器人:ID =@ + ID / top_layover
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignParentLeft =真
        机器人:layout_alignParentTop =真
        机器人:背景=@绘制/ blue_gradient
        机器人:方向=横向&GT;        &LT;的TextView
            风格=@风格/ BlackText
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_gravity =中心
            机器人:比重=中心
            机器人:文字=@字符串/ EVENT_LIST
            机器人:textAppearance =:/&gt;中的Andr​​oid ATTR / textAppearanceLarge?
    &LT; / LinearLayout中&GT;    &LT; ListView控件
        机器人:ID =@机器人:ID /列表
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_below =@ + ID / top_layover
        机器人:背景=#FFF
        机器人:分=@机器人:彩色/透明
        机器人:滚动条=无/&GT;&LT; / RelativeLayout的&GT;


解决方案

感谢大家对您的答复。

我发现错误

其实这只是传递一个错误的参数错误

实际上它是在Web服务器的错误,有应该是2种访问令牌
一个用于登录,另一个用于所选择的事件
但是,当我选择一个事件的实现改变自带登录事件访问令牌之一

previously我具体的事件ID没有工作,完成相关的,这就是为什么我没有注意到的变化事件其他的事情

现在问题解决了

长话短说
在code正确

再次谢谢

UPDATE 4: Problem Solved Check my Answer Below

I am trying to retreive JSON result from PHP Webservice and save it into ListView But I got an errors

I'm not sure what is my mistake could you help me please

I was following this tutorial from Travis (mybringback)

http://www.mybringback.com/tutorial-series/13239/android-mysql-php-json-part-6-json-parsing-and-android-design/

His method (Only on this part) doesn't require any Parameters to get Posts (and it is actually workis using HIS PHP Method) But My web Service Method require 2 Parameters (kioskid (device ID), accesstoken) which are saved in SharedPreferense

Update1:

I modified the Android code also uninstall the old one and start from beginig (Login and so on) until i get to EventListActivity But no List is showing and I got only one error Line in Log (no error message in the device)

Update2: After Modifying the code and separating UpdateJSON() and trying to get JSON Response in doInBackground()

update 3: I Added JSONParse Class

I got a new Error message that I'm getting NullPointerexception at setListAdapter(adapter) inside the method updateList()

this is the error Log:

03-26 16:58:38.397: E/AndroidRuntime(16196): FATAL EXCEPTION: main
03-26 16:58:38.397: E/AndroidRuntime(16196): Process: com.test.event, PID: 16196
03-26 16:58:38.397: E/AndroidRuntime(16196): java.lang.NullPointerException
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.widget.ListView.setAdapter(ListView.java:480)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.app.ListActivity.setListAdapter(ListActivity.java:265)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at com.decoder.tapway.event1.EventListActivity.updateList(EventListActivity.java:140)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at com.decoder.tapway.event1.EventListActivity.access$3(EventListActivity.java:136)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at com.decoder.tapway.event1.EventListActivity$LoadEvents.onPostExecute(EventListActivity.java:221)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at com.decoder.tapway.event1.EventListActivity$LoadEvents.onPostExecute(EventListActivity.java:1)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.os.AsyncTask.finish(AsyncTask.java:632)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.os.Handler.dispatchMessage(Handler.java:102)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.os.Looper.loop(Looper.java:136)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at android.app.ActivityThread.main(ActivityThread.java:5050)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at java.lang.reflect.Method.invokeNative(Native Method)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at java.lang.reflect.Method.invoke(Method.java:515)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-26 16:58:38.397: E/AndroidRuntime(16196):    at dalvik.system.NativeStart.main(Native Method)

this is the PHP function (Yii Framework) that I'm trying to get its JSON result

public function actionEventList(){
        if(isset($_POST['kioskid']) && isset($_POST['accesstoken'])){
            $response = array();

            $kiosk = Kiosk::model()->findByAttributes(array('kioskid'=>$_POST['kioskid'], 'accesstoken'=>$_POST['accesstoken']));
            if($kiosk === null){
                $response['status'] = '0';
                $response['message'] = 'Invalid Kiosk';
            } else {
                $events = Event::model()->findAllByAttributes(array('createdby'=>$kiosk->userid, 'status'=>'A'));
                $list = array();
                foreach($events as $row){
                    $list[] = array('id'=>$row->id, 'name'=>$row->eventname);
                }
                $response['status'] = '1';
                $response['list'] = $list;
            }
            $this->_sendResponse(200, CJSON::encode($response));
        } else {
            $this->_sendResponse(400);
        }
    }

This is my Java code in android: (UPDATED 2)

The Most Important Method is updateJSONdata() that Retrieves recent Events from the server

Then I call that method inside doInBackground()

public class EventListActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;


    // testing on Server:
    private static final String EVENT_LIST_URL = "http://www.XXX.com/XXX/XXX/eventList";



    // JSON IDS:
    private static final String TAG_STATUS = "status";
    private static final String TAG_EVENT_LIST = "list";
    private static final String TAG_EVENT_ID = "id";
    private static final String TAG_EVENT_NAME = "name";
    private static final String TAG_MESSAGE = "message";

    // An array of all of our Events
    private JSONArray jaEvents = null;

    // manages all of our events in a list.
    private ArrayList<HashMap<String, String>> arrayEventList;


    // prerepare SharedPreferences file name
    private static final String PREFS_NAME = "com.MyApp.event"; 

    private SharedPreferences sharedPref ;

    String accesstoken, username, kioskid,spKioskid, password ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.event_list_layout);

        // setup SharedPreferences file
        this.sharedPref = getSharedPreferences(PREFS_NAME,0);

        // get data from previous activity 
        this.accesstoken = sharedPref.getString("accesstoken", null);
        this.kioskid = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

        Toast.makeText(EventListActivity.this, "onCreate\n"+kioskid, Toast.LENGTH_LONG).show();
        Toast.makeText(EventListActivity.this, "onCreate\n"+accesstoken, Toast.LENGTH_LONG).show();

    }

    @Override
    protected void onResume() {
        super.onResume();
        // assign data from SharedPreferences 
        this.accesstoken = sharedPref.getString("accesstoken", null);
        this.kioskid = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        Toast.makeText(EventListActivity.this, "onResume\n"+kioskid, Toast.LENGTH_LONG).show();
        Toast.makeText(EventListActivity.this, "onResume\n"+accesstoken, Toast.LENGTH_LONG).show();


        // loading the comments via AsyncTask
        new LoadEvents().execute();
    }


    /**
     * Retrieves recent Events from the server.
     */
    public void updateJSONdata() {

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

        JSONParser jParser = new JSONParser();

        JSONObject jsonObj = jParser.getJSONFromUrl(EVENT_LIST_URL);

        try {

            jaEvents = jsonObj.getJSONArray(TAG_EVENT_LIST);

            // looping through all events according to the json object returned
            for (int i = 0; i < jaEvents.length(); i++) {
                JSONObject c = jaEvents.getJSONObject(i);

                // gets the content of each tag
                String eventID = c.getString(TAG_EVENT_ID);
                String eventName = c.getString(TAG_EVENT_NAME);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_EVENT_ID, eventID);
                map.put(TAG_EVENT_NAME, eventName);

                arrayEventList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * Inserts the parsed data into the listview.
     */
    private void updateList() {
        ListAdapter adapter = new SimpleAdapter(this, arrayEventList,
                R.layout.single_event_layout, new String[] { TAG_EVENT_ID, TAG_EVENT_NAME}, new int[] { R.id.event_id, R.id.event_name });

        setListAdapter(adapter);

        ListView lv = getListView();    
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // do something
            }
        });
    }

    public class LoadEvents extends AsyncTask<String, String, String> {

        JSONParser jParser = new JSONParser();

        // check for success tag
        int status;
        String accesstoken ;
        String kioskid ;


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EventListActivity.this);
            pDialog.setMessage("Loading Events...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... arg0) {


            this.accesstoken = sharedPref.getString("accesstoken", null);
            this.kioskid = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

            try {
                // building parameters for Logout
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("accesstoken", accesstoken));
                params.add(new BasicNameValuePair("kioskid", kioskid));
                Log.d("request!", "Starting");

                // getting product details by HTTPRequest
                JSONObject json = jParser.makeHttpRequest(EVENT_LIST_URL,"POST",params);

                // checking your log for JSON response
                Log.d("Loding Events Attemp", json.toString());

                // assign status to JSON "status" tag
                status = json.getInt(TAG_STATUS);
                if (status == 1){
                    // print in console success message + JSON response message
                    Log.d("Events Loaded Successfully",json.toString());


                    updateJSONdata();

                    return json.getString(TAG_MESSAGE);
                }else{
                    // print in console failure message + JSON response message
                    Log.d("Faild loding Events!", json.getString(TAG_MESSAGE));

                    return json.getString(TAG_MESSAGE);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;

        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            updateList();
        }
    }
}

Update 3

JSONParser Class

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {
        // making HTTP Request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);

            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();

            // Open an inputStream with the data content.
            is = httpEntity.getContent();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);

            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try to parse the string to a JSON Object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error Parsing data" + e.toString());
        }

        // return JSON String
        return jObj;
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String loginUrl, String method,
            List<NameValuePair> params) {
        // making HTTP Request
        try {
            // check for request method
            if(method == "POST"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(loginUrl);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                HttpResponse httpResponse = httpClient.execute(httpPost);

                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }else 
                // check for request method
                if(method == "GET"){
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    loginUrl += "?" + paramString;
                    HttpGet httpGet = new HttpGet(loginUrl);
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
                BufferedReader  reader = new BufferedReader(
                    new InputStreamReader(is, "iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String  line = null;

                while((line = reader.readLine()) != null){
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (IOException e) {
                Log.d("Buffer Error","Error Converting Reesult "+e.toString());
            }

        // try parse the string to JSON Object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error Parsing data" + e.toString());
        }

        // return JSON String
        return jObj;
    }

}

single_event_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
    android:background="@drawable/post_border_style"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/box"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:background="@drawable/post_background_style"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/tapway_event_logo" />

        <LinearLayout
            android:id="@+id/box"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:orientation="vertical"
            android:padding="5dp" >

            <TextView
                android:id="@+id/event_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:paddingBottom="2dip"
                android:paddingLeft="5dp"
                android:paddingTop="6dip"
                android:textColor="#333"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/event_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingBottom="2dip"
                android:paddingLeft="8dp"
                android:textColor="#888" >
            </TextView>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

event_list_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gradient" >

    <LinearLayout
        android:id="@+id/top_layover"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/blue_gradient"
        android:orientation="horizontal" >

        <TextView
            style="@style/BlackText"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="@string/event_list"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/top_layover"
        android:background="#fff"
        android:divider="@android:color/transparent"
        android:scrollbars="none" />

</RelativeLayout>

解决方案

Thanks to everyone for your responses

I found the mistake

Actually It's just an error passing a wrong parameter

in fact it's a mistake in the web server that there are should be 2 kind of access token one for Login and the other for the selected event But when I select an event the implementation change the one that comes with login to event access token

previously I was working on specific Event ID without to finish other things related to events that's why I didn't notice the changes

Now Problem Solved

Long story short The Code Is Correct

thank you again

这篇关于越来越JSON结果变成ListView控件时发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆