Sharedpref data on destroy - android-studio

i have created a project in which i have multiple activities in which i am using sharedpref for each activity,and i am clearing my editors or sharedperf values in on Destroy but its not working for me.I want that my activity should run from activity1 < activity2 < activity3 < activity4 and on back press it works fines from activity4
private void saveData() {
sharedPreferences = getSharedPreferences("shared_preferenc", MODE_PRIVATE);
editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(last_Year_list);
editor.putString("task_list1", json);
editor.putString("farmer_id1",farmerID);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared_preferenc", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task_list1", null);
farmerID = sharedPreferences.getString("farmer_id1",farmerID);
Type type = new TypeToken<ArrayList<last_year_list>>() {
}.getType();
last_Year_list = gson.fromJson(json, type);
if (last_Year_list == null) {
last_Year_list = new ArrayList<>();
}else{
buildRecyclerView();
linearLayout = findViewById(R.id.linear1231);
linearLayout.setVisibility(View.VISIBLE);
}
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences = getSharedPreferences("shared_preferenc", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
#Override
protected void onDestroy() {
super.onDestroy();
sharedPreferences = getSharedPreferences("shared_preferenc", Context.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = sharedPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();
if (this.mConnReceiver != null) {
unregisterReceiver(this.mConnReceiver);
}
}
I am using Flag in last activity soo that all previous activit should be destroyed Like:
inms.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // here inms is my Intent
Now after completing all process and and trying to enter new data again then its automatically load data from my sharedpref of previous data.

Related

NotifyDataSetChanged() not updating listview after closing alert dialog

In my adapter class I have created a alert dialog and added a update button to it which allows me to update the items on my list view, it updates my listview but only when I leave the page and return back to it, I have used notifydatasetchanged but it doesn't seem to work, I want it to update on the list view immediately after the dialog closing.
update button
viewHolder.btnDisplayUpdate.setText("Update");
viewHolder.btnDisplayUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateCrime(crimes);
}
});
Update method
private void updateCrime(CrimesDelete crimes){
AlertDialog.Builder popupWindow = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
View root = inflater.inflate(R.layout.dialog_update, null);
popupWindow.setView(root);
AlertDialog alertDialog = popupWindow.create();
alertDialog.show();
editLocation = (EditText)root.findViewById(R.id.editText_location);
editType = (EditText)root.findViewById(R.id.editText_type);
editDescription = (EditText)root.findViewById(R.id.editText_description);
editDate = (EditText)root.findViewById(R.id.textViewDate);
editTime = (EditText)root.findViewById(R.id.textViewTime);
Spinner spinner = (Spinner) root.findViewById(R.id.editText_rating);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getContext(), R.array.rating, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
editRating = parent.getItemAtPosition(pos).toString();
if (pos==0){
editRating = null;
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
editLocation.setText(crimes.getLOCATION());
editType.setText(crimes.getTYPE());
editDescription.setText(crimes.getDESCRIPTION());
editDate.setText(crimes.getDATE());
editTime.setText(crimes.getTIME());
root.findViewById(R.id.btnAdd).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String location = editLocation.getText().toString().trim();
String type = editType.getText().toString().trim();
String description = editDescription.getText().toString().trim();
String date = editDate.getText().toString().trim();
String time = editTime.getText().toString().trim();
String rating = spinner.getSelectedItem().toString().trim();
DB_CRIME.updateDate(crimes.getID(), location, type, description, date, time, rating);
loadUpdatedCrimes();
alertDialog.dismiss();
}
});
}
private void loadUpdatedCrimes() {
notifyDataSetChanged();
Toast.makeText(getContext(), "Crime has been Updated" , Toast.LENGTH_SHORT).show();
}

need to check first time opened app or not if yes go to direct main activity otherwise go to intro screen

I need to check my app intro screen is it opened first time or it's not work properly every time i opened my app it display it's not checking the app is first time opened or not...
sorry for my bad English need your help
This is my checking code:
intromanager = new Intromanager(this);
if(!intromanager.Check()){
intromanager.setFirst(false);
Intent i = new Intent(IntroActivity.this,MainActivity.class);
startActivity(i);
finish();
}
class:
public class Intromanager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context context;
public Intromanager(Context context){
this.context = context;
pref = context.getSharedPreferences("first", 0);
editor = pref.edit();
}
public void setFirst(boolean isFirst){
editor.putBoolean("check",isFirst);
editor.commit();
}
public boolean Check(){
return pref.getBoolean("check",true);
}
}
Try below code :
intromanager =new Intromanager(this);
if(intromanager.Check()){
intromanager.setFirst(false);
} else {
Intent i = new Intent(IntroActivity.this, MainActivity.class);
startActivity(i);
finish();
}
public class Intromanager {
SharedPreferences pref;
Context context;
public Intromanager(Context context){
this.context = context;
pref = context.getSharedPreferences("first", Activity.MODE_PRIVATE);
}
public void setFirst(boolean isFirst){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("check",isFirst);
editor.apply();
}
public boolean Check(){
return pref.getBoolean("check",true);
}
}

Loading image from URL to ListView

I am trying to make a list view. I did it successfully without the photos loading from url without using a custom array adapter. However how can I implement loading images from url without using a custom array adapter?
I am trying to use the working codes from this thread but it is giving an error for holder.
Error Part
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
DoctorsActivity.java
public class DoctorsActivity extends AppCompatActivity {
private JSONArray arrayAdapter;
private static final String URL_FOR_BALANCE = "http://192.168.1.28/api2/doctors.php";
String cancel_req_tag = "login";
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
Bitmap icon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctors);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_doctors);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003764")));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String pid = sharedPreferences.getString(Config.UID_SHARED_PREF, null);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_BALANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray contacts = jObj.getJSONArray("user");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String doctorTitle = c.getString("title");
String doctorName = c.getString("first_name");
String doctorSurname = c.getString("last_name");
String doctorPhoto = c.getString("photo"); //image URL
String doctorMobile = c.getString("mobile");
String doctorFullName = doctorTitle+" "+doctorName+" "+doctorSurname;
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("photo", icon);
contact.put("doctor", doctorFullName);
contact.put("mobile", doctorMobile);
// adding contact to contact list
contactList.add(contact);
}
ListAdapter adapter = new SimpleAdapter(
DoctorsActivity.this, contactList,
R.layout.activity_doctors_list_item, new String[]{"photo", "doctor",
"mobile"}, new int[]{R.id.photo,
R.id.doctor, R.id.mobile});
lv.setAdapter(adapter);
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("uid", pid);
params.put("lang", Locale.getDefault().getDisplayLanguage());
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq,cancel_req_tag);
}
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = null;
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Errore durante il download da " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
}
Why not use a 3rd party lib like https://github.com/bumptech/glide?
Relevant code:
// ...
new Glide
.with(convertView.getContext())
.load(url)
.centerCrop()
.placeholder(R.drawable.noimage)
.crossFade()
.into(bmImage);
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
// ...
For everyone who wants to have listView with images this my corrected working Custom Adapter:
public class DoctorAdapter extends ArrayAdapter<Doctors>{
ArrayList<Doctors> doctorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public DoctorAdapter(Context context, int resource, ArrayList<Doctors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
doctorList = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.photo);
holder.tvName = (TextView) v.findViewById(R.id.doctor);
holder.tvMobile = (TextView) v.findViewById(R.id.mobile);
holder.callButton = (Button) v.findViewById(R.id.btnCall);
holder.callButton.setTag(holder);
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
String message= viewHolder.tvMobile.getText().toString();
Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
}
});
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.noimage);
new DownloadImageTask(holder.imageview).execute(doctorList.get(position).getImage());
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvMobile;
public Button callButton;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

How to destroy activity without crashing the app

I`v been trying for a while to destroy activity when the home button is pressed or when the app is in background and I manage to do something with this code
#Override
protected void onPause() {
this.finish();
super.onPause();
}
and when the app runs it does not crash but after a while playing in the activity the app just goes background and crashes.
This is the activity that I`m talking about:
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL=1154;//1 second
final static long TIMEOUT=7000;
int progressValue = 0;
CountDownTimer mcountDown;
List<Question> questionPlay = new ArrayList<>();
DbHelper db;
int index=0 , score =0,thisQuestion=0,totalQuestion,CorrectAnswer;
String mode = "";
ProgressBar progressBar;
ImageView imageView;
Button btnA, btnB, btnC,btnD;
TextView txtScore,txtQuestion;
#Override
protected void onPause() {
this.finish();
super.onPause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
Bundle extra = getIntent().getExtras();
if(extra!=null)
mode =extra.getString("MODE");
db = new DbHelper(this);
txtScore = (TextView)findViewById(R.id.txtScore);
txtQuestion =(TextView)findViewById(R.id.txtQuestion);
progressBar=(ProgressBar) findViewById(R.id.progreessBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB =(Button)findViewById(R.id.btnAnswerB);
btnC = (Button)findViewById(R.id.btnAnswerC);
btnD = (Button)findViewById(R.id.btnAnswerD);
imageView = (ImageView)findViewById(R.id.question_bike);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionPlay = db.getQuestionMode(mode);
totalQuestion = questionPlay.size();
mcountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mcountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion){
thisQuestion++;
txtQuestion.setText(String.format("%d %d",thisQuestion,totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int ImageID = this.getResources().getIdentifier(questionPlay.get(index).getImage().toLowerCase(),"drawable",getPackageName());
imageView.setBackgroundResource(ImageID);
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mcountDown.start();
}
else {
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL",totalQuestion);
dataSend.putInt("CORRECT",CorrectAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mcountDown.cancel();
if (index < totalQuestion){
Button clickedButton = (Button)v;
if(clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())){
score+=1;
CorrectAnswer++;
showQuestion(++index);
}
else showQuestion(++index);
txtScore.setText(String.format("S:%d",score));
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Playing.this ,MainActivity.class) ;
startActivity(intent) ;
finish() ;
}
}
I`v tried and with this code
#Override
protected void onDestroy(){
super.onDestroy;
finish();
}
but then the second activity does not start and the app crashes again.
So what to do?

Loading spinner not showing correctly

I am trying to put a spinner while my data is loaded and UI updated so for this task I do this:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_road_details);
setTitle("Details");
startButt = (Button)findViewById(R.id.BeginJourney);
Map = (Button)findViewById(R.id.map_btn1);
boolean GreenButtState = getIntent().getBooleanExtra("GreenButtState", false);
boolean FastButtonState = getIntent().getBooleanExtra("FastButtonState", false);
AsyncTask<Void, Void, Void> LoadingTask = new AsyncTask<Void, Void, Void>()
{
ProgressDialog dialog = new ProgressDialog(RoadDetails.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Message");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
final HashMap<String, Object> trip1;
Intent intent = getIntent();
mXmlRpcUrl = intent.getStringExtra("XmlRpcUrl");
mSessionID = intent.getStringExtra("SessionID");
mGetSavedTripFunc = intent.getStringExtra("GetSavedTripFunc");
newTripID = intent.getIntExtra("newTripID", 0);
variantID = intent.getIntExtra("VariantID", 0);
Week = intent.getIntExtra("WeekState", 0);
CityName = intent.getStringExtra("NameOfCity");
Flag = intent.getIntExtra("Flag", 0);
startLatitude = intent.getDoubleExtra("startLatitude", 0.0);
startLongitude = intent.getDoubleExtra("startLongitude", 0.0);
endLatitude = intent.getDoubleExtra("endLatitude", 0.0);
endLongitude = intent.getDoubleExtra("endLongitude", 0.0);
trip1 = (HashMap<String, Object>) intent.getSerializableExtra("Variant");
variant = new Variant();
variant.Read(trip1);
startButt.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(RoadDetails.this, Localisation.class);
intent.putExtra("SessionID", mSessionID);
intent.putExtra("XmlRpcUrl", mXmlRpcUrl);
intent.putExtra("NewTripID", newTripID);
intent.putExtra("VariantID", variantID);
intent.putExtra("WeekState", Week);
intent.putExtra("NameOfCity", CityName);
intent.putExtra("Variant", (Serializable)trip1);
intent.putExtra("Flag", Flag);
intent.putExtra("startLatitude", startLatitude);
intent.putExtra("startLongitude", startLongitude);
intent.putExtra("endLatitude", endLatitude);
intent.putExtra("endLongitude",endLongitude);
startActivity(intent);
}
});
Map.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Intent intent1 = new Intent (RoadDetails.this, MapDraw.class);
Intent intent1 = new Intent (RoadDetails.this, OSMActivity.class);
intent1.putExtra("SessionID",mSessionID);
intent1.putExtra("endLatitude", endLatitude);
intent1.putExtra("endLongitude",endLongitude);
intent1.putExtra("startLatitude", startLatitude);
intent1.putExtra("startLongitude", startLongitude);
intent1.putExtra("Variant", (Serializable)trip1);
startActivity(intent1);
}
});
return null;
}
#Override
protected void onPostExecute(Void result)
{
GettingData();
this.dialog.dismiss();
}
};
LoadingTask.execute((Void[])null);
}
However when I do this there is a delay before opening the the activity that contains this code (I want the spinner to be there while the data is loaded) the spinner is not showing. There is just a delay (for the data to be loaded - lets also call it screen freeze for a 1 - 3 seconds) and thats it. What am I doing wrong? I want the spinner to show while the data is loaded and after that to be dismissed. I also what to mention that in the method GettingData(); I am changing the UI - adding Layouts dynamically, adding images etc.
try this...this will work
ProgressDialog dialog = new ProgressDialog(RoadDetails.this);
this.dialog.setMessage("Message");
this.dialog.show();
//start your asynchronous task here
load your data here
//end asynchronous task
this.dialog.dismiss();
write ProgressDialog dialog; outside AsyncTask then
call
dialog = new ProgressDialog(RoadDetails.this);
dialog.setMessage("Message");
dialog.show();
inside onPreExecute().
Hope it will help you..

Resources