SharedPreference not updating - java

SharedPreference not updating (changing). Please help. I'm a starter so I cannot figure it out. Please explain, not just code. Here is the MainActivity.java, where I need the preference and colorPicker.java, where I choose the color.
MainActivity.java:
package com.example.alexsoft.tictactoe;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
boolean turn = true;
int color = 0;
Button A1, B1, C1, A2, B2, C2, A3, B3, C3;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
A1 = (Button) findViewById(R.id.A1);
B1 = (Button) findViewById(R.id.B1);
C1 = (Button) findViewById(R.id.C1);
A2 = (Button) findViewById(R.id.A2);
B2 = (Button) findViewById(R.id.B2);
C2 = (Button) findViewById(R.id.C2);
A3 = (Button) findViewById(R.id.A3);
B3 = (Button) findViewById(R.id.B3);
C3 = (Button) findViewById(R.id.C3);
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
color = prefs.getInt("com.example.alexsoft.tictactoe", R.color.colorAccent);
changeAspect(color);
}
#Override
public void onResume() {
super.onResume();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
color = prefs.getInt("com.example.alexsoft.tictactoe", R.color.colorAccent);
changeAspect(color);
}
#Override
public void onStop() {
super.onStop();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
prefs.edit().putInt("com.example.alexsoft.tictactoe", color).apply();
}
#Override
public void onBackPressed() {
// super.onBackPressed();
//Creating an alert dialog to logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Do you want to exit?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
menu.getItem(1).setIcon(R.mipmap.ic_cached_white_24dp);
switch(Color.rgb(Color.red(color), Color.green(color), Color.blue(color))) {
case R.color.colorPrimary:
menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
case R.color.yellow:
menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
case R.color.lightBlue:
menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.resGame:
restartBtn();
return true;
case R.id.setAsp:
Intent it = new Intent(getBaseContext(), colorPicker.class);
startActivity(it);
return true;
case R.id.aboutBtn:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("About");
alertDialog.setMessage("Tic Tac Toe, verison 1.0, created by Alex Sandulescu");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
return true;
case R.id.resStats:
TextView xCount = (TextView) findViewById(R.id.xCount);
TextView oCount = (TextView) findViewById(R.id.oCount);
TextView roundsPlayed = (TextView) findViewById(R.id.roundsPlayed);
xCount.setText("0");
oCount.setText("0");
roundsPlayed.setText("0");
case R.id.cMode:
if (item.isChecked()) {
//item.setChecked(false);
AlertDialog nYet = new AlertDialog.Builder(MainActivity.this).create();
nYet.setMessage("Not ready yet!");
nYet.setTitle("Message");
nYet.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
nYet.show();
} else {
//item.setChecked(true);
AlertDialog nYet = new AlertDialog.Builder(MainActivity.this).create();
nYet.setMessage("Not ready yet!");
nYet.setTitle("Message");
nYet.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
nYet.show();
}
}
return false;
}
public void btnClick(View v) {
Button b = (Button) v;
if (b.isEnabled()) {
if (turn == true)
b.setText("X");
else
b.setText("0");
b.setEnabled(false);
turn = !turn;
checkForWinner();
}
}
private void checkForWinner() {
String winner = "";
boolean ok = false;
if (A1.getText().equals(B1.getText()) && A1.getText().equals(C1.getText()) && !A1.getText().equals("")) {
ok = true;
winner = A1.getText().toString();
A1.setTextColor(Color.RED);
B1.setTextColor(Color.RED);
C1.setTextColor(Color.RED);
} else if (A2.getText().equals(B2.getText()) && A2.getText().equals(C2.getText()) && !A2.getText().equals("")) {
ok = true;
winner = A2.getText().toString();
A2.setTextColor(Color.RED);
B2.setTextColor(Color.RED);
C2.setTextColor(Color.RED);
} else if (A3.getText().equals(B3.getText()) && A3.getText().equals(C3.getText()) && !A3.getText().equals("")) {
ok = true;
winner = A3.getText().toString();
A3.setTextColor(Color.RED);
B3.setTextColor(Color.RED);
C3.setTextColor(Color.RED);
} else if (A1.getText().equals(A2.getText()) && A1.getText().equals(A3.getText()) && !A1.getText().equals("")) {
ok = true;
winner = A1.getText().toString();
A1.setTextColor(Color.RED);
A2.setTextColor(Color.RED);
A3.setTextColor(Color.RED);
} else if (B1.getText().equals(B2.getText()) && B1.getText().equals(B3.getText()) && !B1.getText().equals("")) {
ok = true;
winner = B1.getText().toString();
B1.setTextColor(Color.RED);
B2.setTextColor(Color.RED);
B3.setTextColor(Color.RED);
} else if (C1.getText().equals(C2.getText()) && C1.getText().equals(C3.getText()) && !C1.getText().equals("")) {
ok = true;
winner = C1.getText().toString();
C1.setTextColor(Color.RED);
C2.setTextColor(Color.RED);
C3.setTextColor(Color.RED);
} else if (A1.getText().equals(B2.getText()) && A1.getText().equals(C3.getText()) && !A1.getText().equals("")) {
ok = true;
winner = A1.getText().toString();
A1.setTextColor(Color.RED);
B2.setTextColor(Color.RED);
C3.setTextColor(Color.RED);
} else if (A3.getText().equals(B2.getText()) && A3.getText().equals(C1.getText()) && !A3.getText().equals("")) {
ok = true;
winner = A3.getText().toString();
A3.setTextColor(Color.RED);
B2.setTextColor(Color.RED);
C1.setTextColor(Color.RED);
}
if (ok) {
Toast.makeText(this, winner + " won!", Toast.LENGTH_LONG).show();
if (winner.equals("X")) {
TextView tcount = (TextView) findViewById(R.id.xCount);
tcount.setText(Integer.toString(Integer.parseInt(tcount.getText().toString()) + 1));
} else {
TextView tcount = (TextView) findViewById(R.id.oCount);
tcount.setText(Integer.toString(Integer.parseInt(tcount.getText().toString()) + 1));
}
A1.setEnabled(false);
B1.setEnabled(false);
C1.setEnabled(false);
A2.setEnabled(false);
B2.setEnabled(false);
C2.setEnabled(false);
A3.setEnabled(false);
B3.setEnabled(false);
C3.setEnabled(false);
}
}
public void restartBtn() {
remakeGame();
TextView rplayed = (TextView) findViewById(R.id.roundsPlayed);
rplayed.setText(Integer.toString(Integer.parseInt(rplayed.getText().toString()) + 1));
}
private void remakeGame() {
A1.setText("");
B1.setText("");
C1.setText("");
A2.setText("");
B2.setText("");
C2.setText("");
A3.setText("");
B3.setText("");
C3.setText("");
//
A1.setTextColor(Color.BLACK);
B1.setTextColor(Color.BLACK);
C1.setTextColor(Color.BLACK);
A2.setTextColor(Color.BLACK);
B2.setTextColor(Color.BLACK);
C2.setTextColor(Color.BLACK);
A3.setTextColor(Color.BLACK);
B3.setTextColor(Color.BLACK);
C3.setTextColor(Color.BLACK);
//
A1.setEnabled(true);
B1.setEnabled(true);
C1.setEnabled(true);
A2.setEnabled(true);
B2.setEnabled(true);
C2.setEnabled(true);
A3.setEnabled(true);
B3.setEnabled(true);
C3.setEnabled(true);
//
turn = true;
}
public void changeAspect(int color) {
if (color != 0) {
A1.setBackgroundColor(color);
B1.setBackgroundColor(color);
C1.setBackgroundColor(color);
A2.setBackgroundColor(color);
B2.setBackgroundColor(color);
C2.setBackgroundColor(color);
A3.setBackgroundColor(color);
B3.setBackgroundColor(color);
C3.setBackgroundColor(color);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f;
color = Color.HSVToColor(hsv);
window.setStatusBarColor(color);
}
}
}
}
colorPicker.java:
package com.example.alexsoft.tictactoe;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class colorPicker extends Activity {
public int color = 0;
String xCount, oCount, roundsPlayed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker);
}
public void onColorConfirm(View v) {
ImageView img = (ImageView) v;
ColorDrawable s = (ColorDrawable) img.getDrawable();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putInt("com.example.alexsoft.tictactoe", color).apply();
finish();
}
#Override
public void onStop() {
super.onStop();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
prefs.edit().putInt("com.example.alexsoft.tictactoe", color).apply();
}
}

The problem is you are not updating the value of color anywhere in your colorPicker activity. The value of color remains 0 all the time.
SOLUTION:
Update color value before storing it into SharedPreferences.
Update your code as below:
public class colorPicker extends Activity {
public int color = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker);
}
public void onColorConfirm(View v) {
ImageView img = (ImageView) v;
ColorDrawable s = (ColorDrawable) img.getDrawable();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
// Update color value
color = SOME_VALUE;
// Store
ed.putInt("com.example.alexsoft.tictactoe", color).apply();
finish();
}
}
Hope this will help~

Related

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

Search focusable null pointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hi i did everything about the search query and have no problem in errors but i keep getting a running time error of nullpointerexception
java src code below
package com.developer.bunamay.mplayer;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends Activity {
String LOG_CLASS = "MainActivity";
public static final PlayUtils PlayerController = PlayUtils.getInstance();
CustomAdapter customAdapter = null;
private MediaFileAdapter mediaFileAdapter = null;
public static final int PICK_FOLDER_REQUEST = 8;
static TextView playingSong;
Button btnPlayer;
static Button btnPause, btnPlay, btnNext, btnPrevious;
Button btnStop;
LinearLayout mediaLayout;
static LinearLayout linearLayoutPlayingSong;
ListView mediaListView;
SeekBar seekBar;
TextView textBufferDuration, textDuration;
static ImageView imageViewAlbumArt;
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
init();
}
private void init() {
getViews();
setListeners();
playingSong.setSelected(true);
seekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
if (PlayerConstants.SONGS_LIST.size() <= 0) {
PlayerConstants.SONGS_LIST = PlayUtils.listOfSongs(getApplicationContext());
}
setListItems();
}
private void setListItems() {
customAdapter = new CustomAdapter(this, R.layout.custom_list, PlayerConstants.SONGS_LIST);
mediaListView.setAdapter(customAdapter);
mediaListView.setFastScrollEnabled(true);
}
private void getViews() {
playingSong = (TextView) findViewById(R.id.textNowPlaying);
btnPlayer = (Button) findViewById(R.id.btnMusicPlayer);
mediaListView = (ListView) findViewById(R.id.listViewMusic);
mediaLayout = (LinearLayout) findViewById(R.id.linearLayoutMusicList);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
seekBar = (SeekBar) findViewById(R.id.seekBar);
btnStop = (Button) findViewById(R.id.btnStop);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
}
private void setListeners() {
mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
Log.d("TAG", "TAG Tapped INOUT(IN)");
PlayerConstants.SONG_PAUSED = false;
PlayerConstants.SONG_NUMBER = position;
boolean isServiceRunning = PlayUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (!isServiceRunning) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
startService(i);
} else {
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage());
}
updateUI();
changeButton();
Log.d("TAG", "TAG Tapped INOUT(OUT)");
}
});
btnPlayer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, AudioPlayerActivity.class);
startActivity(i);
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
btnPrevious.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
stopService(i);
linearLayoutPlayingSong.setVisibility(View.GONE);
}
});
imageViewAlbumArt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, AudioPlayerActivity.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
boolean isServiceRunning = PlayUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
} else {
linearLayoutPlayingSong.setVisibility(View.GONE);
}
changeButton();
PlayerConstants.SEEKBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(PlayUtils.getDuration(i[0]));
textDuration.setText(PlayUtils.getDuration(i[1]));
seekBar.setProgress(i[2]);
}
};
} catch (Exception e) {
}
}
#SuppressWarnings("deprecation")
public static void updateUI() {
try {
MediaItem data = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER);
playingSong.setText(data.getTitle() + " " + data.getArtist() + "-" + data.getAlbum());
Bitmap albumArt = PlayUtils.getAlbumart(context, data.getAlbumId());
if (albumArt != null) {
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(PlayUtils.getDefaultAlbumArt(context)));
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE);
} catch (Exception e) {
}
}
public static void changeButton() {
if (PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
public static void changeUI() {
updateUI();
changeButton();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
Intent about = new Intent(MainActivity.this, About.class);
startActivity(about);
break;
case R.id.action_exit:
finish();
break;
}
int id = item.getItemId();
// get music from specific folder
if (id == R.id.folder_music) {
Intent intent = new Intent(this, FolderPickerActivity.class);
startActivityForResult(intent, PICK_FOLDER_REQUEST);
return true;
}
// search songs by title
if (id == R.id.action_search_title) {
PlayerController.SEARCH_TYPE = "TITLE";
return true;
}
// search songs by artist
if (id == R.id.action_search_artist) {
PlayerController.SEARCH_TYPE = "ARTIST";
return true;
}
// search songs by album
if (id == R.id.action_search_album) {
PlayerController.SEARCH_TYPE = "ALBUM";
return true;
}
if (id == R.id.action_sort_title) {
MediaFileComparator.sortByTitle(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_album) {
MediaFileComparator.sortByAlbum(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_artist) {
MediaFileComparator.sortByArtist(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_duration) {
MediaFileComparator.sortByDuration(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
#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_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// init menu items for search
MenuItem itemSearchTitle = menu.findItem(R.id.action_search_title);
MenuItem itemSearchAlbum = menu.findItem(R.id.action_search_album);
MenuItem itemSearchArtist = menu.findItem(R.id.action_search_artist);
SearchView searchViewTitle = (SearchView) itemSearchTitle.getActionView();
SearchView searchViewAlbum = (SearchView) itemSearchAlbum.getActionView();
SearchView searchViewArtist = (SearchView) itemSearchArtist.getActionView();
searchViewTitle.setFocusable(true);
searchViewAlbum.setFocusable(true);
searchViewArtist.setFocusable(true);
// init searchable info for each menu item
searchViewTitle.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewTitle.setQueryHint("title...");
searchViewTitle.setIconified(true);
searchViewAlbum.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewAlbum.setQueryHint("album...");
searchViewAlbum.setIconified(true);
searchViewArtist.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewArtist.setQueryHint("artist...");
searchViewArtist.setIconified(true);
// set textChangeListeners for each type of search
final SearchView.OnQueryTextListener textChangeListenerTitle = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerAlbum = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerArtist = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
// apply listeners to searchViews
searchViewTitle.setOnQueryTextListener(textChangeListenerTitle);
searchViewAlbum.setOnQueryTextListener(textChangeListenerAlbum);
searchViewArtist.setOnQueryTextListener(textChangeListenerArtist);
return super.onCreateOptionsMenu(menu);
}
}
I keep getting the error on
searchViewTitle.setFocusable(true);
and the here is the logcat displaying the error
07-31 18:12:18.047 2066-2066/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.developer.bunamay.mplayer, PID: 2066
java.lang.NullPointerException
at com.developer.bunamay.mplayer.MainActivity.onCreateOptionsMenu(MainActivity.java:300)
at android.app.Activity.onCreatePanelMenu(Activity.java:2538)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)
at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:800)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:221)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:543)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
07-31 18:12:18.051 587-599/? W/ActivityManager: Force finishing activity com.developer.bunamay.mplayer/.MainActivity
THANKS!!
ActionView of itemSearchTitle is null at this moment.

Using shared preferences to store high score

It gives me a error cannot resolve symbol sharedpreferences, I'm trying to add a high score for every time the user take the quiz it records the high score of the quiz. I dont know what happen. Please help me with this one and I'll help you with ur reputation.
package com.example.quiz;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
public class CS_Assembly_Easy extends Activity{
TextView topscore;
public static final String mypreference = "mypref";
public static final String Topscore = "topKey";
ArrayList<Question> quesList;
ArrayList<Question> toSelectFrom; // <--- HERE
int score = 0;
int qid = 0;
int lives = 5;
int round = 1;
int timer;
Question currentQ;
TextView txtQuestion, times, scored, livess, rounds;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_assembly_easy);
CS_Assembly_QuizHelper db = new CS_Assembly_QuizHelper(this); // my question bank class
quesList = db.getAllQuestions();
toSelectFrom = new ArrayList<Question>(); // <--- HERE
toSelectFrom.addAll(quesList); // <--- HERE
Random random = new Random();// this will fetch all quetonall questions
currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
rounds = (TextView) findViewById(R.id.round);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore) > score) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
public void Save(View view) {
String n = topscore.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Topscore, n);
editor.commit();
}
public void clear(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
topscore.setText("");
}
public void Get(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore)) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText(" Score : " + score);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.correct,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("CORRECT");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
} else if(lives > -10){
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.wrong,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("WRONG");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
else {
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
{
}
if (qid < 10) {
// if questions are not over then do this
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
setQuestionView();
round++;
rounds.setText(" Question:" + round + "/10");
} else {
// if over do this
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onBackPressed() {
return;
}
}
sharedpreferences is not defined in your CS_Assembly_Easy class.
Try changing your code to this:
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);

Android cannot be referenced from a static context

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.

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