Answer the question
In order to leave comments, you need to log in
Where to insert SharedPreferences?
I am writing a program similar to the "Magic Ball" from the movie "Track 60".
I can't figure out which and where to insert the SharedPreferences code.
It is necessary that after the application is closed, the timer does not stop working.
The code:
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity<time> extends AppCompatActivity {
//Объявим переменные компонентов
Button button;
TextView textView;
TextView mTimer;
SharedPreferences nTime;
//Переменная для работы с БД
private BDGuru mDBHelper;
private SQLiteDatabase mDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHelper = new BDGuru(this);
try {
mDBHelper.updateDataBase();
} catch (IOException mIOException) {
throw new Error("UnableToUpdateDatabase");
}
try {
mDb = mDBHelper.getWritableDatabase();
} catch (SQLException mSQLException) {
throw mSQLException;
}
//Найдем компоненты в XML разметке
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
mTimer = (TextView) findViewById(R.id.mTimer);
//Клик по кнопке
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
String product = "";
Cursor cursor = mDb.rawQuery("SELECT * FROM Guru ORDER BY RANDOM() LIMIT 1;", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
product = cursor.getString(1);
cursor.moveToNext();
}
cursor.close();
textView.setText(product);
v.setVisibility(View.GONE);
int _12HoursInMilSecs = 12 * 60 * 60 * 1000;
v.postDelayed(new Runnable() {
public void run() {
v.setVisibility(View.VISIBLE);
}
}, _12HoursInMilSecs);
new CountDownTimer(_12HoursInMilSecs,1000) {
public void onTick(long millisUntilFinished) {
mTimer.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTimer.setText("");
}
}
.start();
}
});
}
}
Answer the question
In order to leave comments, you need to log in
The timer and preferences have nothing to do with each other.
Posting in the ui event loop for 12 hours is very powerful, of course. That's not how it's done. Look towards AlarmManager'a.
You can't go to the ui-thread database.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question