Android cannot be referenced from a static context - java

I'm a beginner on Android and this is the first I'm creating an app named GeoQuiz which basically has a few questions and the user has to click true/false or request the answer with the cheat button.I'm getting this one line of error related with a non-static an a static context in line 138,what am I doing wrong? I'm trying that every time i click on the button cheat, it open the other window that is under a different .xml file and in an another java class
package com.example.fusion.geoquiz;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.TextView;
import android.util.Log;
import android.content.Intent;
import android.content.Intent;
import java.util.*;
import static com.example.fusion.geoquiz.R.string.correct_toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private ProgressBar mProgress;
private Button mCheatButton;
private int mProgressStatus = 0;
private TextView mQuestionTextView;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private int checker = 0;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
private void disablePrev(){
if(mCurrentIndex== 0){
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setEnabled(false);
}
else{
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setEnabled(true);
}
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
checker++;
if(checker >0) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
//mProgressStatus=checker;
//mProgress.setProgress(mProgressStatus);
disablePrev();
}
} else {
messageResId = R.string.incorrect_toast;
checker = 0;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
disablePrev();
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
updateQuestion();
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(false);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
}
});
mNextButton = (ImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checker==1) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
disablePrev();
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurrentIndex != 0){
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
mQuestionTextView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checker==1) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(QuizActivity.this, cheatActivity.startActivity(intent));
}
});
disablePrev();
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quiz, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is the class for the cheat class and cheatButton
package com.example.fusion.geoquiz;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.widget.TextView;
import android.util.Log;
/**
* Created by fusion on 1/21/2015.
*/
public class cheatActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
}
}

Replace
Intent intent = new Intent(QuizActivity.this, cheatActivity.startActivity(intent));
with
Intent intent = new Intent(QuizActivity.this, cheatActivity.class);
startActivity(intent);
See the docs for more details..

Not sure what you're doing there, but you need to reference the other activity class. Simply calling startActivity is enough, because it will be implicitly called from QuizActivity.this.
Intent intent = new Intent(QuizActivity.this, cheatActivity.class);
startActivity(intent);
To save you from future errors choose one activity class that you will be using either Activity or ActionBarActivity. The latter is from the support package.

Related

How do i modify data on my MainActivity from Settings Activity?

I've tried many other threads and articles but I just can't find the right stuff that I am looking for.
So I have a MainActivity and a SettingsActivity both are java classes. In my main activity there is a button when pressed, increases the count by +1, and shows it on a TextView, it also makes the device vibrate on every increment/Every button press. I want to make a switchpreference in SettingsActivity which if kept off/false, turns off the vibration on button press and if kept on/true, turns on the vibration on button press.
I don't know how to retrieve the state of SwitchPreferenceCompat(ON OR OFF) from SettingsActivity and use it in the MainActivity, so if the user turns the switch off in setting activity, the vibration should stop on button press which is in MainActivity.
I have already used Shared Preferences in MainActivity for saving the current count/number when App is closed and resumes from the same count when reopened.
MainAcitivity
package com.saad.tapcounter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.preference.PreferenceManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private AdView mAdView ;
int Start;
TextView txt;
Button btnU,btnT,btnR;
Switch sw,sw2;
private ConstraintLayout Clayout;
Vibrator vibe;
Boolean switchPref;
SharedPreferences sharedPreferences;
private static long back_pressed;
private Vibrator Vibrator;
//Double Tap Exit
#Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
//Inflater for Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
//Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.menui1:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbarid);
setSupportActionBar(toolbar);
MobileAds.initialize(this, "-APPID-");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
vibe =(Vibrator)getSystemService(VIBRATOR_SERVICE);
Clayout = findViewById(R.id.MainLayout);
btnT = findViewById(R.id.tapbtn);
btnR = findViewById(R.id.resetbtn);
btnU = findViewById(R.id.undobtn);
sw = findViewById(R.id.swch);
sw2 = findViewById(R.id.darkswch);
txt = findViewById(R.id.txtv);
txt.setTextColor(Color.BLACK);
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
loadData();
setData();
incrementbtn();
undobtn();
resetbtn();
switchbtn();
themeswitch();
}
public void loadData(){
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
}
private void setData(){
Start = sharedPreferences.getInt("0",0);
if(Start==0){
txt.setText("0");
}
else{
txt.setText(Integer.toString(Start));
}
}
public void incrementbtn(){
btnT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incvibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start += 1;
txt.setText(Integer.toString(Start));
txtresize();
} else {
Start += 1;
txt.setText(Integer.toString(Start));
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void undobtn(){
btnU.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
undovibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start -= 1;
txt.setText(Integer.toString(Start));
}
else{
return;
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void resetbtn(){
btnR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetvibe();
Start = 0;
txt.setText(Integer.toString(Start));
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void switchbtn(){
sw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw.isChecked()) {
btnR.setEnabled(false);
btnT.setEnabled(false);
btnU.setEnabled(false);
txt.setTextColor(Color.RED);
}
else{
btnR.setEnabled(true);
btnT.setEnabled(true);
btnU.setEnabled(true);
if(sw2.isChecked()){
txt.setTextColor(Color.WHITE);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void themeswitch(){
sw2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw2.isChecked()){
Clayout.setBackgroundColor(Color.DKGRAY);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.WHITE);
}
}
else{
Clayout.setBackgroundColor(Color.WHITE);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void txtresize(){
if(Start > 1000 && Start < 10000){
txt.setTextSize(80);
}
else if (Start > 10000 && Start < 100000){
txt.setTextSize(60);
}
else if (Start > 100000){
txt.setTextSize(40);
}
else{
return;
}
}
StringBuilder info = new StringBuilder();
public void undovibe(){
vibe.vibrate(100);
}
public void resetvibe(){
vibe.vibrate(150);
}
public void incvibe(){
vibe.vibrate(40);
}
}//Real one
SettingActivity (created it from NEW > SettingActivity)
I did try some stuff by myself in here but it crashed my app.
package com.saad.tapcounter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
root_preference.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory app:title="Settings"
app:iconSpaceReserved="false">
<SwitchPreferenceCompat
app:key="Switchsett1"
app:title="Vibration"
app:summaryOff="Turn Vibration On"
app:summaryOn="Turn Vibration Off"
app:iconSpaceReserved="false"
app:defaultValue="true"
/>
<SwitchPreferenceCompat
app:key="Switchset2"
app:iconSpaceReserved="false"
app:summaryOff="#string/attachment_summary_off"
app:summaryOn="#string/attachment_summary_on"
app:title="#string/attachment_title" />
</PreferenceCategory>
</PreferenceScreen>
I don't know how to retrieve the state of switch(ON OR OFF) from SettingsActivity
To get the value of SwitchPreferenceCompat from shared preference, then you need to retrieve it as a Boolean
Now the key of your first SwitchPreferenceCompat is Switchsett1, so to retrieve the value of this:
public class MainActivity extends AppCompatActivity {
Boolean switchPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
switchPref = prefs.getBoolean("Switchsett1", false);
Toast.makeText(this, String.valueOf(switchPref), Toast.LENGTH_SHORT).show(); // shows true if the SwitchPreferenceCompat is ON, and false if OFF.
Now the Toast in the above script shows true if the SwitchPreferenceCompat is ON, and false if it's OFF.
You can do the same for Switchset2 SwitchPreferenceCompat

Runnable not works

I have problem with Runnable. It don't want to works, and i don't know what is the problem, because it is works in my other app... Can somebody help me?
Just example, there are "healt" with deafult value=5, for the test i made a button, when i click button, healt value -1... and i want start Runnable when health<5... and add +1 to health.... for the test i setted the Runnable 1 secunds
Here is the code:
MainActivity.java
package com.mygame.test;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import static com.mygame.test.variables.coin;
import static com.mygame.test.variables.health;
public class Main2Activity extends AppCompatActivity {
public static final String PREFS_NAME_MAIN = "mainpref";
TextView coinText, healthText, textView;
Button button3;
private final Context app = this;
private final Handler update = new Handler();
private final Runnable updateHealth = new Runnable()
{
public void run()
{
if (variables.run)
{
healthText.setText(""+health);
update.postDelayed(updateHealth, 500);
}
else if (!variables.run) update.removeCallbacksAndMessages(null);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
coinText = findViewById(R.id.coinText);
healthText = findViewById(R.id.healthText);
healthText.setText(String.valueOf(health));
button3 = findViewById(R.id.button3);
textView = findViewById(R.id.textView);
Button closeButton = findViewById(R.id.closeButton);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, ExitActivity.class));
}
});
Button coinsplusButton = findViewById(R.id.coinsplusButton);
coinsplusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, StoreActivity.class));
}
});
Button level1Button = findViewById(R.id.level1Button);
level1Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, Level1Activity.class));
}
});
}
public void buttontest(View button3)
{
if (health > 0) {
health = health-1;
healthText.setText(""+health);
}
variables.run = true;
Intent activeClick = new Intent(this, ClickService.class);
this.startService(activeClick);
update.post(updateHealth);
save();
}
#Override
protected void onStart()
{
super.onStart();
load();
textupgrade();
if (!variables.run)
{
variables.run = true;
Intent activeClick = new Intent(this, ClickService.class);
this.startService(activeClick);
}
}
protected void onResume()
{
super.onResume();
load();
textupgrade();
update.post(updateHealth);
}
private void load()
{
SharedPreferences varReader = app.getSharedPreferences(PREFS_NAME_MAIN, MODE_PRIVATE);
variables.run = varReader.getBoolean("run", false);
coin = varReader.getInt("coin", 0);
health = varReader.getInt("health", 5);
}
private void save()
{
SharedPreferences.Editor varReader = app.getSharedPreferences(PREFS_NAME_MAIN, 0).edit();
varReader.putBoolean("run", variables.run);
varReader.putInt("coin", coin);
varReader.putInt("health", health);
varReader.apply();
}
private void textupgrade(){
coinText.setText(""+coin);
healthText.setText(""+health);
}
}
ClickService.java
package com.mygame.test;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
public class ClickService extends IntentService
{
private final Handler handler = new Handler();
private final Runnable addHealth = new Runnable()
{
public void run()
{
variables.health++;
if (!variables.run) handler.removeCallbacksAndMessages(null);
else if (variables.run) handler.postDelayed(addHealth, 1000);
}
};
public ClickService()
{
super("ClickService");
}
#Override
protected void onHandleIntent(Intent activeClick)
{
handler.postDelayed(addHealth, 500);
}
}
variables.java
package com.mygame.test;
public class variables {
static int coin;
static int health;
static boolean run;
}
Oh, i fixed it :D ClickService was not registered in AndroidManifest
<service
android:name=".ClickService"
android:exported="false" />

Activity Reloads with Previous Selected Data Bug

So i developed an android news app. A spinner item is available on the toolbar and data reloads according to spinner selection. However, when the data reloads, for some of the items, it directly loads the relevant content but for some others, it loads the previously selected spinner data. Current data for the current item only shows after reloading same spinner data using the swipe refresh functionality which i had implemented. I want the correct data relevant to that selection to load the first time itself without having to refresh all the time.
Below is my MainActivity where all these functions are called.
package com.example.app.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.messaging.FirebaseMessaging;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class MainActivity extends AppCompatActivity {
String URL="url" //outputs JSON data
private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set Font
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());
myApplication = MyApplication.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
spinnerConstituencyName = new ArrayList<>();
mySpinner = findViewById(R.id.mySpinner);
prefManager = new PrefManager(MainActivity.this);
loadSpinnerData(URL);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/
if (++check > 1) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
//intent.putExtra("NAME_KEY", itemSelected);
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_video:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_favorite:
viewPager.setCurrentItem(3);
return true;
case R.id.navigation_profile:
viewPager.setCurrentItem(4);
return true;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
if (viewPager.getCurrentItem() == 1) {
toolbar.setTitle(getResources().getString(R.string.title_nav_category));
} else if (viewPager.getCurrentItem() == 2) {
toolbar.setTitle(getResources().getString(R.string.title_nav_video));
} else if (viewPager.getCurrentItem() == 3) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else if (viewPager.getCurrentItem() == 4) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else {
toolbar.setTitle(R.string.app_name);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (Config.ENABLE_RTL_MODE) {
viewPager.setRotationY(180);
}
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
// now subscribe to global topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);
} else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
Intent intent = getIntent();
final String message = intent.getStringExtra("message");
final String imageUrl = intent.getStringExtra("image");
final long nid = intent.getLongExtra("id", 0);
final String link = intent.getStringExtra("link");
if (message != null) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(mView);
final TextView notification_title = mView.findViewById(R.id.news_title);
final TextView notification_message = mView.findViewById(R.id.news_message);
final ImageView notification_image = mView.findViewById(R.id.news_image);
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
notification_title.setText(message);
notification_message.setVisibility(View.GONE);
Picasso.with(MainActivity.this)
.load(imageUrl.replace(" ", "%20"))
.placeholder(R.drawable.ic_thumbnail)
.resize(200, 200)
.centerCrop()
.into(notification_image);
alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
intent.putExtra("id", nid);
startActivity(intent);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
notification_title.setText(getResources().getString(R.string.app_name));
notification_message.setVisibility(View.VISIBLE);
notification_message.setText(message);
notification_image.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();
if (!link.equals("")) {
alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(open);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
alert.setPositiveButton(R.string.dialog_ok, null);
}
}
alert.setCancelable(false);
alert.show();
}
GDPR.updateConsentStatus(this);
}
public class MyAdapter extends FragmentPagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentRecent();
case 1:
return new FragmentCategory();
case 2:
return new FragmentVideo();
case 3:
return new FragmentFavorite();
case 4:
return new FragmentProfile();
}
return null;
}
#Override
public int getCount() {
return pager_number;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem((0), true);
} else {
exitApp();
}
}
public void exitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).equals(myString)) {
index = i;
}
}
return index;
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//TODO DONE
String name = prefManager.spinReadString();
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getString("status").equals("ok")){
JSONArray jsonArray=jsonObject.getJSONArray("constituencies");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String spinConstituency=jsonObject1.getString("constituency_name");
//TODO DONE
if (spinConstituency.equals(name))
spinConstID = jsonObject1.getInt("const_id");
spinnerConstituencyName.add(spinConstituency);
}
//TODO DONE
prefManager.writeString("" + spinConstID);
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_item, spinnerConstituencyName){
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position % 2 == 1) {
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#910D3F"));
}
else {
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#41061C"));
}
return view;
}
};
mySpinner.setPrompt("Select Your Constituency");
myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
mySpinner.setAdapter(myAdapter);
//RECEIVE DATA VIA INTENT
mySpinner.setSelection(getIndex(mySpinner, name));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
I discovered that from API level 3, one can use the onUserInteraction() on an Activity with a boolean value thereby determining the user's interaction.
Find the documentation in the link below.
http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
#Override
public void onUserInteraction() {
super.onUserInteraction();
userInteracts = true;
}
The my adjustment goes as thus in the MainActivity.java
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (IsInteracting) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}

AdMob Interstitial not loading

I have a problem with admob ads.
The banner ad seems to work fine but the Interstitial is not loading.
I have tried various solutions, generating different ad unit id's and trying admob test ids.
QuoteActivity.java
package com.axdev.thequotesgarden;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
public class QuoteActivity extends ActionBarActivity implements
TextToSpeech.OnInitListener {
private int ID;
private String mode,fav,text;
private Quote qte;
private DataBaseHandler db;
private ArrayList<Quote> myList = new ArrayList<Quote>();
private TextView textAuth,textQuote;
private ImageView imgIcon;
private ImageButton btnNext,btnPrevious;
private TextToSpeech tts;
private RoundImage roundedImage;
private AdView adView;
private InterstitialAd interstitial;
SharedPreferences sharedPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quote);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
db = new DataBaseHandler(this);
textAuth = (TextView) findViewById(R.id.textAuth);
textQuote = (TextView) findViewById(R.id.textQuote);
imgIcon = (ImageView) findViewById(R.id.imgcon);
btnNext = (ImageButton) findViewById(R.id.btn_next);
btnPrevious = (ImageButton) findViewById(R.id.btn_prev);
Typeface fontQuote = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Light.ttf");
Typeface fontAuth = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Italic.ttf");
textQuote.setTypeface(fontQuote);
textQuote.setTextSize(18);
textAuth.setTypeface(fontAuth);
ID = getIntent().getExtras().getInt("id");
mode = getIntent().getExtras().getString("mode");
if(mode.equals("qteday")){
qte = db.getQuote(ID);
btnNext.setVisibility(View.GONE);
btnPrevious.setVisibility(View.GONE);
}
else {
myList = (ArrayList<Quote>) getIntent().getSerializableExtra("array");
qte = myList.get(ID);}
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ID < (myList.size() - 1)) {
ID++;
qte = myList.get(ID);
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ID > 0) {
ID--;
qte = myList.get(ID);
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
}
}
});
fav = qte.getFav();
adView = new AdView(this);
adView.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) findViewById(R.id.layAdsQuote);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
if(mode.equals("qteday")){
tts = new TextToSpeech(this, this);
speakOut();
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getResources().getString(R.string.interstitial_ad_unit_id));
AdRequest adRequest2 = new AdRequest.Builder().build();
interstitial.loadAd(adRequest2);
interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
displayInterstitial();
}
});
}
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void checkPicure(){
boolean isExist = false;
InputStream imageStream = null;
try {
imageStream = getAssets().open("authors/"+qte.getFileName()+".jpg");
isExist =true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isExist != false){
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
roundedImage = new RoundImage(theImage);
imgIcon.setImageDrawable(roundedImage );
}
else {
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.mipmap.author);
roundedImage = new RoundImage(bm);
imgIcon.setImageDrawable(roundedImage);
}
}
public void doShare() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Quote");
intent.putExtra(Intent.EXTRA_TEXT,
qte.getQuote() + " - " + qte.getName());
QuoteActivity.this.startActivity(Intent.createChooser(intent,
getResources().getString(R.string.share)));
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Locale loc = new Locale("en", "UK");
tts.setLanguage(loc);
tts.setSpeechRate((float) 0.8);
speakOut();
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean speaker = sharedPrefs.getBoolean("prefSpeaker", true);
if (speaker.equals(true)) {
text = qte.getQuote() + "\n" + qte.getName();
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
else {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quote, menu);
if (fav.equals("0")) {
menu.findItem(R.id.action_favorite).setIcon(R.mipmap.not_fav);
}
if (fav.equals("1")) {
menu.findItem(R.id.action_favorite).setIcon(R.mipmap.fav);
}
;
return true;
}
#TargetApi(11)
private void copyToClipBoard(String qte) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(qte);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("text", qte);
clipboard.setPrimaryClip(clip);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
case R.id.action_share:
doShare();
break;
case R.id.copy:
String text = qte.getQuote() + "- " + qte.getName();
copyToClipBoard(text);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.copy_msg),
Toast.LENGTH_LONG).show();
break;
case R.id.action_favorite:
if (qte.getFav().equals("0")) {
qte.setFav("1");
db.updateQuote(qte);
item.setIcon(R.mipmap.fav);
} else if (qte.getFav().equals("1")) {
qte.setFav("0");
db.updateQuote(qte);
item.setIcon(R.mipmap.not_fav);
}
}
return true;
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
QuotesActivity.java
package com.axdev.thequotesgarden;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import java.util.ArrayList;
import java.util.List;
public class QuotesActivity extends ActionBarActivity {
private ArrayList<Quote> imageArry = new ArrayList<Quote>();
private QuotesListAdapter adapter;
private String Activitytype;
private DataBaseHandler db;
private ListView dataList;
private int count;
private ImageView noQuotes;
private AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
db = new DataBaseHandler(this);
noQuotes = (ImageView)findViewById(R.id.NoQuotes);
adapter = new QuotesListAdapter(this, R.layout.quote_items, imageArry);
dataList = (ListView) findViewById(R.id.quotesList);
Button btnLoadMore = new Button(this);
btnLoadMore.setBackgroundResource(R.drawable.btn_green);
btnLoadMore.setText(getResources().getText(R.string.btn_LoadMore));
btnLoadMore.setTextColor(0xffffffff);
Activitytype = getIntent().getExtras().getString("mode");
if (Activitytype.equals("isCategory")) {
String categoryValue = getIntent().getExtras()
.getString("category");
List<Quote> contacts = db.getQuotesByCategory(categoryValue);
for (Quote cn : contacts) {
imageArry.add(cn);
}
}
if (Activitytype.equals("isAuthor")) {
String authorValue = getIntent().getExtras().getString("name");
List<Quote> contacts = db.getQuotesByAuthor(authorValue);
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
}
if (Activitytype.equals("isFavorite")) {
actionBar.setTitle(getResources().getText(R.string.title_activity_favorites));
List<Quote> contacts = db.getFavorites();
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
if (imageArry.isEmpty()){
noQuotes.setVisibility(View.VISIBLE);
}
}
if (Activitytype.equals("allQuotes")) {
List<Quote> contacts = db.getAllQuotes(" LIMIT 50");
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
dataList.addFooterView(btnLoadMore);
}
dataList.setAdapter(adapter);
dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
Intent i = new Intent(getApplicationContext(),
QuoteActivity.class);
Quote srr = imageArry.get(position);
i.putExtra("id",position);
i.putExtra("array", imageArry);
i.putExtra("mode", "");
startActivity(i);
}
});
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
new loadMoreListView().execute();
}
});
adView = new AdView(this);
adView.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) findViewById(R.id.layAdsQuotes);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Before starting background task
// Show Progress Dialog etc,.
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
count += 50;
List<Quote> contacts = db.getAllQuotes(" LIMIT "+count+ ",50");
for (Quote cn : contacts) {
imageArry.add(cn);
}
int currentPosition = dataList.getFirstVisiblePosition();
adapter = new QuotesListAdapter(QuotesActivity.this, R.layout.quote_items, imageArry);
dataList.setSelectionFromTop(currentPosition + 1, 0);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
}
}
#Override
public void onBackPressed()
{
finish();
super.onBackPressed(); // optional depending on your needs
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quotes, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
}
return true;
}
}
The simplest answer is that mode is not equal to "qteday"
if(mode.equals("qteday")){
Unless that is true, the interstitial will never be loaded.

Android CountDown Timer in Quiz Application

I have made a quiz application which include 5 questions. I have made a ResultActivity page which displays result of the quiz.
I have added a countDown timer of 20 sec for each question. When the Countdown timer finishes it moves to the next question automatically. When the questions are finished it should move to the ResultActivity page to display result.
I have only one issue...
Afetr reaching my last Question..if i does not select any answer and timer is finished the applicaton is not moving to my ResultActivity page..The timer is getting started again and again on the same question until i select any option
Here is my code:
QuizActivity.java
package com.example.triviality;
import java.util.LinkedHashMap;
import java.util.List;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends Activity {
List<question> quesList;
public static int score, correct, wrong, wronganswers;
public boolean isCorrect;
static int qid = 0;
int totalCount = 5;
Question currentQ;
TextView txtQuestion;
RadioGroup radioGroup1;
RadioButton rda, rdb, rdc;
Button butNext;
TextView rt;
boolean nextFlag = false;
boolean isTimerFinished = false;
static LinkedHashMap lhm = new LinkedHashMap();
MyCountDownTimer countDownTimer = new MyCountDownTimer(10000 /* 20 Sec */,
1000);
// final MyCountDownTimer timer = new MyCountDownTimer(20000,1000);
public static String[] Correctanswers = new String[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
DbHelper db = new DbHelper(this);
quesList = db.getAllQuestions();
currentQ = quesList.get(qid);
txtQuestion = (TextView) findViewById(R.id.textView1);
rda = (RadioButton) findViewById(R.id.radio0);
rdb = (RadioButton) findViewById(R.id.radio1);
rdc = (RadioButton) findViewById(R.id.radio2);
butNext = (Button) findViewById(R.id.button1);
// radioGroup1=(RadioGroup)findViewById(R.id.radioGroup1);
setQuestionView();
// timer.start();
rt = (TextView) findViewById(R.id.rt);
rt.setText("20");
countDownTimer.start();
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countDownTimer.cancel();
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
}
});
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
Log.e("Times up", "Times up");
countDownTimer.cancel();
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
}
#Override
public void onTick(long millisUntilFinished) {
rt.setText((millisUntilFinished / 1000) + "");
Log.e("Second Gone", "Another Second Gone");
Log.e("Time Remaining", "seconds remaining: " + millisUntilFinished
/ 1000);
}
}
boolean getNextQuestion(boolean c) {
nextFlag = true;
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
// grp.clearCheck();
RadioButton answer = (RadioButton) findViewById(grp
.getCheckedRadioButtonId());
if (rda.isChecked() || rdb.isChecked() || rdc.isChecked()) {
qid++;
Log.d("yourans", currentQ.getANSWER() + " " + answer.getText());
grp.clearCheck();
// wronganswers=
if (!c && currentQ.getANSWER().equals(answer.getText())) {
correct++;
} else {
lhm.put(currentQ.getQUESTION(), currentQ.getANSWER());
wrong++;
}
if (qid < 5) {
currentQ = quesList.get(qid);
setQuestionView();
} else {
score = correct;
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);
return false;
}
} else {
lhm.put(currentQ.getQUESTION(), currentQ.getANSWER());
qid++;
if (qid < 5) {
currentQ = quesList.get(qid);
//currentQ.getANSWER().equals(wrong);
wrong++;
Log.e("yourans", currentQ.getANSWER());
setQuestionView();
}
// wrong++;
// Log.e("Without Any Selection ", "without "+wrong);
// Toast.makeText(getApplicationContext(),
// "Please select atleast one Option",Toast.LENGTH_SHORT).show();
}
return true;
}
}
ResultActivity.java:
package com.example.triviality;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ResultActivity extends Activity {
Button restart;
Button check;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
TextView t=(TextView)findViewById(R.id.textResult);
TextView t1=(TextView)findViewById(R.id.textResult1);
TextView t2=(TextView)findViewById(R.id.textResult2);
restart=(Button)findViewById(R.id.restart);
check=(Button)findViewById(R.id.check);
StringBuffer sb=new StringBuffer();
sb.append("Correct ans: "+QuizActivity.correct+"\n");
StringBuffer sc=new StringBuffer();
sc.append("Wrong ans : "+QuizActivity.wrong+"\n");
StringBuffer sd=new StringBuffer();
sd.append("Final Score : "+QuizActivity.score);
t.setText(sb);
t1.setText(sc);
t2.setText(sd);
QuizActivity.correct=0;
QuizActivity.wrong=0;
check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in=new Intent(getApplicationContext(),CheckActivity.class);
startActivity(in);
}
});
restart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//QuizActivity quiz=new QuizActivity();
// TODO Auto-generated method stub
Intent intent=new Intent(getApplicationContext(),QuizActivity.class);
QuizActivity.lhm.clear();
QuizActivity.qid=0;
startActivity(intent);
//quiz.countDownTimer.onTick(19);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
}
This is because Your return false statement will never be reached if the user has made no choice:
if (rda.isChecked() || rdb.isChecked() || rdc.isChecked()){}
in this if else statement You will return false later. But if none is selected, You automatically will return true because the code block inside this statement above will not be rached. And then in Your timer You say:
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
getNextQuestion is allways true if the user makes no choice, so the timer starts again and again.

Categories