I have some problem as I mention in my question. I have two activity, Activity A and Activity B. When I Enter some data in Activity A, then I press next button, it will redirect to Activity B. At Activity B, I also enter some data. When I press back button, the data at Activity A is display as I entered before. When I press next button, the data that I entered at Activity B is missing. Below is my SharedPreferences code.
Activity A:
public class NewSuggestion extends AppCompatActivity {
private EditText etYear, etMonth, etTitle, etOwnValue;
private RadioGroup rgSuggestWill;
private RadioButton radioButton;
private Button btnNext;
ArrayAdapter<CharSequence> adapter;
private Spinner spReviewer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etTitle = findViewById(R.id.etTitle);
etYear = findViewById(R.id.etYear);
etMonth = findViewById(R.id.etMonth);
rgSuggestWill =findViewById(R.id.rgSuggestWill);
final Calendar c = Calendar.getInstance();
String mm = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int yy = c.get(Calendar.YEAR);
etYear.setText(new StringBuilder().append(yy));
etMonth.setText(new StringBuilder().append(mm));
spReviewer = findViewById(R.id.spReviewer);
adapter = ArrayAdapter.createFromResource(this,R.array.reviewer,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spReviewer.setAdapter(adapter);
spReviewer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("title",etTitle.getText().toString());
editor.putString("year",etYear.getText().toString());
editor.putString("month",etMonth.getText().toString());
// get selected radio button from radioGroup
int selectedId = rgSuggestWill.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
editor.putString("suggestionwill",radioButton.getText().toString());
if (spReviewer.getSelectedItem().toString().equals("Please choose")){
AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please choose your reviewer");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}else{
editor.putString("reviewer",spReviewer.getSelectedItem().toString());
Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
startActivity(intent);
}
editor.apply();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(NewSuggestion.this, DashboardApp.class);
startActivity(intent);
}
}
Activity B:
public class NewSuggestion2 extends AppCompatActivity {
private EditText etPresent, etDetails, etBenefit;
private ImageView imgAttach,btnCamera,btnGallery;
private Button btnNext,btnClear;
private Intent intent;
private Bitmap bitmap;
private int REQUEST_CODE = 1;
public static final int RequestPermissionCode = 1 ;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion2);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION (Cont..)");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
btnCamera=findViewById(R.id.btnCamera);
EnableRuntimePermission();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
btnGallery=findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Photo"),REQUEST_CODE);
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
Intent intent = new Intent(NewSuggestion2.this,ConfirmSuggestion.class);
startActivity(intent);
}
});
btnClear = findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgAttach.setImageBitmap(null);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 7 && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imgAttach.setImageBitmap(bitmap);
}
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imgAttach.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(NewSuggestion2.this,
Manifest.permission.CAMERA))
{
Toast.makeText(NewSuggestion2.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(NewSuggestion2.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(NewSuggestion2.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSuggestion2.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onBackPressed() {
}
}
Assign value to present,details,benefit from sharedpref
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));
In Activity B make sure you save data in onBackPressed()
#Override
public void onBackPressed() {
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
super.onBackPressed();
}
You have to override the onBackPress() method.In Activity B it is necessary to put data in to SharedPreferences.
#Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.commit();
}
Related
I want to get the image from one activity to another activity. I tried converting the image to byte array in sender activity (PhotoActivity) and decoding the array to form original bitmap image on the receiver side (MainActivity) on the click of button 'btdn' but this isn't working. The image is visible in the sender activity's imageview but it stops when the button is clicked. This is my code:-
PhotoActivity.java
public class PhotoActivity extends Activity {
ImageView vitb;
Button btcm, btdn;
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_IMAGE_SELECT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
vitb = findViewById(R.id.imageView);
btcm = findViewById(R.id.btn_cam);
btdn = findViewById(R.id.btn_back);
btcm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
btdn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable drawable = vitb.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, bs);
byte[] byteArray = bs.toByteArray();
Intent nIntent = new Intent();
nIntent.putExtra("PICTURE", byteArray);
setResult(RESULT_OK, nIntent);
finish();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,REQUEST_IMAGE_SELECT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap bmp;
Bundle bundle = data.getExtras();
bmp = (Bitmap)bundle.get("data");
vitb.setImageBitmap(bmp);
}
else if (requestCode == 2) {
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]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
//ImageView imageView = findViewById(R.id.imageView);
vitb.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
}
MainActivity.java
public class MainActivity extends Activity{
private static final int REQUEST_CODE1 = 101;
private static final int REQUEST_CODE2 = 102;
Button btnLoc, btnPic;
Button btnSubmit;
TextView tvLoc;
ImageView image;
String phoneNumber = "9000000000";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSubmit = findViewById(R.id.btnSubmit);
btnLoc = findViewById(R.id.btnLoc);
btnPic = findViewById(R.id.btnPic);
tvLoc = findViewById(R.id.textView3);
image = findViewById(R.id.img);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
SmsManager.getDefault().sendTextMessage(phoneNumber, null, "Hello!", null, null);
}
catch (Exception e) {
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(MainActivity.this);
AlertDialog dialog = alertDialogBuilder.create();
dialog.setMessage(e.getMessage());
dialog.show();
}
}
});
btnLoc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,LocActivity.class);
startActivityForResult(intent,REQUEST_CODE1);
}
}
);
btnPic.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,PhotoActivity.class);
startActivityForResult(intent,REQUEST_CODE2);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_CODE1 && data !=null) {
String strMessage = data.getStringExtra("loc");
tvLoc.setText(strMessage);
}
if(requestCode == REQUEST_CODE2 && data !=null) {
Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("PICTURE");
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
image.setImageBitmap(bmp);
}
}
}
}
I am currently facing 2 problems, the spinner state is not saving and when I am on the InformationActivity the spinner is reset. I have used the information on other posts but it doesnt seem to help.
At the moment I cant use finish(); in my onBackPressed(); on InformationActivity because it goes back to the ScannerView as I am Implementing the ZXing library. How could I save the Spinner state and also stop the program from crashing onBackPressed when I am on HomeActivity.
Thanks.
HomeActivity:
public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private FirebaseAuth firebaseAuth;
private Button buttonLogout;
private ZXingScannerView scannerView;
private final int permission_code = 1;
String [] selectedProfile;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this, MainActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
if (savedInstanceState != null) {
spinner.setSelection(savedInstanceState.getInt("yourSpinner", 0));
// do this for each of your text views
}
else {
//android spinner to select profile
spinner = (Spinner) findViewById(R.id.spinnerProfiles);
adapter = ArrayAdapter.createFromResource(this, R.array.restrictions, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
}
//opens camera when button is pressed
public void scanBarcode(View view) {
//check if user given app camera permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, permission_code);
}
//opens camera
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZXingScannerResultHandler());
//stops camera and scannerview
setContentView(scannerView);
scannerView.startCamera();
}
//selects an item from the spinner and passes it to InformationActivity
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getBaseContext(), item + " Selected", Toast.LENGTH_SHORT).show();
switch (position){
case 0:
selectedProfile = getResources().getStringArray(R.array.Wheat);
break;
case 1:
selectedProfile = getResources().getStringArray(R.array.Crustaceans);
break;
case 2:
selectedProfile = getResources().getStringArray(R.array.Eggs);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
//stops camera and outputs barcode result to a Toast
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
String resultBarcode = result.getText();
Intent intent = new Intent(getApplicationContext(), InformationActivity.class);
intent.putExtra("BarcodeString", resultBarcode.toString());
intent.putExtra("ProfileArray", selectedProfile);
startActivity(intent);
scannerView.stopCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == permission_code) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
}
}
//go back to home after permissions accepted
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
scannerView.stopCamera();
}
//goes back to homepage when back button is pressed
#Override
public void onBackPressed() {
setContentView(R.layout.activity_home);
scannerView.stopCamera();
}
//stops the camera on pause
#Override
public void onPause(){
super.onPause();
scannerView.stopCamera();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("yourSpinner", spinner.getSelectedItemPosition());
}
}
InformationActivity:
public class InformationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
TextView barcodeView = (TextView) findViewById(R.id.tvBarcode);
barcodeView.setText(getIntent().getExtras().getString("BarcodeString"));
TextView profileView = (TextView) findViewById(R.id.tvProfile);
String[] selectedProfile = getIntent().getStringArrayExtra("ProfileArray");
profileView.setText(selectedProfile[0]);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}
}
To Save Spinner posotion in sharedpreference :
int userChoice = spinner.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner",usersChoice);
prefEditor.commit();
Get Data from sharedpreferences :
SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner",-1);
if(spinnerValue != -1) {
// set the selected value of the spinner
spinner.setSelection(spinnerValue);
}
Also look into this :
One Another Example to save : https://stackoverflow.com/a/29527936/8448886
SharedPreference Tutorial :https://www.journaldev.com/9412/android-shared-preferences-example-tutorial
when you select any item from spinner at that time get that selected item and store that position and after when you come back to activity load spinner first, compare that item with array items and get position of that item then set that position to spinner i think this way you get exact selection of that item into spinner.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I programmed a quiz now I set up a mediaplayer under the FOR-query, that every time the user hits a correct answer the sound will be played. Now in the same Activity I want that bttOFF will mute the sound of the Activity how can I do that? I set up an onClickListener with mp.setVolume(0,0); But the app crashes on restart. Thanks for looking! :D
public class QuizActivity extends AppCompatActivity {
private ActionBarDrawerToggle mToggle;
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
final MediaPlayer mp = new MediaPlayer();
//Dialog 1
createDialog();
Button dialogButton = (Button) findViewById(R.id.dialogbtn);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//end Dialog 1
//Dialog 2
createDialog2();
Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
dialogButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.show();
}
});
closeButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
}
});
//end Dialog 2
Button bttON = (Button)findViewById(R.id.bttON);
bttON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.setVolume(0,0);
}
});
TextView shareTextView = (TextView) findViewById(R.id.share);
shareTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
startActivity(Intent.createChooser(myIntent, "Share with:"));
}
});
mQuestionLibrary.shuffle();
setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"
((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_stats:
startActivity(new Intent(QuizActivity.this, Menu2.class));
break;
case R.id.nav_about:
startActivity(new Intent(QuizActivity.this, Menu3.class));
break;
}
return true;
}
});
mScoreView = (TextView) findViewById(R.id.score_score);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (Button) findViewById(R.id.choice1);
mButtonChoice2 = (Button) findViewById(R.id.choice2);
mButtonChoice3 = (Button) findViewById(R.id.choice3);
final List<Button> choices = new ArrayList<>();
choices.add(mButtonChoice1);
choices.add(mButtonChoice2);
choices.add(mButtonChoice3);
updateQuestion();
for (final Button choice : choices) {
choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (choice.getText().equals(mAnswer)) {
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sample.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
updateScore();
updateQuestion();
Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore); // pass score to Menu2
startActivity(intent);
}
}
});
}
}
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
} else {
Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizActivity.this, Menu2.class);
intent.putExtra("score", mScore);
startActivity(intent);
}
}
private void updateScore() {
mScoreView.setText(String.valueOf(++mScore));
SharedPreferences mypref = getPreferences(MODE_PRIVATE);
int highScore = mypref.getInt("highScore", 0);
if (mScore > highScore) {
SharedPreferences.Editor editor = mypref.edit();
editor.putInt("highScore", mScore);
editor.apply();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
private void createDialog() {
dialog = new Dialog(this);
dialog.setTitle("Tutorial");
dialog.setContentView(R.layout.popup_menu1_1);
closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}
private void createDialog2() {
dialog2 = new Dialog(this);
dialog2.setTitle("Settings");
dialog2.setContentView(R.layout.popup_menu1_2);
closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
}
Logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at shapy.appz.QuizActivity.onCreate(QuizActivity.java:96)
your get to findViewById fro your closeButton and closeButton2
As shown in the documentation for the MediaPlayer class [here]( https://developer.android.com/reference/android/media/MediaPlayer.html#setVolume(float, float) ) the needed parameters are floats. You could try to do this:
public void onClick(View v) {
mp.setVolume( 0.0, 0.0 );
}
And see if that solves your problem.
setVolume
added in API level 1
void setVolume (float leftVolume, float rightVolume)
Sets the volume on this player. This API is recommended for balancing the output of audio streams within an application. Unless you are writing an application to control user settings, this API should be used in preference to setStreamVolume(int, int, int) which sets the volume of ALL streams of a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0. UI controls should be scaled logarithmically.
Parameters
leftVolume float: left volume scalar
rightVolume float: right volume scalar
I have 3 activities, A, B and C.The flow of activity is from A to B then C. From C, all the images and value will be returned to B then A. All the returned value and image will be loaded in listView A.
The listView is clickable and once it is clicked, it will intent to B to do some edition. But the problem now is when I edit the text value in B and return to A, I get a new list instead of updating the old one.
What's wrong here ? Anyone can help?
Activity C
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fit_screen);
selectImage();
b = (ImageView) findViewById(R.id.imageView3);
t = (EditText) findViewById(R.id.editText38);
cancel=(Button)findViewById(R.id.button15);
ok=(Button)findViewById(R.id.button16);
cancel.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
finish();
}
});
ok.setOnClickListener(new View.OnClickListener()
{ // return to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Activity B
ImageButton imageButton;
ImageView viewImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt = (EditText) findViewById(R.id.editText36);
txt1=(TextView)findViewById(R.id.textView57);
Button b = (Button) findViewById(R.id.button17);
addListenerOnButton();
viewImage = (ImageView) findViewById(R.id.imageView2);
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img);
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Global.img=null;
Intent i = new Intent(B.this,C.class);
startActivityForResult(i, PROJECT_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) { // receive fom C
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); // image from C can be shown here
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
}
Activity A
public class Claims1 extends Fragment {
ListView listV;
String description;
String result="";
String name;
long as=0;
TextView c;
ImageView v;
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
String Text;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
setHasOptionsMenu(true);
View claims = inflater.inflate(R.layout.receipt_text, container, false);
v=(ImageView)claims.findViewById(R.id.imageView4);
listV = (ListView) claims.findViewById(R.id.listView1);
android.support.v7.app.ActionBar myActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
myActionBar.setHomeButtonEnabled(true);
ImageView imageView = new ImageView(myActionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
adapter=new ArrayAdapter<String>(getActivity(),R.layout.claims,R.id.textView1,m_listItems);
android.support.v7.app.ActionBar.LayoutParams layoutParams = new android.support.v7.app.ActionBar.LayoutParams(
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL); // for icon in action bar
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
myActionBar.setCustomView(imageView);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
if(name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap",true);
intent.putExtra("name",name);
intent.putExtra("result",result);
startActivityForResult(intent,0);
}
}
});
return claims;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.my_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create1:
AlertDialogRadio();
return true;
}
return (super.onOptionsItemSelected(item));
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"B", "Petrol"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Class");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(),B.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, 1);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
m_listItems.add(Text);
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
if (Global.img != null) {
v.setImageBitmap(Global.img);
}
as = Long.parseLong(result);
c.setText(" " + name + "------" + "RM " + result);
break;
}
}
Edited
Add a global variable in A - private int mClickedPosition;
Add mClickedPosition = position; in OnItemClick
then
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
m_listItems.set(mClickedPosition,Text);
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
11-16 18:15:54.751 23044-23044/com.example.project.project
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 23044
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=0, result=-1, data=Intent {
(has extras) }} to activity
{com.example.project.project/com.example.project.project.MainActivity}:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.deliverResults(ActivityThread.java:3681)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3724)
m_listItems.set(mClickedPosition,Text);
in your activity A onActivityResult method when you return from activity B after editing you are adding new item into arraylist using this code m_listItems.add(Text);
instead of adding new item you update the array list using this code
m_listItems.set(position Text);
Try edit your code like this:
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
if (m_listItems.size() == 0) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition,Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
I have a button in Claims.java. When button is pressed, it will show Alert Dialog Window with radio buttons.If the radio button is checked, it will goes to specific activity. In the activity, it has an editText and a save button. I want the value on the editText display on the button(Claims.java) when the save button in the activity is clicked.
Claims.java >> AlertDialog Window in Claims.java >> AlertDialogRadio.java
I use startActivityForResult() to receive a result back from AlertRadioDialog.java. But the problem now is it will display AlertDialogRadio which is not what I want and the text does not display on the textView. How can I do to achieve this?
Claims.java
public class Claims extends Fragment {
private TextView c;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.claims, container, false);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
AlertDialogRadio();
}
};
Button button1 = (Button) claims.findViewById(R.id.button10);
Button button = (Button) claims.findViewById(R.id.button8);
button1.setOnClickListener(listener);
c=(TextView)claims.findViewById(R.id.textView49);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), CameraMain.class);
startActivity(intent);
}
});
return claims;
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivity(intent);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivity(intent);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivity(intent);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivity(intent);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivity(intent);
}
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("text");
c.setText(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
Assume the user choose Project.
Project1.java
public class Project1 extends AppCompatActivity {
private static String text;
private static EditText txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
text = txt.getText().toString();
returnIntent.putExtra("text", text);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
First of all, you're not using startActivityForResult at all.
Here's how you should proceed:
Claims.java
public static final int PROJECT_REQUEST_CODE = 1;
public static final int CAMERA_REQUEST_CODE = 2;
public static .....
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
else if .....
And in OnActivityResult :
if (requestCode == PROJECT_REQUEST_CODE) {
...
}
else if(requestCode == CAMERA_REQUEST_CODE) {
...
}
else if ...