Android:Post()与API8中的Runnable Clash

时间:2014-06-09 05:46:19

标签: android android-fragments android-listview runnable

问题

我用Fragment创建了ViewPager。在下面的代码中,问题发生在 setup_screen3()中。我正在编码以保持其方向更改和ViewPager幻灯片的状态。我成功通过在onResume()中实现一些逻辑来实现它。但是,在setup_screen3中有自定义ListView +可扩展动画,我想保留单击项目的展开状态。 我实现onSaveInstanceState()以保存哪些项位置 isOpen 并使用它通过编程方式在setup_screen3()中使用Post()和Runnable()方法执行单击。它成功保留在API19(移动设备)中,但不在API8(仿真器)中。我不知道是什么问题

注意

我已经削减了无关紧要的代码,因为它太长了。

ScreenSlidePageFragment.Class

    private static final String KEY_CONTENT = "INTEREST";
    private String currentPos = "-1";
    private String mContent = "";
    private String yourID = "*******";
    private String yourPassword = "*********";
    private Handler handler;
    private Runnable runnable;

    public static ScreenSlidePageFragment produce(String content) {
       ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
        fragment.mContent = content;
        return fragment;
    }

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

        /*??*/
        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
        if ((savedInstanceState != null) && savedInstanceState.containsKey("aa")) {
            currentPos = savedInstanceState.getString("aa");
        }else{
            currentPos = "-1";
        }

    }

    @Override
    public void onResume() {
        super.onResume();


        if(this.mContent.contains("INTEREST")){

        }
        else if(this.mContent.contains("NEWS")){

        }
        else if(this.mContent.contains("SCHEDULE")){

            scheduleLvItems = new ArrayList<Schedule_ListView>();
            String scheduleJSON = dm3.readFile("scheduleJSON");

            if (!scheduleJSON.equals("empty")){
                System.out.println(scheduleJSON);
                renderScreen3(aq3.getContext(), scheduleJSON);
            }
            else{
                String url = "http://requestURL/getSchedule_v2.php?+" +
                        "loginId="+yourID+
                        "&password="+yourPassword+
                        "&year=2013&semester=2";

                aq3.ajax(url,String.class, this,"cb3");
            }
        }
        else{

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        LinearLayout layout;

//        Toast.makeText(getActivity(),mContent,1).show();

        if(this.mContent.contains("INTEREST")){
            layout = (LinearLayout)inflater.inflate(R.layout.fragment_interest, null);
            setup_screen1(layout);

            return layout;
        }
        else if(this.mContent.contains("NEWS")){
            layout = (LinearLayout)inflater.inflate(R.layout.fragment_news, null);
            setup_screen2(layout);

            return layout;
        }
        else if(this.mContent.contains("SCHEDULE")){
            layout = (LinearLayout)inflater.inflate(R.layout.fragment_schedule, null);
            setup_screen3(layout);

            return layout;
        }
        else{
            layout= (LinearLayout)inflater.inflate(R.layout.fragment_me, null);
            setup_screen4(layout);

            return layout;
        }
    }



    private static int[] SUBJECT_COLOR =  {
            R.color.subject_turquoise,
            R.color.subject_orange,
            R.color.subject_wisteria,
            R.color.subject_cinnabar,
            R.color.subject_belizeHole,
            R.color.subject_malibu,
            R.color.subject_pomegranate,
            R.color.subject_sunFlower,
            R.color.subject_concrete,
            R.color.subject_carrot,
            R.color.subject_emerald,
            R.color.subject_clouds,
    };

    private ListView lvSchedule;
    private ArrayList<Schedule_ListView> scheduleLvItems;
    private Schedule_Adapter scheduleAdapter;
    private DataManager dm3;
    private AQuery aq3;

    private void setup_screen3(LinearLayout layout) {

        View v = (View)layout;
        final Context c = v.getContext();
        aq3 = new AQuery(c);
        dm3 = new DataManager(c);

        lvSchedule = (ListView) v.findViewById(R.id.listView_schedule);




    }

    public void cb3(String url, String html, AjaxStatus status){

        System.out.println(html);
        renderScreen3(aq3.getContext(), html);
    }

    public void renderScreen3(Context c, String jsonString){

        try {

            List<List<String>> monData = new ArrayList<List<String>>();
            List<List<String>> tueData = new ArrayList<List<String>>();
            List<List<String>> wedData = new ArrayList<List<String>>();
            List<List<String>> thuData = new ArrayList<List<String>>();
            List<List<String>> friData = new ArrayList<List<String>>();
            List<List<String>> satData = new ArrayList<List<String>>();
            List<List<String>> sunData = new ArrayList<List<String>>();

                        /*Note [Knowledge]
                        *JSON Symbol {,} = JSONObject
                        *JSON symbol [,] = JSONArray
                        */

            //Change JSONString to JSONArray
            JSONArray jsonArray_data = new JSONArray(jsonString);

            //Save Persistence Json Array in app data for fetch with out internet
            dm3.writeFile("scheduleJSON", jsonArray_data.toString());


            for (int i = 0; i < jsonArray_data.length(); i++) {
                //Change object to String and stored each JSON item in Variable
                JSONObject dataRecord = jsonArray_data.getJSONObject(i);

                String yearSemester = dataRecord.getString("YEAR / SEM");
                String courseID = dataRecord.getString("COURSE ID");
                String courseName = dataRecord.getString("COURSE NAME");
                String courseSection = dataRecord.getString("SECTION");
                JSONArray courseInfo = dataRecord.getJSONArray("COURSE INFO");
                String finalDate = dataRecord.getString("FINAL DATE");
                String finalRoom = dataRecord.getString("FINAL ROOM");
                String finalTime = dataRecord.getString("FINAL TIME");
                String midtermDate = dataRecord.getString("MIDTERM DATE");
                String midtermRoom = dataRecord.getString("MIDTERM ROOM");
                String midtermTime = dataRecord.getString("MIDTERM TIME");
                int subjectColor = getResources().getColor(SUBJECT_COLOR[i]);

                for (int ii = 0; ii < courseInfo.length(); ii++) {
                    //Change object to String and stored each JSON item in Variable
                    JSONObject infoRecord = courseInfo.getJSONObject(ii);

                    String day = infoRecord.getString("DAY").replace(".", "").trim();
                    String tStart = infoRecord.getString("TIME").replace(" - ", "").trim().substring(0, 5);
                    String tStop = infoRecord.getString("TIME").replace(" - ", "").trim().substring(5);
                    String roomStudy = infoRecord.getString("ROOM STUDY");
                    String instructor = infoRecord.getString("INSTRUCTOR");


                    List<String> dataRow = new ArrayList<String>();

                    if (day.contains("Mon")) {
                        dataRow.add(courseName);                    //course name
                        dataRow.add(tStart);                        //period start
                        dataRow.add(tStop);                         //period end
                        dataRow.add(String.valueOf(subjectColor));  //subject color
                        dataRow.add(String.valueOf(i));             //subject position in json
                        monData.add(dataRow);
                    } else if (day.contains("Tue")) {
                        dataRow.add(courseName);                    //course name
                        dataRow.add(tStart);                        //period start
                        dataRow.add(tStop);                         //period end
                        dataRow.add(String.valueOf(subjectColor));  //subject color
                        dataRow.add(String.valueOf(i));             //subject position in json
                        tueData.add(dataRow);
                    } else if (day.contains("Wed")) {
                        dataRow.add(courseName);                    //course name
                        dataRow.add(tStart);                        //period start
                        dataRow.add(tStop);                         //period end
                        dataRow.add(String.valueOf(subjectColor));  //subject color
                        dataRow.add(String.valueOf(i));             //subject position in json
                        wedData.add(dataRow);
                    } else if (day.contains("Thu")) {
                        dataRow.add(courseName);                    //course name
                        dataRow.add(tStart);                        //period start
                        dataRow.add(tStop);                         //period end
                        dataRow.add(String.valueOf(subjectColor));  //subject color
                        dataRow.add(String.valueOf(i));             //subject position in json
                        thuData.add(dataRow);
                    } else if (day.contains("Fri")) {
                        dataRow.add(courseName);                    //course name
                        dataRow.add(tStart);                        //period start
                        dataRow.add(tStop);                         //period end
                        dataRow.add(String.valueOf(subjectColor));  //subject color
                        dataRow.add(String.valueOf(i));             //subject position in json
                        friData.add(dataRow);
                    } else if (day.contains("Sat")) {
                        dataRow.add(courseName);                    //course name
                        dataRow.add(tStart);                        //period start
                        dataRow.add(tStop);                         //period end
                        dataRow.add(String.valueOf(subjectColor));  //subject color
                        dataRow.add(String.valueOf(i));             //subject position in json
                        satData.add(dataRow);
                    } else if (day.contains("Sun")) {
                        dataRow.add(courseName);                    //course name
                        dataRow.add(tStart);                        //period start
                        dataRow.add(tStop);                         //period end
                        dataRow.add(String.valueOf(subjectColor));  //subject color
                        dataRow.add(String.valueOf(i));             //subject position in json
                        sunData.add(dataRow);
                    }
                }
            }

            if (monData.size() != 0) {
                scheduleLvItems.add(new Schedule_ListView(
                        R.drawable.monday_mdpi,
                        monData,
                        getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1)
                ));
            }
            if (tueData.size() != 0) {
                scheduleLvItems.add(new Schedule_ListView(
                        R.drawable.tuesday_mdpi,
                        tueData,
                        getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1)
                ));
            }
            if (wedData.size() != 0) {
                scheduleLvItems.add(new Schedule_ListView(
                        R.drawable.wendesday_mdpi,
                        wedData,
                        getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1)
                ));
            }
            if (thuData.size() != 0) {
                scheduleLvItems.add(new Schedule_ListView(
                        R.drawable.thursday_mdpi,
                        thuData,
                        getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1)
                ));
            }
            if (friData.size() != 0) {
                scheduleLvItems.add(new Schedule_ListView(
                        R.drawable.friday_mdpi,
                        friData,
                        getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1)
                ));
            }
            if (satData.size() != 0) {
                System.out.println("----------------------!");
                scheduleLvItems.add(new Schedule_ListView(
                        R.drawable.saturday_mdpi,
                        satData,
                        getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1)
                ));
            }
            if (sunData.size() != 0) {
                scheduleLvItems.add(new Schedule_ListView(
                        R.drawable.sunday_mdpi,
                        sunData,
                        getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1)
                ));
            }

            //add padding top - bottom for listview
            LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            LinearLayout header = (LinearLayout) inflater.inflate(R.layout.listview_header, null);
            if (lvSchedule.getHeaderViewsCount() < 1) {
                lvSchedule.addFooterView(header, null, false);
                lvSchedule.addHeaderView(header, null, false);
            }
            //setup listView Adapter
            scheduleAdapter = new Schedule_Adapter(c, R.layout.schedule_listview, scheduleLvItems);
            //setup adapter to listView
            lvSchedule.setAdapter(scheduleAdapter);
            //setup OnClickListener
            lvSchedule.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    int postion = i - lvSchedule.getHeaderViewsCount();
                    toggle(postion, true, 200);
                }
            });

            lvSchedule.post(new Runnable() {
                @Override
                public void run() {

                    String[] separated = currentPos.split(",");

                    try{
                        for (String i : separated) {
                            if (!i.equals("-1") && !i.equals("")) {
                                System.out.println("I------------------------------>" + i);
                                toggle(Integer.parseInt(i), false, 0);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });


        }catch (Exception e){
            System.out.println("RENDER 3 ERROR :: "+e);
        }
    }



    private void toggle(final int position,boolean scrollEnable,  int duration) {

        int fromHeight;
        int toHeight;

        Schedule_ListView schedule_listView = scheduleLvItems.get(position);

        int from;
        if (schedule_listView.getDayData().size() == 1){
            from = getResources().getInteger(R.integer.EXPANDED_HEIGHT_1);
        }else if(schedule_listView.getDayData().size() == 2){
            from = getResources().getInteger(R.integer.EXPANDED_HEIGHT_2);
        }else if(schedule_listView.getDayData().size() == 3){
            from = getResources().getInteger(R.integer.EXPANDED_HEIGHT_3);
        }else if(schedule_listView.getDayData().size() == 4){
            from = getResources().getInteger(R.integer.EXPANDED_HEIGHT_4);
        }else{
            from = getResources().getInteger(R.integer.EXPANDED_HEIGHT_5);
        }


        if (schedule_listView.isOpen()) {
            fromHeight = from;
            toHeight = getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1);
        } else {
            fromHeight = getResources().getInteger(R.integer.COLLAPSED_HEIGHT_1);
            toHeight = from;
        }

        toggleAnimation(schedule_listView, position, fromHeight, toHeight, scrollEnable,duration);
    }

    private void toggleAnimation(final Schedule_ListView listItem, final int position,
                                 final int fromHeight, final int toHeight, final boolean goToItem, int duration) {

        ResizeAnimation resizeAnimation = new ResizeAnimation(scheduleAdapter,listItem, 0, fromHeight, 0, toHeight,duration);
        resizeAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                listItem.setOpen(!listItem.isOpen());
                listItem.setCurrentHeight(toHeight);
                scheduleAdapter.notifyDataSetChanged();

                if (goToItem)
                    goToItem(position);
            }
        });

        listItem.getWrapper().startAnimation(resizeAnimation);
    }

    private void goToItem(final int position) {
        lvSchedule.post(new Runnable() {
            @Override
            public void run() {
                try {
                    lvSchedule.smoothScrollToPosition(position + lvSchedule.getHeaderViewsCount());
                } catch (Exception e) {
                    lvSchedule.setSelection(position + lvSchedule.getHeaderViewsCount());
                }
            }
        });
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_CONTENT, mContent);

        try {
            String a = "-1,";
            int i = 0;
            for(Schedule_ListView scLv : scheduleLvItems){
                if(scLv.isOpen()){
                    a += i + ",";
                }
                i++;
            }
            System.out.println("SAVE STATE-----------> "+a);
            outState.putString("aa", a);

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

logcat的

06-09 12:42:58.962    1061-1061/com.bis.org.auInsight D/dalvikvm﹕ GC_FOR_MALLOC freed 6371 objects / 395032 bytes in 72ms
06-09 12:42:59.031    1061-1061/com.bis.org.auInsight I/System.out﹕ RESUME STATE!!!---------------------------------------
06-09 12:42:59.041    1061-1061/com.bis.org.auInsight I/System.out﹕ [{"MIDTERM DATE":"26-02-2014","YEAR \/ SEM":"2013\/2","FINAL DATE":"29-04-2014","COURSE NAME":"ENGLISH IV","SECTION":"409","FINAL TIME":"09:00 - 12:00","COURSE ID":"BG2001","COURSE INFO":[{"DAY":"Tue.","TIME":"09:00 - 10:30  ","INSTRUCTOR":"DANIEL LEE  ONDERDONK","ROOM STUDY":"SG405"},{"DAY":"Wed.","TIME":"09:00 - 10:30  ","INSTRUCTOR":"DANIEL LEE  ONDERDONK","ROOM STUDY":"SG405"},{"DAY":"Thu.","TIME":"09:00 - 10:30  ","INSTRUCTOR":"DANIEL LEE  ONDERDONK","ROOM STUDY":"SG405"},{"DAY":"Fri.","TIME":"09:00 - 10:30  ","INSTRUCTOR":"GREGORY MARK  BORNMANN","ROOM STUDY":"SG405"}],"NO.":"1","MIDTERM ROOM":"","MIDTERM TIME":"09:00 - 11:00","FINAL ROOM":""},{"MIDTERM DATE":"05-03-2014","YEAR \/ SEM":"2013\/2","FINAL DATE":"12-05-2014","COURSE NAME":"MACROECONOMICS","SECTION":"415","FINAL TIME":"13:00 - 16:00","COURSE ID":"BG2400","COURSE INFO":[{"DAY":"Tue.","TIME":"12:00 - 13:30  ","INSTRUCTOR":"SHIH-TSE-LO","ROOM STUDY":"SM331"},{"DAY":"Thu.","TIME":"12:00 - 13:30  ","INSTRUCTOR":"SHIH-TSE-LO","ROOM STUDY":"SM331"}],"NO.":"2","MIDTERM ROOM":"","MIDTERM TIME":"15:00 - 17:00","FINAL ROOM":""},{"MIDTERM DATE":"06-03-2014","YEAR \/ SEM":"2013\/2","FINAL DATE":"02-05-2014","COURSE NAME":"SELECTED PROGRAMMING LANGUAGE","SECTION":"401","FINAL TIME":"09:00 - 12:00","COURSE ID":"BIS3618","COURSE INFO":[{"DAY":"Thu.","TIME":"13:30 - 16:30  ","INSTRUCTOR":"TANAKOM  TANTONTRAKUL","ROOM STUDY":"SC0502"}],"NO.":"3","MIDTERM ROOM":"","MIDTERM TIME":"12:00 - 14:00","FINAL ROOM":""},{"MIDTERM DATE":"04-03-2014","YEAR \/ SEM":"2013\/2","FINAL DATE":"08-05-2014","COURSE NAME":"STRATEGIC TECHNOLOGY MANAGEMENT","SECTION":"401","FINAL TIME":"09:00 - 12:00","COURSE ID":"BIS4875","COURSE INFO":[{"DAY":"Tue.","TIME":"15:00 - 16:30  ","INSTRUCTOR":"KRISEE  VIPULAKOM","ROOM STUDY":"MSM0603"},{"DAY":"Fri.","TIME":"15:00 - 16:30  ","INSTRUCTOR":"KRISEE  VIPULAKOM","ROOM STUDY":"MSM0603"}],"NO.":"4","MIDTERM ROOM":"","MIDTERM TIME":"09:00 - 11:00","FINAL ROOM":""},{"MIDTERM DATE":"27-02-2014","YEAR \/ SEM":"2013\/2","FINAL DATE":"30-04-2014","COURSE NAME":"MONEY, BANKING AND FINANCIAL MARKETS","SECTION":"422","FINAL TIME":"13:00 - 16:00","COURSE ID":"FIN2700","COURSE INFO":[{"DAY":"Wed.","TIME":"10:30 - 12:00  ","INSTRUCTOR":"PEERAWICH  THOVIRIYAVEJ","ROOM STUDY":"CL1904"},{"DAY":"Fri.","TIME":"10:30 - 12:00  ","INSTRUCTOR":"PEERAWICH  THOVIRIYAVEJ","ROOM STUDY":"CL0901"}],"NO.":"5","MIDTERM ROOM":"","MIDTERM TIME":"09:00 - 11:00","FINAL ROOM":""},{"MIDTERM DATE":"03-03-2014","YEAR \/ SEM":"2013\/2","FINAL DATE":"07-05-2014","COURSE NAME":"BUSINESS RESEARCH METHODOLOGY","SECTION":"413","FINAL TIME":"09:00 - 12:00","COURSE ID":"MGT3940","COURSE INFO":[{"DAY":"Tue.","TIME":"10:30 - 12:00  ","INSTRUCTOR":"ANYAMANEE  PHUNGPHOL","ROOM STUDY":"MSM0806"},{"DAY":"Fri.","TIME":"13:30 - 15:00  ","INSTRUCTOR":"ANYAMANEE  PHUNGPHOL","ROOM STUDY":"SM207"}],"NO.":"6","MIDTERM ROOM":"","MIDTERM TIME":"12:00 - 14:00","FINAL ROOM":""}]
06-09 12:42:59.362    1061-1061/com.bis.org.auInsight I/System.out﹕ I------------------------------>0
06-09 12:42:59.362    1061-1061/com.bis.org.auInsight D/AndroidRuntime﹕ Shutting down VM
06-09 12:42:59.362    1061-1061/com.bis.org.auInsight W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-09 12:42:59.372    1061-1061/com.bis.org.auInsight E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalStateException: Fragment ScreenSlidePageFragment{43e72068} not attached to Activity
            at android.support.v4.app.Fragment.getResources(Fragment.java:601)
            at com.bis.org.auInsight.ScreenSlidePageFragment.toggle(ScreenSlidePageFragment.java:471)
            at com.bis.org.auInsight.ScreenSlidePageFragment.access$100(ScreenSlidePageFragment.java:23)
            at com.bis.org.auInsight.ScreenSlidePageFragment$2.run(ScreenSlidePageFragment.java:439)
            at android.os.Handler.handleCallback(Handler.java:587)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:123)
            at android.app.ActivityThread.main(ActivityThread.java:4627)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:521)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
            at dalvik.system.NativeStart.main(Native Method)
06-09 12:43:00.651    1061-1061/com.bis.org.auInsight I/Process﹕ Sending signal. PID: 1061 SIG: 9

0 个答案:

没有答案