这是我的代码:
package com.saba.admin.w2track;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import Adapters.VehicleListAdapter;
import Model.UserData;
import Model.VehicleData;
public class DashboardActivity extends AppCompatActivity {
static ArrayList<VehicleData> vehicleArrayList=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayList1=new ArrayList<>();
boolean clearflag=false;
static ArrayList<VehicleData> vehicleArrayListMoving=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListStopped=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListActive=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListInActive=new ArrayList<>();
String acctype;
//static VehicleListAdapter listAdapter;
UserData userData;
TextView txtStopped,txtMoving,txtTotal,txtInactive,txtAlerts;
RelativeLayout moving,alerts,inactive,stopped,total;
boolean doubleBackToExitPressedOnce = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard3);
setView();
getBundleData();
// String acc[]={acctype};
updateVehicles();
}
public void updateVehicles() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
DashboardActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
vehicle v = new vehicle();
v.execute(acctype);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000);
}
public void setView(){
txtStopped=(TextView)findViewById(R.id.txtstopped);
txtMoving=(TextView)findViewById(R.id.txtmoving);
txtAlerts=(TextView)findViewById(R.id.txtalerts);
txtInactive=(TextView)findViewById(R.id.txtinactive);
txtTotal=(TextView)findViewById(R.id.txttotal);
moving=(RelativeLayout)findViewById(R.id.LayoutMoving);
stopped=(RelativeLayout)findViewById(R.id.LayoutStopped);
alerts=(RelativeLayout)findViewById(R.id.LayoutAlerts);
inactive=(RelativeLayout)findViewById(R.id.LayoutInActive);
total=(RelativeLayout)findViewById(R.id.LayoutTotal);
}
public void getBundleData(){
Bundle b = getIntent().getExtras();
if (b != null && b.containsKey("userData"))
{
userData=b.getParcelable("userData");
acctype=b.getString("acctype");
// Log.d("accountid",userData.getAccountId()+" ");
Log.d("userid123..",userData.getUserId()+" ");
Log.d("timediff123..",userData.getTimediff()+" ");
//Log.d("km1..",userData.getMilesPerKms()+" ");
}
}
//仪表板中的车辆asyncclass ...每隔30秒在仪表板中调用一次以获取更新的数据&amp;存放在arraylist。
private class vehicle extends AsyncTask<String,String,String> {
private ProgressDialog dialog;
String response="";
private JSONObject res;
@Override
protected void onPreExecute() {
super.onPreExecute();
try {
if(!DashboardActivity.this.isFinishing()) {
dialog = new ProgressDialog(DashboardActivity.this);
dialog.setMessage("Please Wait..");
dialog.setCancelable(false);
// searchBox.setEnabled(false);
dialog.show();
}
if(true) {
vehicleArrayList.clear();
vehicleArrayList1.clear();
vehicleArrayListMoving.clear();
vehicleArrayListStopped.clear();
vehicleArrayListActive.clear();
vehicleArrayListInActive.clear();
Log.d("cleared1111", "cleared ");
clearflag=true;
}
}catch (Exception e){
Log.d("eroror1111", e.toString() + " ");
// Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_SHORT).show();
}
}
@Override
protected String doInBackground(String... params) {
try {
JSONObject vehicle_json = new JSONObject();
vehicle_json.put("pAccountId", userData.getUserId());
res = CustomHttpClient.postJsonObject("http://"+params[0]+".w2track.com/api/index.php?cmd=vehicles", vehicle_json,DashboardActivity.this);
String resData=res.getString("ResponseData");
JSONArray array=new JSONArray(resData);
Log.d("1111",array.length()+" ");
for(int i=0;i<array.length();i++){
Log.d("11112","2222");
VehicleData vehicleData=new VehicleData();
JSONObject jsonVehicleObj=new JSONObject(array.get(i).toString());
Log.d("111123", "2222");
if(jsonVehicleObj.getString("vehiclenumber").equals("null") ||jsonVehicleObj.getString("vehiclenumber")==null ){
Log.d("111124","2222");
continue;
// Log.d("11112","2222");
}
vehicleData.setVehicleNumber(jsonVehicleObj.getString("vehiclenumber"));
vehicleData.setPlacename(jsonVehicleObj.getString("location"));
vehicleData.setSpeed(jsonVehicleObj.getString("speed"));
vehicleData.setLandmark(jsonVehicleObj.getString("landmark"));
vehicleData.setIsActive(jsonVehicleObj.getBoolean("isactive"));
vehicleData.setVehicleType(jsonVehicleObj.getString("vehicletype"));
vehicleData.setFuel(jsonVehicleObj.getString("fuel"));
Log.d("fuel11115", vehicleData.getFuel() + " ");
vehicleData.setDept(jsonVehicleObj.getString("department"));
vehicleData.setDivision(jsonVehicleObj.getString("division"));
vehicleData.setIginition(jsonVehicleObj.getString("ignition"));
vehicleData.setLati(jsonVehicleObj.getString("lat"));
vehicleData.setLongi(jsonVehicleObj.getString("lng"));
vehicleData.setOdometer(jsonVehicleObj.getString("odometer"));
vehicleData.setGpsmode(jsonVehicleObj.getString("gpsmode"));
vehicleData.setInnerbattery(jsonVehicleObj.getDouble("inbatt"));
vehicleData.setExtbattery(jsonVehicleObj.getDouble("extbatt"));
vehicleData.setUnitId(jsonVehicleObj.getString("unitid"));
vehicleData.setUnitNo(jsonVehicleObj.getString("unitno"));
vehicleData.setIgnitionTime(jsonVehicleObj.getString("ign_time"));
vehicleData.setDate1(jsonVehicleObj.getString("date"));
vehicleData.setIconImage(jsonVehicleObj.getString("icon"));
vehicleData.setSignal(jsonVehicleObj.getString("signal"));
Log.d("111126", "2222");
if(clearflag) {
vehicleArrayList.add(vehicleData);
vehicleArrayList1.add(vehicleData);
Log.d("111127", "2222");
if (vehicleData.getIginition().equals("Off") && vehicleData.isActive()) {
vehicleArrayListStopped.add(vehicleData);
vehicleArrayListActive.add(vehicleData);
} else if (vehicleData.getIginition().equals("On") && vehicleData.isActive()) {
vehicleArrayListMoving.add(vehicleData);
vehicleArrayListActive.add(vehicleData);
} else if (!vehicleData.isActive()) {
vehicleArrayListInActive.add(vehicleData);
}
}
Log.d("vehicleno1111",vehicleData.getVehicleNumber()+" ");
}
clearflag=false;
// JSONObject jsonObject1=new JSONObject(array.get(0).toString());
// response=jsonObject1.toString();
//Log.d("myresponse",response+" ");
}catch (Exception e){
Log.d("errorrrr1111", e.toString());
}
return response;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
txtTotal.setText("Total ("+ vehicleArrayList.size()+")");
txtMoving.setText("Moving ("+ vehicleArrayListMoving.size()+")");
txtStopped.setText("Stopped ("+vehicleArrayListStopped.size()+")");
// txtAlerts.setText(jsonObject.getString("TotalActive"));
txtInactive.setText("InActive (" + vehicleArrayListInActive.size() + ")");
if(!DashboardActivity.this.isFinishing()) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
// dashboard activty每30秒拨打一次车辆服务&amp;存储在不同的arraylist像移动,停止等我正在使用那个arraraylist&amp;设置适配器&amp;在车辆活动中呼叫notifydatasetchange(每10秒)
VehicleList class
public class VehicleList extends android.support.v4.app.Fragment {
Runnable r;
Timer timer;
TimerTask myTimerTask;
ListView lstVehicle;
EditText searchBox;
static String status;
// Context context;
VehicleListActivityFinal vehicleListActivityFinal;
ImageView img;
static UserData userData;
int accid,timdiff,mile;
String userid,acctype;
VehicleListAdapter listAdapter;
final Handler handler =new Handler() ;
VehicleListActivityFinal vehiclefinal;
}*/
public VehicleList() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("oncreate..", "oncreate..");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_vehicle_list, container, false);
//vehicleArrayList =new ArrayList<VehicleData>();
lstVehicle =(ListView)view.findViewById(R.id.vehicle_listview);
// lstVehicle.requestFocus();
img=(ImageView)view.findViewById(R.id.Imgnodata);
Log.d("createview", "createview");
if (getArguments() != null) {
// Bundle bundle=getArguments();
userid=getArguments().getString("UserID");
acctype=getArguments().getString("acctype");
timdiff=getArguments().getInt("TimeDiff");
status=getArguments().getString("status");
Log.d("arg1111",userid+" ");
Log.d("arg11112",timdiff+" ");
}
else
{
Log.d("insidenull","nullnull");
}
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
vehicleListActivityFinal=(VehicleListActivityFinal)getActivity();
searchBox=(EditText)vehicleListActivityFinal.findViewById(R.id.searchBox);
Log.d("onactivitycrated..", "activitycreated...");
if(savedInstanceState==null) {
if (CheckInternet.isConnectionAvailable(vehicleListActivityFinal)) {
getVehicleData();
updateVehicleData();
} else {
CheckInternet.showNoInternet(vehicleListActivityFinal);
}
}
Log.d("testtest", vehicleListActivityFinal.test + " ");
lstVehicle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
VehicleData vehicleData = (VehicleData) parent.getAdapter().getItem(position);
Intent intent = new Intent(vehicleListActivityFinal, VehicleDetailActivity.class);
intent.putExtra("vehicleData1", vehicleData);
intent.putExtra("acctype", acctype);
// intent.putExtra()
startActivity(intent);
vehicleListActivityFinal.overridePendingTransition(R.anim.push_in, R.anim.push_out);
}catch (Exception e){
Toast.makeText(vehicleListActivityFinal,e.toString(),Toast.LENGTH_SHORT).show();
}
}
});
searchText();
// updateVehicleData();
// setRetainInstance(true);
}
//在车辆活动中每隔10秒调用notifydatasett的方法
public void updateVehicleData(){
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
vehicleListActivityFinal.runOnUiThread(new Runnable() {
public void run() {
try {
// getVehicleData();
img.setVisibility(View.GONE);
listAdapter.notifyDataSetChanged();
lstVehicle.invalidate();
if (lstVehicle.getAdapter().getCount() == 0) {
img.setVisibility(View.VISIBLE);
Toast.makeText(vehicleListActivityFinal, "empty list..", Toast.LENGTH_SHORT).show();
}
Toast.makeText(vehicleListActivityFinal, "Refreshing Data..", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000);
}
将车辆适配器设置为车辆活动的方法
public void getVehicleData(){
// lstVehicle.requestFocus();
if(VehicleListActivityFinal.movingStatus.equals("moving")) {
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListMoving,vehicleListActivityFinal);
// Log.d("adapterempty", listAdapter.isEmpty()+" ");
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("total")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayList1,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("inactive")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListInActive,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("stopped")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListStopped,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
// listAdapter.notifyDataSetChanged();
}
else
{
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayList1,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
// listAdapter.notifyDataSetChanged();
}
// lstVehicle.invalidate();
//lstVehicle.requestLayout();
Log.d("postexecute1111", searchBox.isFocused() + " ");
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
VehicleListActivityFinal.currentFragment="VehicleList";
}
@Override
public void onDetach() {
super.onDetach();
Log.d("detach1", "detach");
}
@Override
public void onResume() {
super.onResume();
Log.d("onresume", "onresume");
}
public void searchText() {
// lstVehicle.setAdapter(listAdapter);
searchBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Toast.makeText(vehicleListActivityFinal,"beforetextchanged",Toast.LENGTH_SHORT).show();
}
@Override
public void onTextChanged(CharSequence s1, int start, int before, int count) {
listAdapter.getFilter().filter(s1.toString());
// Toast.makeText(getActivity(),"ontextchanged",Toast.LENGTH_SHORT).show();
//lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
@Override
public void afterTextChanged(Editable s) {
//Toast.makeText(getActivity(),"afterrtextchanged",Toast.LENGTH_SHORT).show();
}
});
}
}