I am new in Java and writing android game app and I just learnt writing a simple shooting Game app. Now I want to save my highscore and I found that there is a what so called
sharedpreferences
which can be used to store the score. But I dont really understand how to use it. Can anyone help me?
Below is my Game class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//turn title off
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set to full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GamePanel(this));
}
#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_game, 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);
}
And all of the game activity I code it in my GamePanel.java class and inside this class I also count my score. So now I would like to store the score. How can I do it?
Use the android preferences:
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("deficitPercentage_key", prefVal); //
editor.commit();
the prefVal is the value to store
Related
I'm new about coding so i'm sorry for my "basic" questions.
I'm coding an Android app with Android studio; very simple, only webview that show my website but i need to have in settings menu an editText where i can modify my website url.
I made two activitys(Main and Settings) that i post; Could anyone help me to understand how can i store permanently the url that i write in my editText in order to open that url when i came back to main activity?
Hope i submit clearly my question!!
Thanks in advance
Settings.java
private EditText editsite;
private Button button;
public static TextView actSite;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
editsite = findViewById(R.id.editsite);
button = findViewById(R.id.saveButton);
actSite = findViewById(R.id.actSite);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String strData = editsite.getText().toString();
if (strData.length()<=0) {
Toast.makeText(this,"Sito non valido", Toast.LENGTH_SHORT).show();
}else {
actSite.setText(strData);
Main Activity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
WebView vista = (WebView)findViewById(R.id.vista);
vista.getSettings().setJavaScriptEnabled(true);
vista.setWebViewClient(new WebViewClient());
vista.loadUrl("www.google.com"); //examplesite
}
#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);
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) {
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use SharedPreferences Here. And everytime the MainActivity starts you load the Shared Preferences and get the String.
Example:
set Shared Preferences
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("URL", "Your url");
editor.apply();
Get the value
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String url= prefs.getString("URL", "String if URL is emtpy");
I am new in android programming, having error in the given code which are: Multiple markers at this line
-Button1 cannot be resolved to a variable
-Syntax error on token "#", class expected
-id cannot be resolved to a variable
-Line breakpoint:MainActivity [line: 22] - onCreate(Bundle)
public class MainActivity extends Activity {
Button aButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aButton = (Button) this.findViewById(R.id.Button_1);
aButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
aButton.setText("Submitted");
}});
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
1.u must have activity_main and it should include Button with Button_1
2.check .JavaClassName added in Manifest file
I'm working on programming a android application. But as soon as I would like to test my application in my simulator, I get an instant error.
This is my code.
public class MainActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button toPech = (Button)findViewById(R.id.toPech);
toPech.setOnClickListener(this);
ImageButton toInfo = (ImageButton)findViewById(R.id.toInfo);
toInfo.setOnClickListener(this);
//this button is not in the same layoutactivity as the other 2.
ImageButton backPech = (ImageButton)findViewById(R.id.backPech);
backPech.setOnClickListener(this);
}
#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);
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);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.toPech:
startActivity(new Intent(getApplicationContext(), LocationActivity.class));
break;
case R.id.toInfo:
startActivity(new Intent(getApplicationContext(), InfoActivity.class));
break;
case R.id.backPech:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
break;
}
}
I would like to know what is wrong so that I can.
From your commented line:
//this button is not in the same layoutactivity as the other 2.
I think you have a NullPointerException.
While the Button "backPech" isn't in activity_main.xml, so calling findViewById(R.id.backPech); will return a null object ( backPech will be null).
And calling setOnClickListener(this); to a null object will cause the NullPointerException.
i have a code to change the text of textview in a layout according to the value of the edittext (et) in the previous layout >> somethig like this
I cannot comment, so i will help you editing. Use SharedPreferences to store the string from the edittext in order to get persistance. Then get the string from the SharedPreferences and do the same thing that you are doing(pass it through the intent)
there is MorningDrsGeneral :
public class MorningDrsGeneral extends ActionBarActivity {
Button button ;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.morningdrs);
et = (EditText) findViewById(R.id.et);
addListenerOnButton1();
}
public void addListenerOnButton1() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, bookingKamal.class);
intent.putExtra("fn" , et.getText().toString());
startActivity(intent);
}
});
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and there is bookingKamal.java :
public class bookingKamal extends ActionBarActivity {
Button button;
TextView textView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookingkamal);
textView3 = (TextView) findViewById(R.id.textView3);
String A = textView3.getText().toString();
String N = " ";
if (A.equals(N)){
Intent intent = getIntent();
String texx = intent.getStringExtra("fn");
textView3.setText(texx);
}
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So i have to keep the text in the bookingKamal activity .. it means when i go back from this layout and back to it the text should be the same as previous. And in this code it back to null :/ or
You have two options here:
Save the value into the internal file system so it can still will be loaded after the app has been unloaded
Save the value in the Activity which holds the button to this activity and save the text over there in a variable and when the bookingkamal activity starts, it could be read from somewhere (hint: Intent#putExtra("KEY", "VALUE"))
I am not describing how you should do it because there is enough documentation about it out there and that is not the point of this answer. This should give you an idea how to it.
You can do that by using sharedpreferences.
The above link will help you undderstand how to use it.
To add data to SharedPreferences use
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.apply();
And to retrieve
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}
Note : that SharedPreferences will save the value such that, even of you close the application and restart it. The values will still remain. So, make sure you clear the data when you done with it. You can read more about it here at the SharedPreferences docs.
In order to have the ActionBar in my application, my main activity extends from android.support.v7.app.ActionBarActivity. This is how it looks:
However, when I click in the overflow action button, the options show up over the ActionBar:
I wanted to show the overflow menu under the ActionBar, as it is supposed to. How can I solve this?
I'm running Android 4.4 (KITKAT). If you need any more details, just ask. Thanks.
Here is the code of my main activity:
public class SendMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_message);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_action_bar_icon);
getSupportActionBar().setDisplayUseLogoEnabled(true);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.activitySendMessage, new SendMessageFragment())
.commit();
}
}
#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_activity_send_message, 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.actionSettings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
if (id == R.id.actionShowHistory) {
startActivity(new Intent(this, SentMessagesHistoryActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}