Search code examples
javaandroidandroid-intentandroid-activity

How to receive data from one activity to another - android


I'm trying to send an integer from one activity to another in Android studio. In my source class I have sent the data using putExtra() and in the recipient class, I am trying to receive it using getIntent(). However, I get the error 'Could not resolve method 'getIntent()' in the recipient class. Here is my code:

I'm a total newbie to Android studio as well as Java so if I'm missing something really obvious, please be considerate.

Source Activity:

public class AugmentedImageActivity extends AppCompatActivity {

  private ArFragment arFragment;
  private ImageView fitToScanView;

  // Augmented image and its associated center pose anchor, keyed by the augmented image in
  // the database.
  private final Map<AugmentedImage, AugmentedImageNode> augmentedImageMap = new HashMap<>();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);
    fitToScanView = findViewById(R.id.image_view_fit_to_scan);

    arFragment.getArSceneView().getScene().addOnUpdateListener(this::onUpdateFrame);
  }

  @Override
  protected void onResume() {
    super.onResume();
    if (augmentedImageMap.isEmpty()) {
      fitToScanView.setVisibility(View.VISIBLE);
    }
  }

  /**
   * Registered with the Sceneform Scene object, this method is called at the start of each frame.
   *
   * @param frameTime - time since last frame.
   */
  private void onUpdateFrame(FrameTime frameTime) {
    Frame frame = arFragment.getArSceneView().getArFrame();

    // If there is no frame or ARCore is not tracking yet, just return.
    if (frame == null || frame.getCamera().getTrackingState() != TrackingState.TRACKING) {
      return;
    }

    Collection<AugmentedImage> updatedAugmentedImages =
        frame.getUpdatedTrackables(AugmentedImage.class);
    for (AugmentedImage augmentedImage : updatedAugmentedImages) {
      switch (augmentedImage.getTrackingState()) {
        case PAUSED:
          // When an image is in PAUSED state, but the camera is not PAUSED, it has been detected,
          // but not yet tracked.
            int value=augmentedImage.getIndex();
            Intent i = new Intent(AugmentedImageActivity.this, AugmentedImageNode.class);
            i.putExtra("key",value);
            startActivity(i);
          String text = "Detected Image " + augmentedImage.getIndex();
          SnackbarHelper.getInstance().showMessage(this, text);
          break;

        case TRACKING:
          // Have to switch to UI Thread to update View.
          fitToScanView.setVisibility(View.GONE);

          // Create a new anchor for newly found images.
          if (!augmentedImageMap.containsKey(augmentedImage)) {
            AugmentedImageNode node = new AugmentedImageNode(this);
            node.setImage(augmentedImage);
            augmentedImageMap.put(augmentedImage, node);
            arFragment.getArSceneView().getScene().addChild(node);
          }
          break;

        case STOPPED:
          augmentedImageMap.remove(augmentedImage);
          break;
      }
    }
  }
}

Recipient activity:

public class AugmentedImageNode extends AnchorNode {

  private static final String TAG = "AugmentedImageNode";

  // The augmented image represented by this node.
  private AugmentedImage image;

  private static CompletableFuture<ModelRenderable> ulCorner;

  public AugmentedImageNode(Context context) {

       Intent intent = getIntent();
       Bundle extras = intent.getExtras();
       int value = extras.getInt("key");

          if (value == 0) {
              // Upon construction, start loading the models for the corners of the frame.
              if (ulCorner == null) {
                  ulCorner =
                          ModelRenderable.builder()
                                  .setSource(context, Uri.parse("models/tinker.sfb"))
                                  //.setSource(context, Uri.parse("models/borderfence-small2.sfb"))
                                  .build();
                   }
          }
}
@SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"})
  public void setImage(AugmentedImage image) {
    this.image = image;

    // If any of the models are not loaded, then recurse when all are loaded.
    if (!ulCorner.isDone())// || !urCorner.isDone() || !llCorner.isDone() || !lrCorner.isDone())
      {
      CompletableFuture.allOf(ulCorner)//, urCorner, llCorner, lrCorner)
          .thenAccept((Void aVoid) -> setImage(image))
          .exceptionally(
              throwable -> {
                Log.e(TAG, "Exception loading", throwable);
                return null;
              });
    }

    // Set the anchor based on the center of the image.
    setAnchor(image.createAnchor(image.getCenterPose()));

    // Make the 4 corner nodes.
    Vector3 localPosition = new Vector3();
    Node cornerNode;
localPosition.set(-0.0f * image.getExtentX(), 0.1f, +0.5f * image.getExtentZ());
    cornerNode = new Node();
    cornerNode.setParent(this);
    cornerNode.setLocalPosition(localPosition);
    cornerNode.setLocalRotation(Quaternion.axisAngle(new Vector3(-1f, 0, 0), 90f));
    cornerNode.setRenderable(ulCorner.getNow(null));
}

    private void setLocalRotation() {
    }

    public AugmentedImage getImage() {
    return image;
  }
}

Solution

  • Here is code how to use share preference in your scenario.I hope it will help you.

    Instead of below code

    Intent i = new Intent(AugmentedImageActivity.this, AugmentedImageNode.class);
    i.putExtra("key",value);
    startActivity(i);
    

    Use this one

     SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
    Editor editor = pref.edit();
    editor.putInt("Key", "int value");  
    editor.commit();
    

    And retrieve preference value on your AugmentedImageNode screen using below code

    SharedPreferences settings = getSharedPreferences("MyPref", MODE_PRIVATE);
    int snowDensity = settings.getInt("Key", 0); //0 is the default value