OnActivityResult () - java

I have code which should allow me to take value from calculator and use it further:
//-----------------This section creates the keypad functionality
for (int o = 0; o < keybuttons.length; o++) {
final int n = o;
keybuttons[o] = (Button) findViewById(data.keyIds[n]);
keybuttons[o].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String tmp = texts[selectEdit].getText()
.toString();
switch (n) {
case 3:
texts[selectEdit].setText(tmp.substring(0, tmp.length() - 1));
break; //get cursor position and delete char
case 7:
{
// Create intent for RealCalc.
Intent intent2 = new Intent("uk.co.quarticsoftware.REALCALC");
double x = 0; // Set initial value (double).
if (!texts[selectEdit].getText()
.toString()
.equals("")) {
x = Double.valueOf(texts[selectEdit].getText()
.toString());
}
intent2.putExtra("X", x);
// Launch calculator
try {
startActivityForResult(intent2, 0);
} catch (ActivityNotFoundException e) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=uk.co.nickfines.RealCalc"));
try {
startActivity(intent);
} catch (ActivityNotFoundException f) {
// Google Play Store app not available.
}
}
break;
} //open Calculator
case 11:
{
if (!tmp.contains("E")) texts[selectEdit].setText(tmp + "" + keybuttons[n].getText());
break;
} //check for E if dont have do default case
case 15:
{
TL.setVisibility(View.GONE);
break;
} //simulate back button
default:
{
texts[selectEdit].setText(tmp + "" + keybuttons[n].getText());
//get cursor start and end and get entire String
// replace selected String with button text
//insert back
break;
}
} //end of switch
} //end of try
catch (ActivityNotFoundException e) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=uk.co.nickfines.RealCalc"));
// Calculator not installed
} //calculator.num=n;
catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
EasyPhysActivity.error = sw.toString();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
// User pressed OK.
double value = data.getDoubleExtra("X", Double.NaN);
if (Double.isNaN(value)) {
// Calculation result was "Error".
} else {
// Calculation result ok.
}
} else {
// User pressed cancel or back button.
}
}
});
}
//----------------------------------------
But it doesn't like these three lines:
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
If I delete #Override it becomes better, but it still shows an error for
super.onActivityResult(requestCode, resultCode, data);
What is going wrong in here?

You cannot override onActivityResult inside OnClickListener because it does not exist in the base class. Move your onActivityResult code so that it is inside your Activity class, not the OnClickListner.

Related

How to crop two different images in the same activity with different parameters in Android?

I am using this Crop library by SoundCloud. Selecting one imageview, slecting image, cropping and showing the result in the imageview works fine. But now I am trying to do it with two different imageviews with different specifications. I am not getting any errors nor am I seeing any results. Here's what I have tried:
//My click listeners
regCoverPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
});
regUserProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
});
//Handling the result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK) {
beginCropProfile(data.getData());
}else if(requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK){
beginCropCover(data.getData());
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(requestCode, resultCode, data);
}
}
private void beginCropProfile(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).withAspect(ASPECT_X, ASPECT_Y).start(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
private void beginCropCover(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
private void handleCrop(int requestCode, int resultCode, Intent result) {
if (requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK) {
regCoverPhoto.setImageURI(Crop.getOutput(result));
mCoverPhotoUri = Crop.getOutput(result);
uploadCoverToStorage();
Log.d(TAG,"ResultCover: " + Crop.getOutput(result).toString());
}else if(requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK){
regUserProfile.setImageURI(Crop.getOutput(result));
mProfilePhotoUri = Crop.getOutput(result);
uploadProfileToStorage();
Log.d(TAG,"ResultProfile: " + Crop.getOutput(result).toString());
} else if (resultCode == Crop.RESULT_ERROR) {
Snackbar.make(getView(), Crop.getError(result).getMessage(), Snackbar.LENGTH_LONG).show();
}
}
I haven't used this library particularly, but custom request codes seem to be the problem.
Use different request codes for picking and cropping (total of 4 request codes) as you will need to handle them differently, and update onActivityResult(), handleCrop() to reflect that.
See https://gist.github.com/vibinr/fcf54c5e7ab63b9184432cc44c9a1494
List item
Here is a complete code of the images selection to crop and uploading to server using rest client with retrofit library Here few variables are used extra as for my use please ignore them
Also i'm using these library inside gradel
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
compile 'com.squareup.retrofit:retrofit:1.6.1'
And inside Mainfrest i have specifed this as <activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:screenOrientation="portrait" />
side2Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_side_2";
image_number_5 = "image_side_2";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
backImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_back";
image_number_6 = "image_back";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
if (image_name.equals("image_front")) {
image.setImageURI(result.getUri());
} else if (image_name.equals("image_top")) {
topImage.setImageURI(result.getUri());
} else if (image_name.equals("image_bottom")) {
bottomImage.setImageURI(result.getUri());
} else if (image_name.equals("image_side_1")) {
side1Image.setImageURI(result.getUri());
} else if (image_name.equals("image_side_2")) {
side2Image.setImageURI(result.getUri());
} else if (image_name.equals("image_back")) {
backImage.setImageURI(result.getUri());
}
cropped = result.getUri();
File path = getExternalCacheDir();
new File(String.valueOf(path)).mkdir();
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name22 = dateFormat.format(new Date());
// String helloWorld = cropped.toString();
// String hhhh=helloWorld.substring(helloWorld.indexOf(":")+1,helloWorld.indexOf("/"));
// String name="snehal_go";
savedFileDestination = new File(imagePath, name22 + ".jpg");
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("Webmirchi..", Context.MODE_PRIVATE);
String ALLOWED_CHARACTERS = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789qwertyuiopasdfghjklzxcvbnm";
Random generator = new Random();
randomStringBuilder = new StringBuilder();
int randomLength = 10;
for (int i = 0; i < randomLength; i++) {
randomStringBuilder.append(ALLOWED_CHARACTERS.charAt(generator.nextInt(ALLOWED_CHARACTERS.length())));
}
// Create imageDir
mypath = new File(directory, sessionMail + "-" + ProductId + ".jpg");
FileOutputStream fos = null;
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropped);
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
Log.i("File", mypath.toString());
if (image_name.equals("image_front")) {
uploadImage_front();
} else if (image_name.equals("image_top")) {
uploadImage_top();
} else if (image_name.equals("image_bottom")) {
uploadImage_bottom();
} else if (image_name.equals("image_side_1")) {
uploadImage_side1();
} else if (image_name.equals("image_side_2")) {
uploadImage_side2();
} else if (image_name.equals("image_back")) {
uploadImage_back();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(false)
.setMinCropWindowSize(600, 600)
.setAspectRatio(2, 2)
.setRequestedSize(500, 500)
.start(this);
}
Please refer the following url.This may help you. "https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/"
I'm not good in english...
// took extra int
static int a=0;
private void onClickData() {
cover_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=1;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
author_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=2;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==1){
// change the value again
a=0;
}
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==2){
// change the value again
a=0;
}
}

Voice Recognition without Google Dialog

I am trying to use the Speech recognition without dialog with RecognitionListener, but it doesn't work. The following codes are the way now I use, and the bottom codes (test part) are for checking that could phone receive my commanding. Additionally, I have added permissions Audio. Finally, I don't want there have any button.
This is my first time asking question, so hope I dont violate any unspoken rules.
Thank you very much,
public class Step extends AppCompatActivity {
private final int SPEECH_RECOGNITION_CODE = 1;
private TextView txtOutput;
private Button btnMicrophone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step);
txtOutput = (TextView) findViewById(R.id.txt_output);
btnMicrophone = (Button) findViewById(R.id.btn_mic);
startSpeechToText();
btnMicrophone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSpeechToText();
}
});
}
private void startSpeechToText() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "SPEAK");
try {
startActivityForResult(intent, SPEECH_RECOGNITION_CODE);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(), "Sorry! Speech recognition is not supported in this device.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SPEECH_RECOGNITION_CODE: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String text = result.get(0);
txtOutput.setText(text);
test(txtOutput.getText().toString());
startSpeechToText();
}
break;
}
}
}
public void test (String com) {
for(int i=0;i<com.length();i++) {
if (com.startsWith("good",i)) {
com = com + "123";
Toast.makeText(CookStep.this, com, Toast.LENGTH_SHORT).show();
}
}
if(com.compareToIgnoreCase("OK")==0){
com=com+"456";
Toast.makeText(CookStep.this, com, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CookStep.this, com, Toast.LENGTH_SHORT).show();
}
}
}

why Image can return to previous activity but not intent to new activity

Why image can be pass to previous activity but not intent to new activity?
ImageFitScreen.java
b = (ImageView) findViewById(R.id.imageView3);
public void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(ImageFitScreen.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);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
//pic = f;
// Toast.makeText(getApplicationContext(), Uri.fromFile(f) +"", Toast.LENGTH_LONG).show();
startActivityForResult(intent, 1);
} 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, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
finish();
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
//h=0;
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
//pic = photo;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOptions.inDither = true;
bitmapOptions.inSampleSize=8;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
Global.img = bitmap;
b.setImageBitmap(bitmap);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
//p = path;
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
//pic=file;
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
// h=1;
//imgui = selectedImage;
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ******", picturePath + "");
b.setImageBitmap(thumbnail);
}
}
else
{
finish();
}
}
ok.setOnClickListener(new View.OnClickListener() //back to Project1.java
{
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();
}
});
Project1.java
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); //image can be returned
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
b.setOnClickListener(new View.OnClickListener() { // back to Claims.java
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
returnIntent.putExtra("c",c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Claims.java
#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");
if (Global.img != null) {
v.setImageBitmap(Global.img); //image can shown here
}
c.setText(" " + name + "------" + "RM " + result);
break;
}
}
c.setOnClickListener(new View.OnClickListener() { //pass image to EditClaims.java
#Override
public void onClick(View v) {
if ((name != null && name.trim().length() > 0) && (result != null && result.trim().length() > 0)) {
Toast.makeText(getActivity().getApplicationContext(), "not null", Toast.LENGTH_LONG).show();
Global.img=null;
Intent intent = new Intent(getActivity(), EditClaims.class);
v.setDrawingCacheEnabled(true);
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
intent.putExtra("name", name);
intent.putExtra("result", result);
intent.putExtra("description", description);
if (v.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
startActivity(intent);
}
}
else {
Toast.makeText(getActivity().getApplicationContext(), "null", Toast.LENGTH_LONG).show();
}
}
} );
EditClaims.java
viewImage.setImageBitmap(Global.img);
Global.java
public class Global {
static Bitmap img;
}
But what I get in viewImage is (" " + name + "------" + "RM " + result) which is get from the c.setText. Can someone help me to figure out the problem?
Activity Flow: ImageFitScreen----->Back to project1----->Back to Claims----->Claims intent to EditClaims
Screen shot of Claims
Note that the image beside Amount is return from Project1. Since c.setText is not null, it can intent to EditClaims.java.
It works like charm, but only for captured image.
Now I try with the image from gallery
When I click c, it shows me this. It didn't intent to EditClaims.java
The problem is with the OnClickListener you're setting on c. That listener has a method public void onClick(View v), in which you're confusing your v variables.
Judging from the onActivityResult() method, you have a class member ImageView named v. But, within the onClick() method, an unqualified v is going to be the View v passed into the method, not the class member v. The View v passed into the onClick() method of an OnClickListener is the View that is being clicked, so this explains why you're seeing the content of c in the next Activity.
The simplest solution would be to change the parameter variable of the onClick() method to a different name. For example:
public void onClick(View view)

Pass bundle to if-statement

Activity Claims----> has 2 button and a textView (get the total amount)
Activity Project1 and Petrol-----> one editText and a save button
Activity Claims
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a2);
}
});
public void AlertDialogRadio(final int k) {
final CharSequence[] ClaimsModel = {"Project1", "Petrol"};
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);
intent.putExtra("k",k);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
intent.putExtra("k", k);
startActivityForResult(intent, 1);
}
** Either Project1 or Petrol, depends...)**
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
text= (EditText)findViewById(R.id.editText1);
Button save=(Button)findViewById(R.id.button12);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
l="A";
text = text.getText().toString();
returnIntent.putExtra("text", text);
returnIntent.putExtra("l", l);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
#Override
public void onBackPressed()
{
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
}
Is it possible to pass a bundle to if statement? I want to pass a value to another cases and finally total up the two values. How can I achieve this? Now I only get the value as and bs, but not value amount. I do believe it need to add a bundle to both if statement...
Continue Claims.java....
public void onActivityResult(int requestCode, int resultCode, Intent data) {
int button = data.getIntExtra("k1", 0); // to check which button was pressed
long a=0;
long as=0;
long bs=0;
String result;
String result1;
if (button == 1) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
String b = data.getStringExtra("l");
as=Long.parseLong(result);
c.setText(" " + b + "------" + "RM " + result);
Toast.makeText(getActivity(),as+"", Toast.LENGTH_LONG).show();
break;
case 1:
result = data.getStringExtra("text");
String b1 = data.getStringExtra("l");
as=Long.parseLong(result);
c.setText(" " + b1 + "------" + "RM " + result);
Toast.makeText(getActivity(),as+"", Toast.LENGTH_LONG).show();
break;
}
if(button==2)
{
switch (requestCode) {
case 0:
result1 = data.getStringExtra("text");
String b = data.getStringExtra("l");
bs=Long.parseLong(result1);
d.setText(" " + b + "------" + "RM " + result1);
Toast.makeText(getActivity(),bs+"", Toast.LENGTH_LONG).show();
break;
case 1:
result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("l");
bs=Long.parseLong(result1);
d.setText(" " + b1 + "------" + "RM " + result1);
Toast.makeText(getActivity(),bs+"", Toast.LENGTH_LONG).show();
break;
}
}
else if(requestCode==CAMERA_REQUEST_CODE)
{
}
long amount=as+bs;
Toast.makeText(getActivity(),amount+"", Toast.LENGTH_LONG).show();
I refer How can i pass a string value, that has been created in an if statement, through a bundle inside another if statement? but the answer is quite unclear for me.
The image for Claims
The toast should display 1 12 13 but I get 1 12 12. It seems like the value 1 cannot be added!
You should store the values you get passed in your onActivityResult in a variable of your Activity, and then directly read these variables for the Toast.
public class Claims{
long a, as, bs;
public void onActivityResult(int requestCode, int resultCode, Intent data) {
int button = data.getIntExtra("k1", 0);
String result;
if (button == 1) {
result = data.getStringExtra("text");
as=Long.parseLong(result);
} else if(button==2) {
result = data.getStringExtra("text");
bs=Long.parseLong(result1);
}
long amount=as+bs;
Toast.makeText(getActivity(),amount+"", Toast.LENGTH_LONG).show();
}
}
You still need to initialise your values according to your standards though.

Can't make button invisible from another activity

First, I click on Go to level one button in MainActivity to go to the LevelOne Activity from MainActivity, then I am going back to MainActivity and now here I need Go to level one button to be INVISIBLE.
I tried to accomplish this via SharedPreferences, but couldn't make it.
The code I posted below is working just fine, it just doesn't make my Go to level one button invisible when I go back to MainActivity.
I've done this so far:
MainActivity.java:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLevelOne:
Intent i = new Intent(this, LevelOne.class);
startActivityForResult(i, 1);
break;
case R.id.bLevelTwo:
break;
case R.id.bLevelThree:
break;
case R.id.bLevelFour:
break;
case R.id.bLevelFive:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
if (result == "milos") {
level1.setVisibility(View.INVISIBLE);
}
}
}
}
LevelOne.java:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.bMenu:
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "milos");
setResult(RESULT_OK, returnIntent);
finish();
break;
case R.id.bNextLevel:
break;
}
}
you have a problem over here.
if (result == "milos") {
level1.setVisibility(View.INVISIBLE);
}
it should rather be
if (result.equalsIgnoreCase("milos") {
level1.setVisibility(View.INVISIBLE);
}

Categories