在android中执行异步任务后,值不会更新

时间:2015-02-27 09:25:00

标签: java android web-services android-asynctask

这是我在DashBoard_Gujrat活动中的代码

    public class DashBoard_Gujrat extends NavigationDrawerActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);



            inflater = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View contentView = inflater
                    .inflate(R.layout.dashboard_new, null, false);



            mDrawerLayout.addView(contentView, 0);

            bar = getActionBar();

            bar.setDisplayShowHomeEnabled(true);

            try {
                dbhelper = new DatabaseHelper(this);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



            bar.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.top_header));
            yesarrow = (ImageView) findViewById(R.id.yes_arrow);
            yes_vehicle = (ImageView) findViewById(R.id.yes_vehicle);       



            ostwald_bold = Typeface.createFromAsset(getAssets(),
                    "fonts/Oswald-Bold.otf");
            ostwald_regular = Typeface.createFromAsset(getAssets(),
                    "fonts/Oswald-Regular.otf");
            roboto_light = Typeface.createFromAsset(getAssets(),
                    "fonts/Roboto-Light.ttf");
            roboto_regular = Typeface.createFromAsset(getAssets(),
                    "fonts/Roboto-Regular.ttf");
            roboto_thin = Typeface.createFromAsset(getAssets(),
                    "fonts/Roboto-Thin.ttf");

            viewPager = (ViewPager) findViewById(R.id.summarypager);

            Ylayout = (LinearLayout) findViewById(R.id.yesLayout);
            Yclick = (LinearLayout) findViewById(R.id.yLayout);
            Tclick = (LinearLayout) findViewById(R.id.tLayout);
            Tlayout = (LinearLayout) findViewById(R.id.toLayout);
            first = (ImageView) findViewById(R.id.firstimage);
            arrowtrip = (ImageView) findViewById(R.id.ontrip_arrow);


            valve6 = (ImageView) findViewById(R.id.valve6);


            today = (TextView) findViewById(R.id.todaydate);
            yesterday = (TextView) findViewById(R.id.yesterdattxt);
            stop = (TextView) findViewById(R.id.stop);
            stoptxt = (TextView) findViewById(R.id.stoptxt);
            idle = (TextView) findViewById(R.id.idle);
            idletxt = (TextView) findViewById(R.id.idletxt);
            normal = (TextView) findViewById(R.id.normal);
            normaltxt = (TextView) findViewById(R.id.normaltxt);
            overspeed = (TextView) findViewById(R.id.overspeed);
            overspeedtxt = (TextView) findViewById(R.id.overtxt);
            ontriptxt = (TextView) findViewById(R.id.ontripstxt);

            km_yesterday = (TextView) findViewById(R.id.km_yesterday);

            km_travelled_yesterday = (TextView) findViewById(R.id.KmTravelledYesterday);
            vehicle_count_yesterday = (TextView) findViewById(R.id.vehicleCountYesterday);
            no_of_trips_yesterday = (TextView) findViewById(R.id.NooftripsYesterday);

            km_yestxt = (TextView) findViewById(R.id.km_yesterday);
            comp_txt = (TextView) findViewById(R.id.comp_txt);
            vehcle_txt = (TextView) findViewById(R.id.vehicle_txt);

            stop.setTypeface(roboto_regular);
            stoptxt.setTypeface(roboto_regular);
            idle.setTypeface(roboto_regular);
            idletxt.setTypeface(roboto_regular);
            normal.setTypeface(roboto_regular);
            normaltxt.setTypeface(roboto_regular);
            overspeed.setTypeface(roboto_regular);
            overspeedtxt.setTypeface(roboto_regular);


            no_of_trips = (TextView) findViewById(R.id.NooftripsToday);


            today.setTypeface(roboto_regular);
            yesterday.setTypeface(roboto_regular);

            ontriptxt.setTypeface(roboto_regular);

            Calendar c = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
            dateformat = new SimpleDateFormat("dd/MM/yyyy");
            formattedDate = df.format(c.getTime());
            todayDate = dateformat.format(c.getTime());
            today.setText("Today, " + todayDate);

            shPreferences = getSharedPreferences(WebServiceHelper.PREFS_NAME, 0);
            shEditor = shPreferences.edit();

            connectionDetector = new ConnectionDetecter(getApplicationContext());
            isInternetPresent = connectionDetector.isConnectingToInternet();
            vdetails = new VehicleDetails();
            usernameString = shPreferences.getString("Username", "");

            telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);// get

            IMEI_Number = telephonyManager.getDeviceId();

            clientCode = shPreferences.getString("ClientCode", "");
            secretCode = shPreferences.getString("SecretCode", "");





            callAsynchronousTask();

            /*GetYesterdaysSummaryTask yTask = new GetYesterdaysSummaryTask();
            yTask.execute();*/

            adapter = new MyPagerAdapter();

            viewPager.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int position) {
                    //


                    device = vd[position].deviceId;
                    vehicle = vd[position].vehicleNo;
                    licNo = vd[position].licenseplateNo;
                    driverId = vd[position].driver_id;
                    vehicle = vd[position].vehicleId;
                    driverName = vd[position].driver;
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });

            gestureDetector = new GestureDetector(this, new MyGestureDetector());
            gestureListener = new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    Log.d(WebServiceHelper.TAG, "Gesture Detector------------->");
                    return gestureDetector.onTouchEvent(event);
                }
            };

            animMoveleft = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.moveleft);
            animMoveright = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.moveright);
            animLeft = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.move_left);
            animRight = AnimationUtils.loadAnimation(getApplicationContext(),
                    R.anim.move_right);
            km_travelled_yesterday.setVisibility(View.GONE);
            yes_vehicle.setVisibility(View.GONE);
            vehcle_txt.setVisibility(View.GONE);
            Tclick.startAnimation(animMoveright);
            Yclick.startAnimation(animMoveleft);

            Ylayout.setOnTouchListener(gestureListener);
            Tlayout.setOnTouchListener(gestureListener);

        }




        /*public void invalidate(){
            if(vdetails.outlet_status.contentEquals("1")){
                valve6.setImageResource(R.drawable.red_tanker);
            }else{
                valve6.setImageResource(R.drawable.grenn_tanker);
            }
        }*/
        // get yesterdays summary
        public class GetYesterdaysSummaryTask extends
                AsyncTask<String, Void, String> {

            ProgressDialog Dialog;

            @Override
            protected void onPreExecute() {
                Dialog = new ProgressDialog(DashBoard_Gujrat.this);
                Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
                        R.string.loading));
                Dialog.setCanceledOnTouchOutside(false);
                Dialog.show();
                Dialog.setContentView(R.layout.progress);
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                String result = "";
                // TODO Auto-generated method stub


                if (isInternetPresent) {
                    try {

                        vdetails = WebServiceHelper.getYesterdaysSummary(
                                clientCode, secretCode);

                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    result = "Success";
                } else {
                    result = "Failure";

                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                if (result.contentEquals("Success")) {
                    if (vdetails.status_login.contentEquals("success")) {

                        km_travelled_yesterday
                                .setText(vdetails.distance_travelled_yesterday);
                        km_travelled_yesterday.setTypeface(ostwald_bold);
                        vehicle_count_yesterday
                                .setText(vdetails.vehicle_count_yesterday);
                        vehicle_count_yesterday.setTypeface(roboto_regular);
                        no_of_trips_yesterday
                                .setText(vdetails.completed_trips_yesterday);
                        no_of_trips_yesterday.setTypeface(roboto_regular);
                        km_yestxt.setTypeface(roboto_regular);
                        comp_txt.setTypeface(roboto_regular);
                        vehcle_txt.setTypeface(roboto_regular);

                        GetAllvehicleSummarytask gTask = new GetAllvehicleSummarytask();
                        gTask.execute();
                    } else {
                        Toast.makeText(context, "failed", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(context, "No internet", Toast.LENGTH_LONG)
                            .show();

                }
                super.onPostExecute(result);
                Dialog.dismiss();
            }
        }


        public class GetTodaysSummaryTask extends AsyncTask<String, Void, String> {

            ProgressDialog Dialog;

            @Override
            protected void onPreExecute() {
                Dialog = new ProgressDialog(DashBoard_Gujrat.this);
                Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
                        R.string.loading));
                Dialog.setCanceledOnTouchOutside(false);
                Dialog.hide();
                Dialog.setContentView(R.layout.progress);
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                String result = "";
                // TODO Auto-generated method stub


                if (isInternetPresent) {
                    try {

                        vdetails = WebServiceHelper.getTankerSummary(clientCode,
                                secretCode);

                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    result = "Success";
                } else {
                    result = "Failure";

                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                if (result.contentEquals("Success")) {
                    Log.d(WebServiceHelper.TAG, "On Post Execute------------->");
                    //callAsynchronousTask();           
                    overspeed.setText(vdetails.overspeed_count);
                    normal.setText(vdetails.normal_count);
                    idle.setText(vdetails.idle_count);
                    stop.setText(vdetails.off_count);

                    // kmtravelled.setTypeface(roboto_regular);
                    km_yesterday.setTypeface(roboto_regular);
                    no_of_trips.setText(vdetails.on_trips_today);
                    no_of_trips.setTypeface(roboto_regular);

    //Tclick.invalidate();

                    if(vdetails.outlet_status.contentEquals("0")){
                        Log.d(WebServiceHelper.TAG, "Check Green------------->");
                        valve6.setImageResource(R.drawable.grenn_tanker);

                    }else if(vdetails.outlet_status.contentEquals("1")){
                        Log.d(WebServiceHelper.TAG, "Check Red------------->");

                        valve6.setImageResource(R.drawable.red_tanker);
                        callAsynchronousTask();
                    }

                //invalidate(); 
                } else if (result.contentEquals("Failure")) {
                    Toast.makeText(getApplicationContext(), "No data",
                            Toast.LENGTH_SHORT).show();

                }
                super.onPostExecute(result);
                Dialog.dismiss();
            }
        }





        private class MyPagerAdapter extends PagerAdapter {

            public int getCount() {
                return licenseArray.length;
            }

            public Object instantiateItem(ViewGroup collection, int position) {

                LayoutInflater inflater = (LayoutInflater) collection.getContext()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View page = inflater.inflate(R.layout.sliding_summary_page, null);
                license = (TextView) page.findViewById(R.id.licenseSummary);
                license.setTypeface(roboto_regular);
                license.setText(licenseArray[position]);
                TextView driver = (TextView) page.findViewById(R.id.driverSummary);
                ImageView img = (ImageView) page.findViewById(R.id.eng_btn);
                driver.setTypeface(roboto_regular);
                popup = (ImageView) page.findViewById(R.id.pop_button);
                TextView kmtravelledtxt = (TextView) page
                        .findViewById(R.id.kmtravelledtxt);
                kmtravelledtxt.setTypeface(roboto_regular);
                driver.setText(driverArray[position]);
                TextView km = (TextView) page.findViewById(R.id.kmSummary);
                if (KmArray[position].equals("null")) {
                    km.setText("0");
                    km.setTypeface(roboto_regular);
                } else {
                    km.setText(KmArray[position]);
                    km.setTypeface(roboto_regular);
                }
                TextView loc = (TextView) page.findViewById(R.id.locationSummary);
                loc.setText(LocArray[position]);
                loc.setTypeface(roboto_regular);
                TextView en = (TextView) page.findViewById(R.id.engineSummary);
                if (engArray[position].equals("0")) {
                    img.setImageResource(R.drawable.engine_off);
                    en.setText("OFF");
                    en.setTypeface(roboto_regular);
                } else {
                    img.setImageResource(R.drawable.engine_on);
                    en.setText("ON");
                    en.setTypeface(roboto_regular);
                }
                TextView ac = (TextView) page.findViewById(R.id.acSummary);
                if (acArray[position].equals("0")) {
                    ac.setText("OFF");
                    ac.setTypeface(roboto_regular);
                } else {
                    ac.setText("ON");
                    ac.setTypeface(roboto_regular);
                }
                device = vd[0].deviceId;
                vehicle = vd[0].vehicleId;
                licNo = vd[0].licenseplateNo;
                driverId = vd[0].driver_id;
                driverName = vd[0].driver;


                popup.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        String[] values = new String[] { "Live Tracking",
                                "Vehicle Profile", "Driver Profile" };
                        dialog = new Dialog(context);
                        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        dialog.setContentView(R.layout.vts_popup);

                        ListView lv = (ListView) dialog
                                .findViewById(R.id.list_popupmenu);

                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                context, android.R.layout.simple_list_item_1,
                                android.R.id.text1, values) {
                            @Override
                            public View getView(int position, View convertView,
                                    ViewGroup parent) {
                                // TODO Auto-generated method stub
                                View view = super.getView(position, convertView,
                                        parent);

                                TextView textView = (TextView) view
                                        .findViewById(android.R.id.text1);

                                /* YOUR CHOICE OF COLOR */
                                textView.setTextColor(Color.WHITE);
                                textView.setGravity(Gravity.CENTER);
                                return view;
                            }
                        };

                        // Assign adapter to ListView
                        lv.setAdapter(adapter);

                        // dialog_dismiss=(ImageView)dialog.findViewById(R.id.dialog_dismiss);
                        dialog.show();

                        lv.setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                                // TODO Auto-generated method stub
                                switch (position) {
                                case 0: {


                                    Intent moreView = new Intent(context,
                                            Tracking.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("device", device);
                                    bundle.putString("vehicle", vehicle);
                                    bundle.putString("License No", licNo);
                                    shEditor.putString("flag", "1").commit();
                                    moreView.putExtras(bundle);
                                    context.startActivity(moreView);
                                    // finish();
                                    break;
                                }
                                case 1: {


                                    Intent moreView = new Intent(context,
                                            Vehicle_Profile.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("device", device);
                                    bundle.putString("License No", licNo);
                                    bundle.putString("vehicle", vehicle);
                                    shEditor.putString("flag", "1").commit();
                                    moreView.putExtras(bundle);
                                    context.startActivity(moreView);

                                    break;
                                }
                                case 2: {

                                    Intent moreView = new Intent(context,
                                            DriverProfile.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("driver", driverId);
                                    bundle.putString("DriverName", driverName);
                                    shEditor.putString("flag", "1").commit();
                                    moreView.putExtras(bundle);
                                    context.startActivity(moreView);

                                    break;
                                }
                                default:
                                    break;
                                }
                            }
                        });

                    }
                });

                ((ViewPager) collection).addView(page, 0);

                return page;
            }


            @Override
            public void destroyItem(View arg0, int arg1, Object arg2) {
                ((ViewPager) arg0).removeView((View) arg2);

            }

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == ((View) arg1);

            }

            @Override
            public Parcelable saveState() {
                return null;
            }
        }

        // webservice call to get all vehicles
        public class GetAllvehicleSummarytask extends
                AsyncTask<String, Void, String> {

            ProgressDialog Dialog;

            @Override
            protected void onPreExecute() {
                Dialog = new ProgressDialog(DashBoard_Gujrat.this);
                Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
                        R.string.loading));
                Dialog.setCanceledOnTouchOutside(false);
                // Dialog.show();
                Dialog.setContentView(R.layout.progress);
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                String result = "";


                if (isInternetPresent) {
                    try {


                        vd = WebServiceHelper.getAllvehicleSummary(clientCode,
                                secretCode, usernameString, IMEI_Number,
                                formattedDate);

                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    result = "Success";
                } else {
                    result = "Failure";

                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                if (result.contentEquals("Success")) {

                    if (VehicleDetails.status_login.equals("success")) {
                        deviceArray = new String[vd.length];
                        licenseArray = new String[vd.length];
                        driverArray = new String[vd.length];
                        LocArray = new String[vd.length];
                        KmArray = new String[vd.length];
                        engArray = new String[vd.length];
                        acArray = new String[vd.length];
                        for (int i = 0; i < vd.length; i++) {
                            licenseArray[i] = vd[i].licenseplateNo;
                            driverArray[i] = vd[i].driver;
                            LocArray[i] = vd[i].location_travell;
                            KmArray[i] = vd[i].km_travelled;
                            deviceArray[i] = vd[i].deviceId;
                            engArray[i] = vd[i].en_stat;

                            acArray[i] = vd[i].ac_stat;
                        }

                        viewPager.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    } else if (VehicleDetails.status_login.equals("failed")) {
                        Toast.makeText(getApplicationContext(), "No data",
                                Toast.LENGTH_SHORT).show();

                    }


                } else if (result.contentEquals("Failure")) {
                    Toast.makeText(getApplicationContext(), "No data",
                            Toast.LENGTH_SHORT).show();
                }
                super.onPostExecute(result);
                Dialog.dismiss();
            }
        }

        // to get gesture
        class MyGestureDetector extends SimpleOnGestureListener {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                    float velocityY) {
                try {
                    if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                        return false;
                    // right to left swipe
                    if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                            && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                        first.setVisibility(View.VISIBLE);
                        overspeed.setVisibility(View.VISIBLE);
                        overspeedtxt.setVisibility(View.VISIBLE);
                        vehcle_txt.setVisibility(View.GONE);
                        yesarrow.setVisibility(View.VISIBLE);

                        /*GetTodaysSummaryTask task=new GetTodaysSummaryTask();
                        task.execute();*/

                        km_travelled_yesterday.setVisibility(View.GONE);
                        yes_vehicle.setVisibility(View.GONE);
                        // vehcle_txt.setVisibility(View.GONE);
                        Tclick.startAnimation(animMoveright);
                        Yclick.startAnimation(animMoveleft);
                    } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                            && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                        first.setVisibility(View.GONE);
                        overspeed.setVisibility(View.GONE);
                        overspeedtxt.setVisibility(View.GONE);
                        vehcle_txt.setVisibility(View.VISIBLE);
                        yes_vehicle.setVisibility(View.VISIBLE);
                        km_travelled_yesterday.setVisibility(View.VISIBLE);
                        yes_vehicle.setVisibility(View.VISIBLE);
                        // vehcle_txt.setVisibility(View.GONE);
                        km_travelled_yesterday.setVisibility(View.VISIBLE);

                        yesarrow.setVisibility(View.GONE);
                        Tclick.startAnimation(animLeft);
                        Yclick.startAnimation(animRight);
                    }
                } catch (Exception e) {
                    // nothing
                }
                return false;
            }

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
        }

        @Override
        public void onBackPressed() {

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }





        public void callAsynchronousTask() {
            //Log.d(WebServiceHelper.TAG, "Call Async Task>>>>>>>>>>.");
            final Handler handler = new Handler();
            Timer timer = new Timer();
            TimerTask doAsynchronousTask = new TimerTask() {
                @Override
                public void run() {
                    handler.post(new Runnable() {
                        public void run() {
                            try {

                                if (!isCancelled) {


                                    tTask = new GetTodaysSummaryTask();
                                    tTask.execute();
                                }

                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                            }
                        }
                    });
                }
            };

            timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 5000 ms
                                                            // ie in every 5 sec
        }





    }

这里我使用异步任务GetTadaysSummary任务来更新阀门状态,跳闸等。对于值的自动更新,我使用callasynchronous()方法每隔5秒使用一次计时器来调用GetTodaysSummaryTask。但是现场测试中的值来自于GetTodaysSummaryTask不会自动更新。只有在重新启动活动时才会更改。     我不知道是什么问题。请提前帮助我。谢谢。如果我的问题有任何不妥,请原谅我。

1 个答案:

答案 0 :(得分:0)

好像从非UI线程启动ASyncTask(此处为= TimerTask Runnable)。据我所知,ASyncTask旨在在UI线程上运行,只有doInBackground()方法在单独的线程中运行。 查看此问题/答案,了解更多信息:

Start AsyncTask in TimerTask

我也注意到了

if (VehicleDetails.status_login.equals("success"))

无法找到字符串&#34;成功&#34;在您的代码中的任何位置初始化,只有&#34;成功&#34;与资本S ...