Anu
Anu

Reputation: 773

Pass java variables from javacode to javascript code in react-native

I want to pass and display the image and text received through Intents in MainActivity.java file in android code into my JavaScript file in react-native.

Here is the code to get data through intents in my MainActivity.java file code

@Override
  protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();

        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if ("text/plain".equals(type)) {
                handleSendText(intent); 
            } else if (type.startsWith("image/")) {
                setContentView(R.layout.activity_main);
                imageView = (ImageView) findViewById(R.id.sentImage);
                handleSendImage(intent);
            } 
        }else {
            // Handle other intents, such as being started from the home screen
        }
    }


  void handleSendText(Intent intent) {
          String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
           if (sharedText != null) {
             AlertDialog.Builder builder = new AlertDialog.Builder(context);
             builder.setMessage(sharedText);
             AlertDialog alertDialog = builder.create();
             alertDialog.show();
           }
   }

   void handleSendImage(Intent intent) {
        Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
          if (imageUri != null) {
            imageView.setImageURI(imageUri);
          }else{

          }
    }

Upvotes: 2

Views: 997

Answers (1)

Ayush Bansal
Ayush Bansal

Reputation: 722

Try this

import com.facebook.react.bridge.Callback;


// a callback is used to provide the function call result to JavaScript.

@ReactMethod
public void getImageNText(Callback successCallback,Callback errorCallback)

{
try{

  //Do your stuff here 
  // let say result of text is storedin respText and image in respImg
  // to send it to Javascript side 
  successCallback.invoke(respText,respImg);
 }catch(Exception e){
  errorCallback.invoke(e.getMessage());
}



}

Now to read it on javascript side

"YourModuleName".getImageNText(

(text,image) => {/*successCallback*/
// do your stuff with image and 
},
(error) => {// handle error} ///*errorCallback*/
);

Also give this a read for better understanding

Upvotes: 1

Related Questions