i m making a quiz app , in my quizzActivity where qestions load i used countDowntimer so when this countdown timer is finished i m displaying alert dialog of Game over with sound , everything working fine
Problem is when my quiz is finished , i am also getting the Gameover sound in my result activity , and in MainActivity.
my QuizzActvity code
ActivityQuizBinding binding;
ArrayList<Questions> qestions;
Questions question;
CountDownTimer timer;
FirebaseFirestore database;
int correctAnswer = 0;
MediaPlayer mMediaPlayer;
int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityQuizBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
qestions = new ArrayList<>();
database = FirebaseFirestore.getInstance();
final String cateGoryID = getIntent().getStringExtra("categoryID");
database.collection("categories")
.document(cateGoryID)
.collection("questions")
.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (DocumentSnapshot snapshot : queryDocumentSnapshots) {
Questions questions = snapshot.toObject(Questions.class);
qestions.add(questions);
}
Collections.shuffle(qestions);
setNextQestions();
}
});
resetTimer();
}
void resetTimer() {
timer = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long l) {
binding.timer.setText(String.valueOf(l / 1000));
}
#Override
public void onFinish() {
new AlertDialog.Builder(QuizActivity.this)
.setIcon(R.drawable.sad)
.setTitle("Oops Game Over!")
.setCancelable(false)
.setMessage(" Please Try Again ")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivity(in);
finish();
}
}).create().show();
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(QuizActivity.this, R.raw.wrong);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(false);
mMediaPlayer.start();
}
};
}
public void CheckAnwer(TextView textView) {
String selectAnswer = textView.getText().toString();
if (selectAnswer.equals(question.getAnswer())) {
correctAnswer++;
textView.setBackground(getResources().getDrawable(R.drawable.option_right));
} else {
showAnswer();
textView.setBackground(getResources().getDrawable(R.drawable.option_wrong));
}
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(QuizActivity.this)
.setIcon(R.drawable.ic_baseline_person_24)
.setMessage("Are you sure want to Quit Game")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivity(in);
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create().show();
}
public void setNextQestions() {
if (timer != null) {
timer.cancel();
}
timer.start();
if (index < qestions.size()) {
binding.qestioncounter.setText(String.format("%d/%d", (index + 1), qestions.size()));
question = qestions.get(index);
binding.qestions.setText(question.getQestion());
binding.option1.setText(question.getOption1());
binding.option2.setText(question.getOption2());
binding.option3.setText(question.getOption3());
binding.option4.setText(question.getOption4());
index++;
} else {
reset();
Toast.makeText(this, "Quiz Finsished", Toast.LENGTH_SHORT).show();
Intent in = new Intent(QuizActivity.this, ResultActivity.class);
in.putExtra("correct_answer", correctAnswer);
in.putExtra("total", qestions.size());
startActivity(in);
}
}
void reset() {
binding.option1.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option2.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option3.setBackground(getResources().getDrawable(R.drawable.option_unselected));
binding.option4.setBackground(getResources().getDrawable(R.drawable.option_unselected));
}
void showAnswer() {
if (question.getAnswer().equals(binding.option1.getText().toString()))
binding.option1.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option2.getText().toString()))
binding.option2.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option3.getText().toString()))
binding.option3.setBackground(getResources().getDrawable(R.drawable.option_right));
else if (question.getAnswer().equals(binding.option4.getText().toString()))
binding.option4.setBackground(getResources().getDrawable(R.drawable.option_right));
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.option_1:
case R.id.option_2:
case R.id.option_3:
case R.id.option_4:
if (timer != null) {
timer.cancel();
}
TextView selected = (TextView) view;
CheckAnwer(selected);
break;
case R.id.next_btn:
reset();
setNextQestions();
break;
}
}
}
You have to stop the MediaPlayer before switching to another activity. You may use the OnActivityResult result for stopping Mediaplayer while switching between activities.
Here is the sample code:
public static final int REQUEST_CODE = 1;
Intent in = new Intent(QuizActivity.this, MainActivity.class);
startActivityForResult(in, REQUEST_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
mMediaPlayer.stop()
}
} catch (Exception ex) {
}
}
Also, make sure that you cancel the CountDownTimer before switching to another activity.
Related
hi guys im run into problem and it take 3 days and still nothing at all ;
first of all im very sorry for my poor english and apologies ;
my probelm is i can't reach the second else if in sale_ads_fragment although i setresult and started my intent im really upset and even can't sleep for this bug
thanks in advance
private void setUpActivity() {
lnContainer1.setVisibility(View.VISIBLE);
lnContainer2.setVisibility(View.GONE);
txtToolBarTitle.setText("درج آگهی");
txtSend.setText(" " + "ارسال");
//activity result
activityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Constant.RESULT_OK && result.getData() != null) {
Intent intent = result.getData();
String mid = intent.getStringExtra(Constant.KEY_ID);
String mTitle = intent.getStringExtra(Constant.KEY_TITLE);
btnChoose1.setText(mTitle);
btnChoose2.setText(mTitle);
lnContainer1.setVisibility(View.GONE);
lnContainer2.setVisibility(View.VISIBLE);
setData(mid);
}**else if (result.getResultCode()==1318) {
G.T("success");**
}
}
});
}
private void selectDialog() {
View view = G.myGLayoutInflater.inflate(R.layout.dialog_select_camera_or_gallery,null);
txtTitle_chooseImg=view.findViewById(R.id.txtTitle);
txtCamera=view.findViewById(R.id.Camera);
txtGallery=view.findViewById(R.id.chooseGallery);
txtCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
**Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
activity.setResult(1318,intent);
activity.startActivity(intent);**
alertDialog.dismiss();
}
});
txtGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// G.T("اینو نتونستم ردیفش کنم اما قول میدم درستش کنم");
alertDialog.dismiss();
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(view);
builder.setCancelable(true);
alertDialog=builder.create();
alertDialog.show();
}
}
private void setUpListeners() {
lstCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (!categories.get(i).isLastNode) {
assignArrayList(categories.get(i).getId(), false);
} else {
String mId = categories.get(i).getId();
String mTitle = categories.get(i).getTitle();
Intent intent = new Intent();
intent.putExtra(Constant.KEY_ID,mId);
intent.putExtra(Constant.KEY_TITLE,mTitle);
setResult(Constant.RESULT_OK,intent);
finish();
}
}
});
edtSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String text = edtSearch.getText().toString();
int counter = 0;
for (int i = 0; i < G.CATEGORIES.size(); i++) {
if (G.CATEGORIES.get(i).getTitle().equals(text))
{
if (counter == position) {
String mId = G.CATEGORIES.get(i).getId();
String mTitle = G.CATEGORIES.get(i).getTitle();
Intent intent = new Intent();
intent.putExtra(Constant.KEY_ID,mId);
intent.putExtra(Constant.KEY_TITLE,mTitle);
setResult(Constant.RESULT_OK,intent);
finish();
break;
} else {
counter ++;
}
}
}
}
});
}
}
I have a QR code scanner in my app and the camera stops when my AlertDialog is being displayed but restarts as soon as I move to another activity and keeps running in the background even when the app isn't in the foreground.
I have the stopCamera() and stopCameraPreview() both but it restarts and stays on as long as the app is open (both foreground and background)
Here's the code for the activity:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
private ZXingScannerView scannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
Toast.makeText(MainActivity.this, "Scanner Active", Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
}
private boolean checkPermission() {
return (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String[] permission, int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted) {
Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
displayAlertMessage("You need to allow access for both permsisions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA}, REQUEST_CAMERA);
}
}
});
return;
}
}
}
break;
}
}
#Override
public void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
if (scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
scannerView.stopCameraPreview();
}
public void displayAlertMessage(String message, DialogInterface.OnClickListener listener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", listener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
String[] a = {"ABCD", "PQR"};
String scanned = "";
#Override
public void handleResult(Result result) {
final String scanResult = result.getText();
for (int i = 0; i < 2; i++) {
if (scanResult.equals(a[i])) {
scanned = a[i];
scannerView.stopCamera();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("QR Scan");
builder.setMessage("Machine Identified!");
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent1 = new Intent(MainActivity.this, buttons.class);
startActivity(intent1);
scannerView.stopCameraPreview();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.show();
break;
} else {
Toast.makeText(this, "ERROR: Unrecognized QR Code", Toast.LENGTH_LONG).show();
scannerView.resumeCameraPreview(MainActivity.this);
}
}
}
}
"keeps running in the background even when the app isn't in the foreground" - this is due to the Activity lifecycle. Note that onDestroy() is the last method of the class Activity that is called and called only when activity is for sure destroyed.
What it means: when you move to the background onDestroy() is not called. The activity is still alive and waiting to be resumed. Your activity is still alive and it should be. Use instead of onDestroy() method called onPause(). You will reach this method if the activity is killed, and it will return back to the onResume() when appropriate.
Just overwrite onDestroy() to:
#Override
public void onPause() {
super.onPause();
scannerView.stopCamera();
scannerView.stopCameraPreview();
}
this project code belongs to the project for the blinds to purchase the items. the scanresult fetch the details to the textview and reads for them and uses gesture options to handle the app.
i created the android project byr barcode scanner and output as textview and voice output. used xzing library as you can see it in the code. the problem is after showing the scanresult in plaintext, it does't atuostart the audio output functionallity. that is the real usage of this project. i referred youtube but can't. then making a chance to anyone to fix this program to text to voice.
this is my code, when working no errors at all. but no audio output after the scanresult from the barcodescanner. i tried my level best. so anyone can help out of it ??/?.
public class SecondActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA =1;
private ZXingScannerView scannerView;
TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
Toast.makeText(SecondActivity.this, "Firebase connection is successful", Toast.LENGTH_LONG).show();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
Toast.makeText(this, "permission is granted", Toast.LENGTH_SHORT).show();
}
else
{
requestPermission();
}
}
}
private boolean checkPermission()
{
return (ContextCompat.checkSelfPermission(SecondActivity.this, CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission()
{
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String permission[], int grantResults[])
{
switch(requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0)
{
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted)
{
Toast.makeText(SecondActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(shouldShowRequestPermissionRationale(CAMERA))
{
displayAlertMessage("you need to allow access for both permission",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{CAMERA}, REQUEST_CAMERA);
}
});
return;
}
}
}
}
break;
}
}
#Override
public void onResume()
{
super.onResume();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
if(scannerView == null)
{
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
}
else
{
requestPermission();
}
}
}
#Override
public void onDestroy(){
super.onDestroy();
scannerView.stopCamera();
}
public void displayAlertMessage(String message, DialogInterface.OnClickListener listener)
{
new AlertDialog.Builder(SecondActivity.this)
.setMessage(message)
.setPositiveButton("OK", listener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
EditText ed1;
TextToSpeech txt;
#Override
public void handleResult(Result result) {
final String scanResult = result.getText();
setContentView(R.layout.activity_second);
final TextView text = (TextView) findViewById(R.id.editText);
/* long n=890103073;
long n1=Integer.parseInt(scanResult);
if(n1 == n)
text.setText("Pears Bathing Bar, Pure and Gentle.98% pure Glycerin & Natural Oils. Net weight 75 grams. MRP rupees 105 ");
*/
text.setText(scanResult);
scannerView.stopCamera();
txt=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status!=TextToSpeech.ERROR)
{
txt.setLanguage(Locale.UK);
}
}
});
String toSpeak=ed1.getText().toString();
Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);
/* public void onPause()
{
if(txt!=null)
{
txt.stop();
txt.shutdown();
}
super.onPause();
}*/
/*AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(SecondActivity.this);
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse(scanResult));
startActivity(intent);
}
});
builder.setMessage(scanResult);
AlertDialog alert = builder.create();
alert.show();*/
}
}
My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.