So I have a Spinner and a EditText to login. The array of the Spinner owns "Anonymous" and " Owner" (means "Anonymous" is 0 and "Owner" is 1 in the array). When you choose "Anonymous" the password is "0000" and when you choose "Owner" the password is "1234".
But when I choose "Owner", the password "1234" is wrong and the Logcat shows "Anonymous". How can I make "Owner" selected? Maybe getSelectedItemPosition() is wrong?
My Code:
public class PinEnterActivity extends AppCompatActivity {
Button nextButton;
EditText pinEditText;
Spinner pinRoleSpinner = null;
private String TAG = "PinEnterActivity";
private Byte selectedUserRole = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pin_enter);
nextButton = findViewById(R.id.nextActivity)
pinEditText = findViewById(R.id.pinET);
pinRoleSpinner = findViewById(R.id.roleSpinner);
selectedUserRole = (byte) pinRoleSpinner.getSelectedItemPosition();
switch (selectedUserRole) {
case 0:
Log.i(TAG, "Anonymous");
SharedPreferences sharedpreferences = getSharedPreferences("My_Prefs", 0);
final String password = sharedpreferences.getString("pass", "");
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pinEditText.getText().toString().equals("0000")) {
Intent intent = new Intent(PinEnterActivity.this, NextActivity.class);
startActivity(intent);
} else {
pinEditText.setError("Password incorrect");
Animation shake = AnimationUtils.loadAnimation(PinEnterActivity.this, R.anim.shake);
pinEditText.startAnimation(shake);
return;
}
}
});
break;
case 1:
Log.i(TAG, "Owner");
SharedPreferences preferences = getSharedPreferences("My_Prefs", 0);
final String password2 = preferences.getString("pass", "");
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pinEditText.getText().toString().equals("1234")) {
Intent intent = new Intent(PinEnterActivity.this, NextActivity.class);
startActivity(intent);
}else{
pinEditText.setError("Password incorrect");
Animation shake = AnimationUtils.loadAnimation(PinEnterActivity.this, R.anim.shake);
pinEditText.startAnimation(shake);
return;
}
}
});
}
}
I finally found out the right answer.
pinRoleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(selectedUserRole) {
case 0:
Log.i(TAG, "Anonymous");
// Code
break;
case 1:
Log.i(TAG, "Owner");
// Code
break;
default;
// Code
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Related
I'm using the Retrofit2 Library to consume Rest API with a post request that delivers data in query parameters not in body. Now I want to integrate that api but retrofit stops us from providing data as a query parameters through a post request. It is possible to use a post request with retrofit to deliver data in query parameters?
Here is API Interface
#POST("calculation")
Call<QuestionResponse> calculation(
#Query("height") Double height,
#Query("age") Integer age,
#Query("gender") Boolean gender,
#Query("current_weight") Double current_weight,
#Query("activity_level") Double activity_level,
#Query("user_id") Integer user_id
Here is Question.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentWeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if (rbMale.isSelected()) {
gender= Boolean.valueOf("0");
}
if (rbFemale.isSelected()) {
gender= Boolean.valueOf("1");
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
}
}
public void openHomePage() {
Double userHeight = Double.valueOf(height.getText().toString());
Double userWeight = Double.valueOf(weight.getText().toString());
Integer userAge = Integer.valueOf(age.getText().toString());
if(rgGender.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please Select Gender", Toast.LENGTH_SHORT).show();
return;
}
Intent i=new Intent(BMIquestions.this,ActivityLevel.class);
i.putExtra("age",userAge);
i.putExtra("height",userHeight);
i.putExtra("weight",userWeight);
i.putExtra("gender",gender);
startActivity(i);
Here is Activity_level.java
public class ActivityLevel extends AppCompatActivity implements View.OnClickListener {
ImageButton next;
ImageButton previous;
CardView card1,card2,card3,card4;
SharedPreferenceManager sharedPreferenceManager;
SharedPreferences.Editor editor;
TextView l1,l2,l3,l4;
Double activity_level;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
getSupportActionBar().hide();
next = findViewById(R.id.NextButton);
previous = findViewById(R.id.PreviousButton);
card1 = (CardView) findViewById(R.id.level1);
card2 = (CardView) findViewById(R.id.level2);
card3 = (CardView) findViewById(R.id.level3);
card4 = (CardView) findViewById(R.id.level4);
card1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.55;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.725;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.75;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=2.04;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openHomePage();
}
});
sharedPreferenceManager=new SharedPreferenceManager(getApplicationContext());
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.PreviousButton:
openBMIPage();
break;
}
}
public void openHomePage() {
Integer age= Integer.valueOf(getIntent().getStringExtra("age"));
Boolean gender= Boolean.valueOf(getIntent().getStringExtra("gender"));
Double height= Double.valueOf(getIntent().getStringExtra("height"));
Double weight= Double.valueOf(getIntent().getStringExtra("weight"));
Integer userId= sharedPreferenceManager.getUser().getUserId();
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(height,age,gender,weight,activity_level,userId);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ActivityLevel.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(ActivityLevel.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void openBMIPage() {
Intent intent1 = new Intent(this, BMIquestions.class);
startActivity(intent1);
}
}
After Debugging
Connected to the target VM, address: 'localhost:52230', transport: 'socket'
Disconnected from the target VM, address: 'localhost:52230', transport: 'socket'
How do I fix this?
I have two activities, Activity 1 and Activity 2. Activity 1 contains 8 buttons, each button sends some data to Activity 2 through intents and Activity 2 takes data and shows in listview. I want to show data in listview based on the condition so in Activity 2 I put every button data in a if blockSo my problem isWhat condition I should place in if(condition?) to know which button is clicked in Activity 1 my Activity 1
public void hmoral(View v){
moralref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
List<String> moraldata = new ArrayList<>();
Map<String,Object> map = task.getResult().getData();
for (Map.Entry<String,Object> entry:map.entrySet()){
moraldata.add(entry.getKey());
Log.d(TAG,entry.getKey());
}
Intent intent1 = new Intent(Activity1.this,Activity2.class);
intent1.putExtra("moraldata", (Serializable) moraldata);
startActivity(intent1);
}
}
});
}
public void hhorror(View v){
horrorref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
List<String> horrordata = new ArrayList<>();
Map<String,Object> map = task.getResult().getData();
for (Map.Entry<String,Object> entry:map.entrySet()){
horrordata.add(entry.getKey());
Log.d(TAG,entry.getKey());
}
Intent intent = new Intent(Activity1.this,Activity2.class);
intent.putExtra("horrordata", (Serializable) horrordata);
startActivity(intent);
}
}
});
}
}
code of Activity2 below:
public class ListAcivity extends AppCompatActivity {
ListView originallist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_acivity);
originallist = findViewById(R.id.originallist);
if (){
ArrayList<String> morallist = getIntent().getStringArrayListExtra("moraldata");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,morallist);
originallist.setAdapter(arrayAdapter);
}
if (){
ArrayList<String> horrorlist = getIntent().getStringArrayListExtra("horrordata");
ArrayAdapter<String>arrayAdapter1 = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,horrorlist);
originallist.setAdapter(arrayAdapter1);
}
}
how to know which button is clicked in other activity
Send Button id using intent to next Activity :
intent.putExtra("clicked_view_id", view.getId());
Now use clicked_view_id with switch case to compare with Button ids:
int clickedButtonID = getIntent().getIntExtra("clicked_view_id", 0);
switch(clickedButtonID){
case R.id.button1:
...
break;
case R.id.button2:
...
break;
}
In your activity1 :
Private String buttonText ="";
yourButtonClick.setOnClickListener(this);
#Override
public void onClick(View view) {
buttonText = getIntent().getStringExtra("btn_text");
switch (view.getId()) {
case R.id.button1:
buttonText = "buttonOne";
break;
case R.id.button2:
buttonText = "buttonTwo";
break;
case R.id.button8:
buttonText = "buttonEight";
break;
}
}
}
Intent intent = new Intent(Activity1.this,Activity2.class);
intent.putExtra("btnClicked", buttonText);
startActivity(intent);
// In list activity
String btnClicked = getIntent().getStringArrayListExtra("btnClicked");
I don't know if anyone can offer some guidance on this.
I have a main class where a user will input their name. I then want the user to choose a game from the options available in the action/app bar. When they choose their game, the name they entered in the main class will then be showing on the game class. I hope that makes sense?
I know this involves passing data from one activity to another using intents but every tutorial I see involves setting up a button in the main class (so using something like onclicklistener) but I don't want a button. I want choosing the menu option to do the same job but I can't find anywhere how to do it.
Thanks in advance.
EDIT - ATTEMPTED CODE ADDED
Main class:
public class GameCentral extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_central_layout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.commonmenus, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.guessingGame) {
startActivity(new Intent(this, Task3Activity.class));
switch (item.getItemId()) {
case R.id.playerNameEntered:
startActivity(this, Task3Activity.class).putExtra(playerNameInput, value);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
else if (id ==R.id.placeOne) {
Toast.makeText(this, "Game Placeholder One option is Clicked", Toast.LENGTH_SHORT).show();
}
else if (id ==R.id.placeTwo) {
Toast.makeText(this, "Game Placeholder Two option is Clicked", Toast.LENGTH_SHORT).show();
}
else if (id ==R.id.placeThree) {
Toast.makeText(this, "Game Placeholder Three option is Clicked", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
Game Class
public class Task3Activity extends GameCentral {
public Button rtnBtn;
// button to return to Game Central at any point when clicked
public void init() {
rtnBtn = (Button)findViewById(R.id.returnBtn);
rtnBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent homeScreen = new Intent(Task3Activity.this, GameCentral.class);
startActivity(homeScreen);
}
});
}
String value;
int attempts = 0;
final int maxAttempts = 1;
Random randGen = new Random();
int ranNum;
private SoundPlayer sound;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task3_layout);
init();
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getString("Value1");
if (value != null) {
TextView dataRcvd = (TextView) findViewById(R.id.playerNameEntered);
dataRcvd.setText(value );
}
}
sound = new SoundPlayer(this);
final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
final EditText userGuess = (EditText) findViewById(R.id.etNumber);
Button pressMe = (Button) findViewById(R.id.btnGuess);
final Button rtnButton = (Button) findViewById(R.id.returnBtn);
int min = 1;
int max = 19;
randGen = new Random();
// Generate number once
ranNum = randGen.nextInt(max - min + 1) + min;
final Toast toast = Toast.makeText(getApplicationContext(), "Please guess between 0 and 20", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 350);
// When the button is clicked, it shows the text assigned to the txtResponse TextView box
pressMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean correct = false;
final AlertDialog.Builder alert = new AlertDialog.Builder(Task3Activity.this);
alert.setTitle("Unlucky");
alert.setCancelable(false);
alert.setMessage("You have guessed incorrectly three times. " +
"The answer was " + ranNum + ". " + "Would you like to play again?")
//.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//dialog.dismiss();
Intent i = new Intent(Task3Activity.this, Task3Activity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
alert
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
//Task1Activity.this.finish();
dialog.dismiss();
//finishAffinity();
Intent toy = new Intent(Task3Activity.this, GameCentral.class);
startActivity(toy);
}
;
});
final AlertDialog.Builder alert2 = new AlertDialog.Builder(Task3Activity.this);
alert2.setTitle("You Did It!");
alert2.setCancelable(false);
alert2.setMessage("The answer was " + ranNum + ". " + "Would you like to play again?")
//.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//dialog.dismiss();
Intent i = new Intent(Task3Activity.this, Task3Activity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
alert2
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
//Task1Activity.this.finish();
dialog.dismiss();
Intent toy = new Intent(Task3Activity.this, GameCentral.class);
startActivity(toy);
//finishAffinity();
}
;
});
int userNumber = Integer.parseInt(userGuess.getText().toString());
if ((userNumber < 1) || (userNumber > 19)) {
//guessText.setText("Please guess between 0 and 20");
//guessText.setBackgroundColor(Color.WHITE);
toast.show();
} else if (userNumber < ranNum) {
guessText.setText("Your answer is too low. Guess again!");
guessText.setBackgroundColor(Color.YELLOW);
//sound.playBuzzerSound();
} else if (userNumber > ranNum) {
guessText.setText("Your answer is too high. Guess again!");
guessText.setBackgroundColor(Color.RED);
//sound.playBuzzerSound();
} else if (userNumber == ranNum) {
ranNum = randGen.nextInt(20);
//guessText.setText("You did it!");
//guessText.setBackgroundColor(Color.WHITE);
correct = true;
alert2.show();
sound.playApplauseSound();
}
if (attempts++ > maxAttempts && !correct) {
alert.show();
sound.playBooSound();
//guessText.setText("You have guessed incorrectly three times. The answer was " + ranNum);
} else if (correct) {
} else {
String randText = "";
randText = Integer.toString(ranNum);
textResponse.setText("");
userGuess.setText("");
}
}
}
);
}
}
Because you are not passing a Bundle in your intent, you don't need to use getIntent().getExtras();.
GameCentral:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.guessingGame:
Intent intent = new Intent(GameCentral.this, Task3Activity.class);
intent.putExtra("PlayerName", "Name");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Task3Activity:
public class Task3Activity extends AppCompatActivity {
...
#Override
public void onCreate(Bundle savedInstanceSate) {
...
String playerName = getIntent().getStringExtra("PlayerName");
if (playerName != null) {
TextView dataRcvd = (TextView) findViewById(R.id.playerNameEntered);
dataRcvd.setText(playerName);
}
}
...
}
intent.putExtra("PlayerName", "Name"); where "Name" is the string for where you get the player's name from. You need to create the EditText object within the scope of the Activity if you want to get the player's name from a text box.
if (id == R.id.guessingGame) {
startActivity(new Intent(this, Task3Activity.class));
switch (item.getItemId()) {
case R.id.playerNameEntered:
Bundle b = getIntent().getExtras();
value= b.getString("playerNameInput");
startActivity(this, Task3Activity.class).putExtra("playerNameInput", value);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
In my case, I use bundle to get string in onOptionsItemSelected function evertime.
To active this, should send data(playerNameInput) when you change activity everytime.
I'm trying to used sharedpreferences for when a user chooses a specific custom image they want in their storage for a part of a grid of images. I want the image they chose to show up even after they close the application and reopen it. The problem I'm having is that the sharedpreferences don't seem to be working. Nothing shows up as the background image for the grid item they've selected once they've closed the app or even just pressed the back button.
Do I have to create a sharedpreferences file myself? I can't figure out how to get to it or create one if so using androidstudio.
Here's my code for the class (Sorry if it's long and messy...I am new to coding and still testing things):
public class editCreations extends Activity {
public int mPosition = 0;
protected static Sounds sound = new Sounds();
private static int RESULT_LOAD_IMAGE = 1;
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private String mOutputFile = Environment.getExternalStorageDirectory().getAbsolutePath();
private Drawable mImageFileName;
private Button recordBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private ImageButton imgBtn;
private Drawable bg;
private String mPicturePath;
private ImageAdapter img = new ImageAdapter(this);
View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(editCreations.this, "test", Toast.LENGTH_SHORT);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setOutputFile(mOutputFile);
recordBtn = (Button)findViewById(R.id.create_record_button);
recordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start(view);
}
});
stopBtn = (Button)findViewById(R.id.create_stop_record_button);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stop(view);
}
});
playBtn = (Button)findViewById(R.id.create_play_button);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play(view);
}
});
stopPlayBtn = (Button)findViewById(R.id.create_stop_button);
stopPlayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopPlay(view);
}
});
imgBtn = (ImageButton)findViewById(R.id.imageButton);
Intent extra = getIntent();
Bundle extras = extra.getExtras();
// gave mPosition a default int to debug and find problem -> found it
mPosition = extras.getInt("position");
getSelectedFile(mPosition);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
public void start (View view) {
try {
mRecorder.prepare();
mRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recordBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(editCreations.this, mPosition + "!", Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
stopBtn.setEnabled(false);
recordBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void play(View view) {
try{
mPlayer = new MediaPlayer();
mPlayer.setDataSource(mOutputFile);
mPlayer.prepare();
mPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void getSoundPosition(int position) {
mOutputFile = mOutputFile + "/Lollatone_clip_" + mPosition + ".3gpp";
// use to get proper image and sound files and edit output file to proper name
}
public void getSelectedFile(int position) {
switch (mPosition) {
case 0:
imgBtn.setBackgroundResource(R.drawable.sample_0);
imgBtn.refreshDrawableState();
break;
case 1:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 2:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 3:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 4:
imgBtn.setBackgroundResource(R.drawable.sample_4);
imgBtn.refreshDrawableState();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_creations, 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);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPicturePath = cursor.getString(columnIndex);
cursor.close();
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
// String picturePath contains the path of
// selected image
}
}
protected void onPause() {
super.onPause();
//need an editor object to make preference changes
// all objects are from android.context.Context
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("img_" + mPosition, mPicturePath);
editor.commit();
}
protected void onResume() {
super.onResume();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
mPicturePath = sharedPref.getString("img_" + mPosition, "img_" + mPosition);
}
}
You are using SharedPreferences correctly but you are not placing the code in the right activity lifecycle methods. You are reading the preference on onCreate() and saving on onStop() so maybe what you can do it save the preference on onPause() (to make sure it gets saved earlier) and reload on onResume() instead of onCreate() (the latter only occurs once in the life cycle of an activity).
Also, you might want to check if Context.getSharedPreferences() would be a better choice for this, since it's shared between more than just one activity.
I'm making a custom dialer and everything till now was perfect. Now while testing, I saw that the "#" sign was not working properly. It shows on the dialer but while calling, it goes away. For eg, if I dial *121#, it becomes *121 when the call is being made through the stock dialer. Here is the code for my activity-
public class DialPadActivity extends Activity {
private EditText numberField = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeButtonArrowClickListeners();
}
public void dialButtonClick(View v) {
int buttonId = v.getId();
putNumberToEditText(buttonId);
}
public void buttonPhone_click(View v) {
if (numberField != null) {
String phone = numberField.getText().toString();
String uriString = "tel:" + phone;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uriString));
startActivity(intent);
}
}
public void putNumberToEditText(int buttonId) {
switch (buttonId) {
case R.id.dial_button0:
putNumber("0");
break;
case R.id.dial_button1:
putNumber("1");
break;
case R.id.dial_button2:
putNumber("2");
break;
case R.id.dial_button3:
putNumber("3");
break;
case R.id.dial_button4:
putNumber("4");
break;
case R.id.dial_button5:
putNumber("5");
break;
case R.id.dial_button6:
putNumber("6");
break;
case R.id.dial_button7:
putNumber("7");
break;
case R.id.dial_button8:
putNumber("8");
break;
case R.id.dial_button9:
putNumber("9");
break;
case R.id.dial_button_s:
putNumber("*");
break;
case R.id.dial_button_p:
putNumber("#");
break;
}
}
public void putNumber(String number) {
if (numberField == null) {
numberField = (EditText) findViewById(R.id.phone_number_field);
}
numberField.append(number);
}
private void initializeButtonArrowClickListeners() {
ImageButton buttonArrow = (ImageButton) findViewById(R.id.button_arrow);
buttonArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (numberField != null && numberField.length() > 0) {
String previousNumbers = numberField.getText().toString();
String numbersMinusTheLast = previousNumbers.substring(0,
numberField.length() - 1);
numberField.setText(numbersMinusTheLast);
}
}
});
buttonArrow.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (numberField != null) {
numberField.setText("");
}
return false;
}
});
}
Where am I doing the wrong?
Use URLEncoder.encode(string, "UTF-8");
For example:
String uriString = "tel:" + URLEncoder.encode(phone, "UTF-8");
Replace your # symbol with %23.
That is: *121%2311 instead of *121#11
String uri = "tel:" + "*6133%235345";
Intent intent;
intent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(intent);
the output for this is : *6133#5345