Home » Android » How to send data through intent in android without opening another activity?

How to send data through intent in android without opening another activity?

Posted by: admin June 15, 2020 Leave a comment

Questions:

here is my code for sending data by intent but i don’t want open another activity i just want to send the data without opening it..

Bundle contain = new Bundle();
            contain.putString("key4", item);
            contain.putString("price", price);

Intent a  = new Intent(Searchbydate.this, Searchbyitem.class);
            a.putExtras(contain);
            startActivity(a); 

here i don’t want to open this Searchbyitem.class just send the data…

How to&Answers:

Yes i have also faced this problem .

Many developers also facing problems when passing data from dialog to another activity through Intent or Bundle. It returns null at the retrieving time from another activity.

And the only solution is SharedPreferences.

But you have to place it inside the dismiss button.( ex: ok/cancel etc)

And retrieve the data from another activity easily through the same key. Do not use any service followed by broadcast intent .

The code in dialog activity is like this:

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(R.drawable.mailicon);
    builder.setTitle(name);
    builder.setView(view);

    builder.setPositiveButton("Send Request",new DialogInterface.OnClickListener()
    {

     @Override 
     public void onClick(DialogInterface dialog,    int which) {
     String mailID = id.getText().toString();

     //Here define all your sharedpreferences code with key and value
     SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
     SharedPreferences.Editor edit = prefs.edit();
     edit.putString("MID", mailID );
     edit.commit();

    }

});

And from another fetch the data like this:

    SharedPreferences bb = getSharedPreferences("my_prefs", 0);
    String m = bb.getString("NUM", "");
    Toast.makeText(this, m, Toast.LENGTH_SHORT).show();

Add some checkings for a good standard.

Thank you

Answer:

You call also use SharedPreferences to archieve that

Answer:

You probably want to use a Service not an activity.

Read:
http://developer.android.com/guide/components/fundamentals.html#Components

Answer:

You can try EventBus or Otto Android libraries to communicate between activities, services and fragments..

So you should create a Service to pass data and for communication between activities, fragments etc use an event bus