[Q] onSaveInstanceState - Java for Android App Development

I'm new to android app development
Facing an issue:
Data (String values) lost while changing screen orientation
I googled about it and found it can be handled by onSaveInstanceState()
But didn't get how to use that in the java file
Can someone clear it to me?

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
@override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
 @override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}

ChahatGupta said:
I'm new to android app development
Facing an issue:
Data (String values) lost while changing screen orientation
I googled about it and found it can be handled by onSaveInstanceState()
But didn't get how to use that in the java file
Can someone clear it to me?
Click to expand...
Click to collapse
If It s so important then save it as file
Or save it as temporary data to Bundle
Code:
Bundle.putExtra("name", Data);
:good:

Related

[Q] Spinner problem

I have a little problem with my equations while using a spinner. What happens is user chooses option from spinner then enters three separate numbers in different EditText the calculation will perform as soon as the user hits the calculation button.
the originally return of the calculation is 0.0. until you again choose an option from the spinner and click calculate again. which then returns the correct answer.
thanks ahead of time.
Is there supposed to be a question in there somewhere?
Yeah sorry,
I guess I forgot to add the question.
Does anyone now why this is happening? should I put the onItemSelectionListener before the onClick. that part of the code looks somethink this.
Code:
btnCalc.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if ((ageEdit.getText().toString()== " " )
||(ageEdit.getText().length()== 0 )
||(heightEdit.getText().toString()== " ")
||(heightEdit.getText().length()== 0 )
||(weightEdit.getText().toString()== " ")
||(weightEdit.getText().length()== 0 )
)
{
showErrorAlert("Some Input are empty!",
input.getId());
}
else {
height = Double.parseDouble(txtwlHeight2.getText().toString());
weight = Double.parseDouble(txtwlWeight.getText().toString());
age = (int) Double.parseDouble(txtageinput01.getText().toString());
spnGender.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onNothingSelected(AdapterView<?> arg0){}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub{
switch (position){
case 0:
//some equation
break;
case 1:
//some equation
break;
}
}
});
// etc. such calculation out to text view.
Any Idea's anyone? I've does a lot of research and reading. Tried to re write code in different ways still no luck.. need help please.

[Q] AlertDialog (-> list with a lot of elements) how to handle orientation-change

Hi,
A few weeks ago I started developing an Android app but I've gut one problem
If the user changed the orientation of his phone the Activity is of course newly created. If there is ProgressDialog opened, I simply open a new one and the user does not realize it, but if I show an AlertDialog containing a few hundred elements and the user scrolls a bit he/she will realize it after I recreate the AlertDialog because the dialog will start again with the first element and the user has to scroll newly to the element he wants.
How I handle the "ListDialog":
At first I have two classes which simplify the ListDialog because I use it a few times...
ListDialog class:
Code:
public class ListDialog {
public static int CHOOSE_MODE_ONLINE = 0x01;
public static int CHOOSE_MODE_BOOKMARK = 0x02;
public static int CHOOSE_MODE_LOCAL = 0x03;
public static int CHOOSE_CHAPTER_ONLINE_DOWNLOAD = 0x04;
public static int CHOOSE_CHAPTER_BOOKMARK_DOWNLOAD = 0x05;
public static int CHOOSE_CHAPTER_ONLINE_READ = 0x06;
public static int CHOOSE_CHAPTER_BOOKMARK_READ = 0x07;
public static int CHOOSE_CHAPTER_LOCAL_READ = 0x08;
public static int CHOOSE_CHAPTER_LOCAL_DELETE = 0x09;
public static int GOTO_PAGE = 0x0A;
public static void show(Context context, String title, CharSequence[] elems, final ListMethodInvoker invoker)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setItems(elems, new DialogInterface.OnClickListener() {
%mail%Override
public void onClick(DialogInterface dialog, int which) {
invoker.invoke(which);
}
});
builder.setOnCancelListener(new OnCancelListener() {
%mail%Override
public void onCancel(DialogInterface dialog) {
invoker.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
ListMethodInvoker class:
Code:
public class ListMethodInvoker {
public void invoke(int id)
{
}
public void cancel()
{
}
}
and now I create the dialog:
Code:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
ListDialog.show(OnlineActivity.this,
mangaController.getManga().getMangaName(),
new CharSequence[]{"Add to Bookmarks", "Download a Chapter", "Read a Chapter"},
new ListMethodInvoker()
{
%mail%Override
public void invoke(int id)
{
ApplicationController.get().removeOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
switch(id)
{
case 0: addBookmark(mangaController.getManga()); break;
case 1:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_CHAPTER_ONLINE_DOWNLOAD);
handleChapter(ChapterMode.Download);
break;
case 2:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_CHAPTER_ONLINE_READ);
handleChapter(ChapterMode.Read);
break;
}
}
%mail%Override
public void cancel()
{
ApplicationController.get().removeOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
}
});
I also add the ID of the dialog to my ApplicationController which allows me to remember if a dialog has been openend and I can recreate it when onCreate(...) is called again.
(The ApplicationController uses the singleton design pattern which always allows me to retrieve the same instance of the ApplicationController.)
Thanks in advance
best regards
mike
btw: If you wonder why I write %mail% instead of the correct symbol, I get the following exception message if I use it: To prevent spam to the forums, new users are not permitted to post outside links in their messages. All new user accounts will be verified by moderators before this restriction is removed.

Help writing something with setOnItemClickListener

In my Android app, I have a sound that I want to play when a certain selection has been made from a spinner, but I want it to play the when the user actually makes the proper selection (or just after). My problem is that although the sound does play when they make the correct selection, as long as that selection stays chosen, it also plays every time the app starts up, when it should ONLY play at the time it's chosen. I think I need to change my setOnItemSelectedListener to setOnItemClickListener, but I'm not sure how (still pretty new to java). Can any generous soul out there show me how to change this up (assuming that's how to best solve this problem)?
Here is the code I have now:
Code:
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(
this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.bowchica);
mp.start();
} if(position == 4) {
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.debbie2);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I haven't try the below code but you can try it on your own and tell us.
In onCreate() declare MediaPlayer mp;
In every if statement that you use for check insert this code:
Code:
if(mp!=null){mp.release();}
int resid = R.raw.yoursound;
mp = MediaPlayer.create(this, resid);
After that override the methods onPause() and onResume() and insert this:
if(mp!=null){mp.release();}
If it is still playing a sound when you start your app, then you should check your code again if you have set as default option any of your selection options.
I would LOVE to try this out...Unfortunately, I'm way too dumb at this point point ot figure out exactly where those code snippets would go inside of what I already have.
Does anyone have a couple of minutes to show me where it would go?
Below is a sample code. Since i don't know your code I give you a snippet that you should adjust it to your code.
Code:
public class SampleSound extends Activity{
private Spinner fitnessSpinner;
private MediaPlayer mp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//here goes your layout
setViews();//here you will set all your views(spinners buttons textviews etc..)
setAdapters();//set your adapters here
setListeners();//
}
private void setListeners() {
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
if(mp!=null){mp.release();}
int resid = R.raw.bowchica;
mp = MediaPlayer.create(this, resid);
mp.start();
} if(position == 4) {
if(mp!=null){mp.release();}
int resid = R.raw.debbie2;
mp = MediaPlayer.create(this, resid);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void setAdapters() {
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
}
private void setViews() {
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
}
public void onResume(){
super.onResume();
if(mp!=null){mp.release();}
}
public void onPause(){
super.onPause();
if(mp!=null){mp.release();}
}
}
I really appreciate the help. I put the code in my routine, but it still plays the sound every time the activity is loaded (as long as the selection in the spinner is correct). It should only play the sound when the correct selection is made.
Any other ideas?
I am sure that your Spinner is set to some value (since you have values to display). Because your Spinner points to a selection (doesn't matter if you have selected or it is selected by default) your sound plays (even when you start the app).
A way to stop the sound playing at start is to declare and an other Item like you did with the previous 4 and set it as default selection of your Spinner.
To sum up:
1.You have to append in R.array.fitness_array an Item (like you did with the previous Items) and give it a name.
2.At the end of method setAdapters() insert this:
Code:
fitnessSpiner.setSelection(5);// or whatever is your selection number
Now it should work but you should know that this is not a good practice and you should try make a ListView or something else.
I'd be happy to change this out to a listview, or whatever would work. I just have to give my user a choice of 4 or 5 items, from which they can choose only one. Something like a drop down box, but in Android, I thought my only option was a spinner. But whatever I use, I have to be able to play a sound when certain items are chosen, but ONLY when those items are chosen, NOT whenever the activity is called up.
Any specific ideas of what I might change to?
What if I had another control like a textview or an edittext (with it's visibility property set to false) that I programatically populated with the users selection (when it's the selection that I want) and then have an OnItemClcickListener set to play the sound?
Could that work?
I will answer from the last to the top of your questions.
1.You can do whatever you want with android. You want TextViews and EditTexts with complex and nested Layouts you can do it. Write services that will communicate with your contacts through a content provider? You can do it.
Write, read and test code. Only this way you will actually learn.
2.Read developer.android.com. Read the android tutorials from there and specifically the Notepad example. You will learn a lot.
A good resource with small examples for ListViews is this.
3.Have you tried the changes I told you from the last post? Did it worked?
Since you just started with android and programming you must first be happy if you have the expected result and then read more to make your code better
Your suggested changes (fitnessSpiner.setSelection(5);// or whatever is your selection number) would stop the sound from playing, but defeat the apps purpose. Every time this activity is loaded, the spinners hit preferences to load the previously stored data. So if I force the spinner to a different selection to NOT play sound when the activity loads, then I would be displaying the wrong data for the user.
Yes you are right. So it is better to make a ListActivity. Read developer.android.com and the link i gave you before. You will be ok with this!
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Lakers16 said:
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Click to expand...
Click to collapse
onClickListener doesn't work for the spinner...I wish it did.
I REALLY need the drop down functionality of teh spinner, so I guess I'm going to try and figure out a way to have an invisible edittext that I set to the spinner selection and then use onClickListener or onChange...

[Q] EditText on use of SharedPreference displays junkValue

Hello All,
My functionality is.
- When user types his username and for some reason the application goes to onPause, then i should be able to retrieve the last entered data of the user.
-To achieve this, I have used sharedPreferences & PFB my code.
However, when I execute it, I get the restored username value like "[email protected]" and the value keeps changing for obvious reasons.
I have attached screenshot of the wrong value that i am getting during runtime.
Can anyone please help me with this?
public class RegistrationPage extends Activity {
public static final String PREF_uNAME = "MyPrefsFile";
private static final String TAG =RegistrationPage.class.getSimpleName() ;
//Set regPageDetails = new HashSet();
EditText regPage_userName;
EditText regPage_Passwd;
EditText regPage_eMailAddress;
String UserName;
TextView check1;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_page);
regPage_userName = (EditText) findViewById(R.id.regPage_editText_UserName);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.registration_page, menu);
return true;
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onResume(){
super.onResume();
SharedPreferences sharedPref_uName = getApplicationContext().getSharedPreferences(PREF_uNAME, MODE_PRIVATE);
Log.d(TAG,"shared preference value - string" + UserName);
regPage_userName.setText(sharedPref_uName.getString(PREF_uNAME, ""), TextView.BufferType.EDITABLE);
//regPage_userName.setText(sharedPref_uName.getString(PREF_uNAME, ""));
Log.d(TAG,"shared preference value - string" + regPage_userName.toString());
}
public void onPause(){
super.onPause();
UserName = regPage_userName.toString();
SharedPreferences sharedPref_uName = getSharedPreferences(PREF_uNAME, MODE_PRIVATE);
SharedPreferences.Editor editor_uName = sharedPref_uName.edit();
editor_uName.putString(PREF_uNAME, UserName);
editor_uName.commit();
}
public void onStop(){
super.onStop();
regPage_userName.setText("");
}
}
You're pulling the I'd of the edittext out of the shared pref instead of the value in it. Read up on shared preference methods. My github has a login page using shared pref, you could see that.
No, problem lies within onPause when he sets username to regPage_username.toString(). It should be regPage_username.getText().toString()
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0

Android Studio Fragments using Java

I'm working in a project that have 3 Fragments (List, Add and Update fragments)
The List Fragment have a RecyclerView and FloatingActionButton to add a new record.
the Add Fragments have the fields (EditText) to Add New Record
and the Update Fragment have the fields (EditText) to change Data and update.
When a new record is added, the data for this record can be viewed in the recycler. And clicking on any item in the recycler gives you the opportunity to delete or show the data of this item in the UpdateFragment.
my problem is that simple project is near to be finished but I have a big problem:
I'm not know how to send the data of clicked item on the RecyclerView to the UpdateData Fragment to show this data on the EditText in UpdateFragment and updat if I desire.
I'm created a Click.Listener on the RecyclerView Adapter when I click a row_layout in RecyclerView:
@override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Model model = arrayList.get(position);
final String id = model.getId();
final String titulo = model.getTitulo();
final String prioridad = model.getPrioridad();
final String descripcion = model.getDescripcion();
final String addTimeStamp = model.getAddTimeStamp();
final String updateTimeStamp = model.getUpdateTimeStamp();
// set views
holder.titulo.setText(titulo);
holder.descripcion.setText(descripcion);
// colorea el ImageView
switch(prioridad){
case "ALTA": holder.itemView.findViewById(R.id.priority_indicator).setBackgroundColor(Color.parseColor("#FF4646")); break; // rojo
case "MEDIA": holder.itemView.findViewById(R.id.priority_indicator).setBackgroundColor(Color.parseColor("#FFC114")); break; // amarillo
case "BAJA": holder.itemView.findViewById(R.id.priority_indicator).setBackgroundColor(Color.parseColor("#00C980")); break; // verde
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
//Toast.makeText(context, "CLICK EN UN ITEM", Toast.LENGTH_SHORT).show()
editDialog(
""+position,
""+id,
""+titulo,
""+prioridad,
""+descripcion,
""+addTimeStamp,
""+updateTimeStamp
);
}
});
//This take me to Update Fragment but I'm not have a way to send the holder data (id, titulo, prioridad, description) to UpdateFragment
holder.row_layout.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.action_listFragment_to_editRecordFragment);
}
});
}
Can anyone please know how to solve this problem?
Thank in advanced to all for read.

Categories

Resources