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

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);
}
}

Related

Sharedpref data on destroy

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.

how to Update ListView after deletion

Here I'm using Custom Adapter by implementing listAdapter to Support buttons in the list items. When i click the Delete button it deletes currect row. But i can't able to refresh this listView.
File Structure is MainActivity -> FragmentClass-> this Custom class for the listAdpater.
public class Category_ListView_Custom_Adapter extends BaseAdapter implements ListAdapter{
private Realm realm;
private ArrayList<String> list = new ArrayList<>();
private Context context;
public Category_ListView_Custom_Adapter(ArrayList<String> list, Context context){
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View view1 = view;
realm = Realm.getDefaultInstance();
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.category_listview_row, null);
}
TextView listItemText = (TextView) view.findViewById(R.id.item);
listItemText.setText(list.get(i));
ImageView edit = (ImageView) view.findViewById(R.id.image);
ImageView delete = (ImageView) view.findViewById(R.id.delete);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// list.remove(i);
/// Toast.makeText(view.getContext(), "hey "+list.get(i).toString(), Toast.LENGTH_SHORT).show();
// notifyDataSetChanged();
Intent intent = new Intent(context, AddCategory.class);
intent.putExtra("category","expense");
intent.putExtra("subcategory", list.get(i));
context.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RealmResults<Category> categorylist = realm.where(Category.class).equalTo("Id",i+1).and().equalTo("Subcategory",list.get(i)).findAll();
for (Category category : categorylist) {
realm.beginTransaction();
categorylist.deleteFirstFromRealm();
realm.commitTransaction();
try {
context.notifyAll();
}catch (Exception e){
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
// Expense.call_resume
}
}
});
return view;
}
}
Please Help me. Thank you.
You are .removing from a wrong view. Try to make root List<> static and do Class.list.get(i).remove or something like that.
Also, try to hide a view inside your get view.

How to detect recent button in android 8.1.0

I want to detect recent button but in android 8.1.0 it's not working.Below code is working on another version of android but in 8.1.0 the Intent.ACTION_CLOSE_SYSTEM_DIALOGS broadcast is not calling.I am using below implementation.
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter();
mFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
mFilter.addAction("");
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
and in class, I am calling using below code.
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.startWatch();
Please help!.
Edited----
The above code is working properly in normal flow but when the screen pinning is set(ON) then it's not working. Even i am not getting any event like KeyUp, KeyDown
com.android.systemui package will be the foreground app when you click recent app button, so find the foreground running apps and launch your page if foreground running app is 'com.android.systemui'.
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
// do something here...
}
#Override
public void onHomeLongPressed() {
}
});
mHomeWatcher.startWatch();
For a detailed Answer Check
Detect Home And Recent App Button
Please use below code
`#Override
public boolean dispatchKeyEvent(KeyEvent event) {
Log.i("key pressed", String.valueOf(event.getKeyCode()));
return super.dispatchKeyEvent(event);
}`

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