많은 데이터가 sqlite 데이터베이스, json 요청, Google지도 및 recyclerView에서 검색하는 Android 애플리케이션을 개발 중입니다.Android - 내 앱 속도를 높이려면 어떻게해야하나요?
문제는 응용 프로그램이 느리고 많은 지연이 있는지입니다. json 요청이나 어댑터에 이미 asynctask 클래스를 사용하고 있습니다. 그러나 db와 swap 리사이클 뷰의 아이템을 시간과 속도로 빠르게 가져올 수있는 방법이 있습니까?
나는 사용자 정의 로더에 대해 읽었지만, 그것이 나를 위해 유용 할 수 있는지 모르겠습니다. busUtility에서
/**
* Fragment for Bus function
*/
public class BusFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Fermata> myDataset;
public View view;
private static final String TAG_LOG = BusFragment.class.getName();
private final String MAP = "BUS";
Polyline line;
/**
* This is the request code we use for the onActivityResult management
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
/**
* The GoogleApiClient we use to interact with Location Services
*/
public GoogleApiClient mGoogleApiClient;
/**
* The last location
*/
public static volatile Location mLastLocation;
/**
* The Fragment for the Map
*/
public SupportMapFragment mMapFragment;
/**
* The handle to manage Google Map
*/
public GoogleMap mGoogleMap;
/**
* The implementation of the interface to manage CallBacks from Google Play Services
*/
private final GoogleApiClient.ConnectionCallbacks mConnectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG_LOG, "Connected");
// We update the data into the View with the first location
try {
final Location firstLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastLocation = firstLocation;
} catch (SecurityException e) {
e.printStackTrace();
}
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG_LOG, "Disconnected. Please re-connect.");
}
};
/**
* The implementation of the interface we use to manage errors from Google Play Services
*/
private final GoogleApiClient.OnConnectionFailedListener mOnConnectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// This is invoked when we have an error in Google Play Services management.
// We have to check if there is a standard resolution for this
if (connectionResult.hasResolution()) {
// In this case we launch the Intent to manage the problem
try {
connectionResult.startResolutionForResult(getActivity(),
CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
// In case Play Services cancels the Intent
e.printStackTrace();
}
} else {
// In this case there's no standard resolution for the error so we can
// only show a Dialog with the error
DialogFragment dialogFragment = new DialogFragment();
dialogFragment.show(getFragmentManager(), "Error:" + connectionResult.getErrorCode());
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(mConnectionCallbacks)
.addOnConnectionFailedListener(mOnConnectionFailedListener)
.build();
}
@Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
Log.d(TAG_LOG, "Dentro onStart");
}
@Override
public void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
/**
* Method to require Location Updates
*/
protected void startLocationUpdates() {
LocationRequest mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setSmallestDisplacement(10).setInterval(6000);
try {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
new UpdateLocationRecycler().execute();
}
});
} catch (SecurityException e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.bus_fragment,
container, false);
mMapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final GoogleMap googleMap) {
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
new getDistanceTask().execute();
startLocationUpdates();
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
if (line != null) {
line.remove();
}
ArrayList<String> mark = new ArrayList<String>();
mark.add(JsonUtility.createJsonUrl(mLastLocation,LocationUtility.getLocationFromLatLng(marker.getPosition()),Const.MODE_WALKING));
new JSONParse().execute(mark);
return false;
}
});
}
});
}
}
);
mRecyclerView = (RecyclerView) view.findViewById(R.id.bus_stop_recycler_view);
mLayoutManager = new LinearLayoutManager(MyApplication.getAppContext());
mRecyclerView.setLayoutManager(mLayoutManager);
final BusStopAdapter mAdapter = new BusStopAdapter(myDataset,mRecyclerView);
mRecyclerView.setAdapter(mAdapter);
return view;
}
/**
* AsyncTask class to manage json request
*/
public class JSONParse extends AsyncTask<ArrayList<String>, String, ArrayList<JSONObject>> {
@Override
protected ArrayList<JSONObject> doInBackground(ArrayList<String>... args) {
ArrayList<JSONObject> array = new ArrayList<>();
for (int i = 0; i < args[0].size(); i++) {
array.add(JsonUtility.getJSONFromUrl(args[0].get(i)));
}
return array;
}
@Override
protected void onPostExecute(ArrayList<JSONObject> array) {
ArrayList<List<LatLng>> list = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
JSONObject json = array.get(i);
list.add(PolylineUtility.listPolyline(json.toString()));
}
PolylineUtility.drawPath(list,mGoogleMap);
}
}
private class getDistanceTask extends AsyncTask<Void, String, BusStopAdapter> {
ProgressBar mProgressBar;
TextView mLoading;
@Override
protected void onPreExecute() {
super.onPreExecute();
mRecyclerView = (RecyclerView) view.findViewById(R.id.bus_stop_recycler_view);
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
mLoading = (TextView) view.findViewById(R.id.loading);
}
@Override
protected BusStopAdapter doInBackground(Void... params) {
publishProgress("Loading...");
BusUtility busUtility = new BusUtility();
myDataset = SplashScreenActivity.fermatas;
final BusStopAdapter mAdapter = new BusStopAdapter(myDataset,mRecyclerView);
return mAdapter;
}
@Override
protected void onPostExecute(BusStopAdapter mAdapter) {
super.onPostExecute(mAdapter);
mRecyclerView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mLoading.setVisibility(View.GONE);
View progress = view.findViewById(R.id.loading_layout);
((ViewGroup) progress.getParent()).removeView(progress);
mRecyclerView.setAdapter(mAdapter);
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
mLoading.setText(values[0]);
}
}
private class UpdateLocationRecycler extends AsyncTask<Void, ProgressBar, List<Fermata>> {
private ProgressBar mProgressBar;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar = (ProgressBar) view.findViewById(R.id.progess_update);
}
@Override
protected List<Fermata> doInBackground(Void... params) {
publishProgress(mProgressBar);
BusUtility busUtility = new BusUtility();
myDataset = busUtility.dist(mLastLocation);
return myDataset;
}
@Override
protected void onPostExecute(List<Fermata> newData) {
super.onPostExecute(newData);
final BusStopAdapter mAdapter = new BusStopAdapter(myDataset,mRecyclerView);
mRecyclerView.setAdapter(mAdapter);
mAdapter.swapItems(newData);
mProgressBar.setVisibility(View.GONE);
}
@Override
protected void onProgressUpdate(ProgressBar... values) {
super.onProgressUpdate(values);
values[0].setVisibility(View.VISIBLE);
mGoogleMap.clear();
LocationUtility.addMarkerBusStop(mGoogleMap);
}
}
}
저는 버스 정류장에 currentLocation의 거리 및 시간을 계산하고 textViews이 데이터 세트 어댑터라고 불리는 방법이있다. 모든 버스 정류장은 로컬 sqlite3 데이터베이스에 저장됩니다. 요약
public String[] getArray(Fermata currentItem) throws JSONException, ExecutionException, InterruptedException {
return JsonUtility.getDistanceTime(new JSONParse().execute(currentItem).get());
}
: 나 근처의 버스 정류장 (나는 하버 사인 공식을 사용)를 얻을, JSON이 버스 정류장에 나까지의 거리를 계산하고 recyclerview에 모든 데이터를 설정합니다.
문제는 recyclerview 및 구글지도가 매우 느린이며 많이 지연 있다는 것입니다. (많은 요청이 Google에?)
정말 정말 당신의 앱 잘못 무엇을 말할 수 없다하지만 난 당신에게 줄 수
. 가장 효율적인 방법으로 데이터를 가져 오는 것을 나는 모릅니다. 더 작은 조각 만 필요할 때 거대한 데이터 세트를 가져오고 있다는 것을 나는 모른다. 시도를 게시하지 않으면 도움을받을 수 없습니다. – DejaVuSansMono
@DejaVuSansMono ok 죄송합니다. 유용 할 수있는 여행이 있는지를 알기 위해 일반적인 질문을했습니다. 예를 들어 db에 대한 연결은 모델 객체를 만들기 위해 커서가있는 정적 dbOpenHelper로 이루어집니다. 나는 가능한 빨리 코드를 게시 할 것이다. – Fidelis
@DejaVuSansMono 내 편집을 확인하십시오. 고맙습니다. – Fidelis