Am new For Android am having doubt regarding how to unregister ForceLoadContentObserver in onDestroy method Here let me explain my problem briefly i use cursolader and Cursor recyclerviewadapter for whenever data changes in sqlite db but i feel like am leaking memory because am not unregistering the ForceLoadContentObserver how can i do this . Here Let me post my Code:
This is the activity where am using ForceLoadContentObserver:
public class Customer extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>,SearchView.OnQueryTextListener {
private static final int customer = 1;
RecyclerView recyclerView;
TimeTrackerDAO timetrackerdaoobj;
Cursor c;
String mCurFilter;
CustomerListAdapter customerlistadapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.customer_recyclerview);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
timetrackerdaoobj = new TimeTrackerDAO(getApplicationContext());
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CustomerDetails.class);
startActivity(intent);
}
});
if (getSupportActionBar()!=null) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DashBoard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
}
});
getLoaderManager().initLoader(customer, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getApplicationContext(), TimeTrackerDAO.DB_Timetracker, null, null, null, null) {
ForceLoadContentObserver mObserver = new ForceLoadContentObserver();
@Override
public Cursor loadInBackground() {
if (mCurFilter != null) {
c = timetrackerdaoobj.SearchCustomerList(mCurFilter);
} else{
c = timetrackerdaoobj.CustomerList();
if (c != null) {
c.getCount();
c.registerContentObserver(mObserver);
c.setNotificationUri(getContext().getContentResolver(), getUri());
}
}
return c;
}
};
}
@Override
public void onLoadFinished(Loader<Cursor> loader,final Cursor data) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
customerlistadapter = new CustomerListAdapter(getApplicationContext(), data);
recyclerView.setAdapter(customerlistadapter);
customerlistadapter.setOnItemClickListener(new CustomerListAdapter.OnItemClickListener() {
@Override
public void onItemClicked(Cursor cursor) {
Integer webid=cursor.getInt(cursor.getColumnIndex(CustomerModel.Customer_WebID));
if(webid<=0){
Toast.makeText(getApplicationContext(),"Please Sync The Data Before Editing",Toast.LENGTH_SHORT).show();
}
else {
Integer id = cursor.getInt(cursor.getColumnIndex(CustomerModel.CustomerPrimaryID));Bundle bundle = new Bundle();
String CreatedDateTime=cursor.getString(cursor.getColumnIndex(CustomerModel.Customer_CreatedAt
));
Integer timeflag=cursor.getInt(cursor.getColumnIndex(CustomerModel.Customer_TimeFlag));
Integer Createdby=cursor.getInt(cursor.getColumnIndex(CustomerModel.Customer_CreateByID));
String Createdbyname=cursor.getString(cursor.getColumnIndex(CustomerModel.Customer_CreatedBy));
bundle.putInt("webid",webid);
bundle.putInt("customerid", id);
bundle.putInt("createdbys",Createdby);
bundle.putInt("timeflag",timeflag);
bundle.putString("createdbyname",Createdbyname);
bundle.putString("createdby",CreatedDateTime);
Intent intent = new Intent(getApplicationContext(), CustomerView.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
});}});
customerlistadapter.swapCursor(data);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
customerlistadapter.swapCursor(null);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.sync, menu);
MenuItem searchItem = menu.findItem(R.id.searchcustomer);
SearchView msearchview=(SearchView) MenuItemCompat.getActionView(searchItem);
msearchview.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
OnClick();
return true;
case R.id.searchcustomer:
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
getLoaderManager().restartLoader(0, null, this);
return false;
}
public class CustomerDetail extends AsyncTask<String, String, String> {
String JsonResponse = null;
@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String JsonDATA = params[0];
byte[] post = JsonDATA.getBytes();
int request_post = post.length;
BufferedReader reader = null;
try {
Thread.sleep(2000);
URL url = new URL("http://xxx");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "utf-8");
urlConnection.setRequestProperty("Content-Length", Integer.toString(request_post));
urlConnection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(JsonDATA);
writer.close();
int response = urlConnection.getResponseCode();
if (response >= 400 && response <= 499) {
Log.e("", "HTTPx Response: " + response + " - " + urlConnection.getResponseMessage());
InputStream in = new BufferedInputStream(urlConnection.getErrorStream());
}
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
Log.i("response", JsonResponse);
return JsonResponse;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("", "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
CustomerModel customerModel=new CustomerModel();
try {
JSONArray jsonArray=new JSONArray(s);
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject=jsonArray.getJSONObject(i);
int webid=jsonObject.getInt("WebID");
int appid=jsonObject.getInt("AppID");
customerModel.setFlag(0);
customerModel.setCustomerID(webid);
customerModel.setID(appid);
timetrackerdaoobj.UpdateWebCustomer(customerModel);
customerlistadapter.addModelClass(customerModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class CustomerUpdate extends AsyncTask<String, String, String> {
String JsonResponse = null;
@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String JsonDATA = params[0];
byte[] post = JsonDATA.getBytes();
int request_post = post.length;
BufferedReader reader = null;
try {
Thread.sleep(2000);
URL url = new URL("xxx");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "utf-8");
urlConnection.setRequestProperty("Content-Length", Integer.toString(request_post));
urlConnection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(JsonDATA);
writer.close();
int response = urlConnection.getResponseCode();
if (response >= 400 && response <= 499) {
Log.e("", "HTTPx Response: " + response + " - " + urlConnection.getResponseMessage());
InputStream in = new BufferedInputStream(urlConnection.getErrorStream());
}
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
Log.i("response", JsonResponse);
if(JsonResponse.contains("Success")){
timetrackerdaoobj.UpdateCustomer();
}
return JsonResponse;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("", "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
public class CustomerList extends AsyncTask<String, Void, Void> {
ProgressDialog Dialog = new ProgressDialog(Customer.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
Dialog.setMessage("Syncing Please Wait");
Dialog.show();
}
@Override
protected Void doInBackground(String... params) {
RequestQueue queuess = Volley.newRequestQueue(getApplicationContext());
JsonArrayRequest jsonObjRequestss = new JsonArrayRequest(Request.Method.GET, params[0], new JSONArray(),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
String server_response = response.toString();
try {
CustomerModel customerModel=new CustomerModel();
JSONArray jsonArray = new JSONArray(server_response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
customerModel.setCustomerID(jsonObject.getInt("CustomerID"));
String customername=jsonObject.getString("CustomerName");
String customerName=customername.substring(0, 1).toUpperCase() + customername.substring(1);
customerModel.setCustomerName(customerName);
customerModel.setMobileNumber(jsonObject.getString("MobileNo"));
customerModel.setPhoneNumber(jsonObject.getString("PhoneNo"));
customerModel.setEmailID(jsonObject.getString("EmailID"));
customerModel.setCreatedat(jsonObject.getString("CreatedDatetime"));
customerModel.setLastModifiedAt(jsonObject.getString("LastModifiedDatetime"));
int id=jsonObject.getInt("Status");
customerModel.setTimeFlag(1);
customerModel.setCreatedBy(jsonObject.getInt("CreatedBy"));
customerModel.setLastModifiedBy(jsonObject.getInt("LastModifiedBy"));
if(id==1){
customerModel.setStatus("Active");
customerModel.setStatusID(1);
}
else{
customerModel.setStatus("In Active");
customerModel.setStatusID(0);
}
String datetime=jsonObject.getString("LastModifiedDatetime");
customerModel.setLastModifiedFlag(datetime);
timetrackerdaoobj.CustomerInsertorUpdate(customerModel);
customerlistadapter.addModelClass(customerModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "");
}
});
//Creating request queue
queuess.add(jsonObjRequestss);
return null;
} @Override
protected void onPostExecute(Void modleobjs) {
super.onPostExecute(modleobjs);
Dialog.hide();
}
}
public void OnClick(){
this.runOnUiThread(new Runnable() {
@Override
public void run() {
String datetime=timetrackerdaoobj.DateTime();
String CustomerListUrl="http://172.16.7.55:8080/Rest/TimeTracker/restcustomergetlistbydate/ " + datetime;
if(datetime.equals("")){
new CustomerList().execute(CustomerListUrl);
Log.d("url", CustomerListUrl);
}
else{
CustomerListUrl=CustomerListUrl.replace(" ", "%20");
new CustomerList().execute(CustomerListUrl);
Log.d("url", CustomerListUrl);
}
List<CustomerModel> listobj;
listobj = timetrackerdaoobj.Listtoserver();
Gson gson = new Gson();
String gsonString = gson.toJson(listobj);
int id=timetrackerdaoobj.getServerCunt();
int updateid=timetrackerdaoobj.getUpdateCount();
List<CustomerModel>listupdatted;
listupdatted=timetrackerdaoobj.EditListtoserver();
String gsonupdatestring=gson.toJson(listupdatted);
if(updateid>0){
new CustomerUpdate().execute(gsonupdatestring);
}
if(id>0) {
new CustomerDetail().execute(gsonString);
}
else{
Log.d("no records","No Records");
}
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), DashBoard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
Here is the CursorRecyclerViewAdapter:
package Adapters;
public abstract class CursorRecycleViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
private Context mContext;
private Cursor mCursor;
private boolean mDataValid;
private int mRowIdColumn;
private DataSetObserver mDataSetObserver;
public CursorRecycleViewAdapter(Context context, Cursor cursor) {
mContext = context;
mCursor = cursor;
mDataValid = cursor != null;
mRowIdColumn = mDataValid ? mCursor.getColumnIndex("_id") : -1;
mDataSetObserver = new NotifyingDataSetObserver();
if (mCursor != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
}
public Cursor getCursor() {
return mCursor;
}
@Override
public int getItemCount() {
if (mDataValid && mCursor != null) {
return mCursor.getCount();
}
return 0;
}
public Cursor getItem(final int position) {
if (this.mCursor != null && !this.mCursor.isClosed()) {
this.mCursor.moveToPosition(position);
}
return this.mCursor;
}
@Override
public long getItemId(int position) {
if (mDataValid && mCursor != null && mCursor.moveToPosition(position)) {
return mCursor.getLong(mRowIdColumn);
}
return 0;
}
@Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(true);
}
public abstract void onBindViewHolder(VH viewHolder, Cursor cursor);
@Override
public void onBindViewHolder(VH viewHolder, int position) {
if (!mDataValid) {
throw new IllegalStateException("this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
onBindViewHolder(viewHolder, mCursor);
}
/**
* Change the underlying cursor to a new cursor. If there is an existing cursor it will be
* closed.
*/
public void changeCursor(Cursor cursor) {
Cursor old = swapCursor(cursor);
if (old != null) {
old.close();
}
}
/**
* Swap in a new Cursor, returning the old Cursor. Unlike
* {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
* closed.
*/
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
final Cursor oldCursor = mCursor;
if (oldCursor != null && mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
mCursor = newCursor;
if (mCursor != null) {
if (mDataSetObserver != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
mRowIdColumn = newCursor.getColumnIndexOrThrow("_id");
mDataValid = true;
notifyDataSetChanged();
} else {
mRowIdColumn = -1;
mDataValid = false;
notifyDataSetChanged();
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
return oldCursor;
}
private class NotifyingDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
super.onChanged();
mDataValid = true;
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
mDataValid = false;
notifyDataSetChanged();
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
}
}
Is it the efficient way my primay doubt is how to unregister the ContentObsever used in my activity One More info am not using Content Provider
Aucun commentaire:
Enregistrer un commentaire