How to transfer data from one app to another app in android - java

So, what I need here is to send data from App1 to App2. I've tried with simple code that I've made, but something is wrong here. I want to make a simple input on 1 editText in app1 then it will be received by app2.
Example :
App1 : EditText -> I input 'Hello!'
Then
App2 : TextView -> 'Hello!'
But what happens next, the textview in App2 does not show anything. What's wrong here?
These are my code that I've tried.
My Application 1:
secondAppButton = (Button)findViewById(R.id.secondAppButton);
namaEditText = (EditText)findViewById(R.id.namaEditText);
secondAppButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nama = namaEditText.getText().toString();
Intent secondApp = getPackageManager().getLaunchIntentForPackage("com.example.yosua.myapplication2");
Bundle bundleApp = new Bundle();
bundleApp.putString("namaOrang", nama);
secondApp.putExtras(bundleApp);
startActivity(secondApp);
}
});
My Application 2:
namaDariApp1 = (TextView)findViewById(R.id.namaApp2);
String nama;
Intent intent = getIntent();
Bundle extras = intent.getExtras();
nama = extras.getString("namaOrang");
namaDariApp1.setText(nama);

Try including the key
secondApp.putExtras("key",bundleApp);
And retrieve it like this
Bundle extras = intent.getBundleExtra("key");

You have to options to pass a value between two applications, The first one is by using ContentProviders are a good approach to share data between applications, or you can use a SharedPreferences something like this answer

Related

Having Trouble Passing And Recieving Data From My Intent

I'm trying to make a pretty simple app to help my girlfriend feel safer.
Im really bad at this, and a little help would go a long way. I've been trying to work with intents, and I really feel as if I'm super close to the solution at hand, I just need a little help.
So, the opening page is supposed to wait until you have data in your shared Preferences and then it will act on it.
The second page is supposed to take some data from EditTexts and store it in your intent. For some reason though, my data is not being stored, and when I pull something from the intent it is "".
CLASS 1:
public void ActivateAlarm(View view){
Bundle myBundle = getIntent().getExtras();
if(myBundle == null){
Log.i("The bundle is empty!", "Smashing success!");
}
else{
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
String NumberToCall = sharedPreferences.getString("CallNumber", "");
String TextOne = sharedPreferences.getString("1Text", "");
String TextTwo = sharedPreferences.getString("2Text", "");
String TextThree = sharedPreferences.getString("3Text", "");
Button myButton = (Button) findViewById(R.id.button);
myButton.setText(TextOne);
Log.i("MY NUMBER TO CALL", NumberToCall);
/*Take in the data from the settings. Check it for consistency.
1)Are the numbers empty?
2)Is the number 911 or a 7 digit number?
3)Do they have a passcode?
4)Is the number real? No philisophical BS
*/
}
}
CLASS 2:
public void GoToAlarm(View view){
EditText NumberToCall = (EditText) findViewById(R.id.callNumber);
EditText text1 = (EditText) findViewById(R.id.textNumOne);
EditText text2 = (EditText) findViewById(R.id.textNumTwo);
EditText text3 = (EditText) findViewById(R.id.textNumThree);
Intent intent = new Intent(this, AlarmActive.class);
intent.putExtra("callNumber", NumberToCall.getText().toString());
intent.putExtra("1Text", text1.getText().toString());
intent.putExtra("2Text", text2.getText().toString());
intent.putExtra("3Text", text3.getText().toString());
startActivity(intent);
}
I think the problem is coming from a bit of a mix-up between Intents and SharedPreferences.
An Intent is a way to pass data from one activity to another. You're passing data correctly in Class 2, but you're not retrieving it in Class 1. Here's how you can do that:
String NumberToCall = intent.getStringExtra("CallNumber");
String TextOne = intent.getStringExtra("1Text");
String TextTwo = intent.getStringExtra("2Text");
String TextThree = intent.getStringExtra("3Text");
SharedPreferences are a way to save user data. If you want to save data in addition to passing it between activities, you'll need to add it to SharedPreferences with the following code:
SharedPreferences preferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("callNumber", NumberToCall.getText().toString());
editor.putString("1Text", text1.getText().toString());
editor.putString("2Text", text2.getText().toString());
editor.putString("3Text", text3.getText().toString());
editor.apply();
You can retrieve the values with the code you were using in Class 1.

Is it possible to pass a int and a string both from one activty to another , if yes then how to achive it?

I am trying to send a string and a int type data from one activity to another but due to lack of knowledge i don't know how to do it.
With the particular coding given below now i can only send any one of the data type.
searched a lot but not found any answer appropriate for my question. If i have asked any thing wrong plzz notify me as i am new to android Dev.
Any help may be appreciated.
this is my java coding of the two activities :
First.java
public class QM extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qm);
}
public void FLG(View view) {
// Do something in response to button
EditText mEditText= (EditText)findViewById(R.id.editText1);
String str = mEditText.getText().toString();
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
startActivity(intent);
finish();
}
}
Second.java
public class Q1 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q1);
Intent intent = getIntent();
if (intent.hasExtra("myExtra")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!"); }
}
}
You can send 2 extras or even more as long you have different keys for it, so in your problem you need 2 extras one for String and one for Integer.
sample:
pass:
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
intent.putExtra("myExtraInt", yourInt);
get:
Intent intent = getIntent();
if (intent.hasExtra("myExtra") && intent.hasExtra("myExtraInt")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!");
int extraInt = intent.getIntExtra(myExtraInt);
}
I'd like to give you some information.
Imagine the Intent's extras to be a (theoretically) infinitely sized bagpack. You can put certain type of data into it in an infinite number as long as each of the data has a unique name which is a string.
Internally it's a table that maps names to values.
So: Yes you can put String and Int simultaneously into the Intent's extras like this.
String str = "Test";
int val = 2933;
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtra("MyStringExtraUniqueName", str);
i.putExtra("MyIntExtraUniqueName", val);
To check for it use i.hasExtra("MyStringExtraUniqueName") as you did already and to get it use i.getExtra("MyStringExtraUniqueName").
BUT if you only use getExtra you'll be returned data of type object. Remember to cast the returned value to the appropriate type or use one of the specialized getter methods for some predefined data types.
See this for the available getters: http://developer.android.com/reference/android/content/Intent.html
Bundle data = new Bundle();
data.putInt("intKey", 5);
data.putString("stringKey", "stackoverflow");
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtras(data);
//And in the second acitvity fetch this way
Bundle data = getIntent().putExtras(b);

Passing an ID over an intent

I am trying to pass the ID of the clicked on data from my listview to a new activity in a second class i.e. I click the item on the listview.The onListItemClick method is called and starts a new intent. The id is passed with the object in the i.getExtra. Then the id is stored into a new variable on the second class to be used later.
Ive got as far as working out how to pass the id, but I cant seem to work out how I then store it in the new variable on the second class.
Heres my code:
public void onListItemClick(ListView list, View v, int list_posistion, long item_id)
{
long id = item_id;
Intent i = new Intent("com.example.sqliteexample.SQLView");
i.putExtra(null, id);
startActivity(i);
}
Could anyone tell me how to reference it in the second class?
You need to get Bundle from Intent and then do get... to get particular element.
Bundle extras = getIntent().getExtras();
String id;
if (extras != null) {
id= extras.getString("key"); //key should be what ever used in invoker.
}
One thing surprising is why you are using null as key? I would avoid using reserve words, instead use proper name like userID etc.,
Intent intent = new Intent("com.example.sqliteexample.SQLView");
Bundle bundle = new Bundle();
bundle.putString("position", v.getTag().toString());
intent.putExtras(bundle);
context.startActivity(intent);
in second class
Bundle intent= getIntent().getExtras();
if (intent.getExtras() == null) {
id= intent.getString("position");
}
Hope this helps
It is very simple.
Just change :
i.putExtra(null, id);
with :
i.putExtra("myId", id);
and in the second Activity just use :
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getInt("myId");
}
The first parameter for Intent.putExtra() is a String key used to identify your Extra. Instead of i.putExtra(null, id) try i.putExtra("SomeString", id).
Then, in the onCreate of (or anywhere within) your second activity, you can get your id back from the intent like this:
Intent intent = getIntent();
long id = intent.getLongExtra("SomeString");
There are also methods for getting Strings, Chars, Booleans, Ints, and more complex data structures. Check here: http://developer.android.com/reference/android/content/Intent.html for more info on methods for the Intent class.

Moving spinner items in a Bundle from one activity to another

I'm trying to get the value from a Spinner on my android application and convert it into a String so I can move it over as a data item in a Bundle to another activity. I have successfully managed to move EditText values over using the combination of getText().toString(); methods. I'm looking for the same result but with Spinner items now but have so far had no success.
Here's the code:
This method is called when a user selects a button in the onClick method:
public void commitData(){
Bundle bundle = new Bundle();
bundle.putString("key", txtBuildingName.getText().toString()); //Gets the TEXT that the TEXTVIEW was holding converts it to a String and adds to the Extras bundle
Bundle bundle1 = new Bundle();
bundle1.putString("key1", txtDescription.getText().toString()); // Same again
Bundle bundle2 = new Bundle();
bundle2.putString("key2", type.getItemAtPosition(type.getSelectedItemPosition()).toString());
Bundle bundle3 = new Bundle();
bundle3.putString("key3", project.getItemAtPosition(project.getSelectedItemPosition()).toString());
Intent newIntent = new Intent(this.getApplicationContext(), DataSummary.class);
newIntent.putExtras(bundle);
newIntent.putExtras(bundle1);
startActivityForResult(newIntent, 0);
}
I am getting no results from the project and type lines of code using type.getItemAtPosition().getSelectedItemPosition()).toString(); and the same for project.
Shown below is the code for the Activity that receives and output this data from the entry form.
TextView resultName;
TextView resultDescription;
TextView resultType;
TextView resultProject;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_summary);
//Check if there is anything in the 'bundle' and if not produce message - AVOIDS NULLPOINTEREXCEPTION when navigating to Activity
Bundle bundle = this.getIntent().getExtras();
if (bundle != null){
String name = bundle.getString("key");
String description = bundle.getString("key1"); //gets data from DataEntry activity
String type = bundle.getString("key2");
String project = bundle.getString("key3");
resultName=(TextView)findViewById(R.id.resultName); //adds the TextViews to the activity
resultType=(TextView)findViewById(R.id.resultType);
resultDescription=(TextView)findViewById(R.id.resultDesc);
resultProject=(TextView)findViewById(R.id.resultProject);
resultName.setText(name); // Fills the textviews with imported data
resultType.setText(type);
resultDescription.setText(description);
resultProject.setText(project);
}
else
{
Toast.makeText(DataSummary.this,"Received no data yet!", Toast.LENGTH_LONG).show();
}
}
Anyone got any ideas how to successfully gather the data from the Spinner item?
Why are you passing different bundles? On the side of your receiving Activity you are only getting the first bundle, I guess.
Try your code with these edits:
public void commitData(){
Bundle bundle = new Bundle();
bundle.putString("key", txtBuildingName.getText().toString()); //Gets the TEXT that the TEXTVIEW was holding converts it to a String and adds to the Extras bundle
bundle.putString("key1", txtDescription.getText().toString()); // Same again
bundle.putString("key2", type.getItemAtPosition(type.getSelectedItemPosition()).toString());
bundle.putString("key3", project.getItemAtPosition(project.getSelectedItemPosition()).toString());

Sending Bundle/data to another class or screen

What am I doing wrong?
I've looked at other questions and thought I was doing the exact same things, but since its not working for me, obviously I'm doing something wrong!
I have my MainActivity.class that gets JSON data (coordinates) from a URL. This part works. I then want to load up a MapView, called OverlayActivity.class, and send this data to this map so I can populate it with overlays etc.
I pull varying numbers of points down and dynamically create buttons. Depending on what button is clicked, it sends different data.
Here's the code for this loop:
final LinearLayout layout = (LinearLayout) findViewById(R.id.menuLayout);
layout.removeAllViewsInLayout();
String itemName="";
int itemID=0;
for (int i = 0; i < dataSetsMap.size(); i++) {
itemID=i+1;
itemName=dataSetsMap.get(itemID);
Button b = new Button(this);
b.setText(itemName);
layout.addView(b);
// These need to be final to use them inside OnClickListener()
final String tempName=itemName;
final int tempID=itemID;
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
Bundle b = new Bundle();
i.setClass(myContext, OverlayActivity.class);
Log.i(TAG, "Setting extras: 1:"+tempName+" and 2:"+tempID);
b.putInt(tempName, tempID);
i.putExtras(b);
startActivity(i);
}
});
} // End for()
So obviously I want to read this data on the other side, assuming I'm sending it correctly. So, to read it, I've been trying a few different things:
//Method 1:
String test1=intent.getStringExtra("name");
String test2=intent.getStringExtra("id");
//Method 2:
String meh=getIntent().getExtras().getString("id").toString();
String bleh=getIntent().getExtras().getString("name");
//Method 3:
String value=savedInstanceState.getString("name");
String id=savedInstanceState.getString("id").toString();
//Method 4:
Bundle bundle = getIntent().getExtras();
String id=bundle.getString("id");
String value = getIntent().getExtras().getString("name");
i get a NullPointerException when trying to use any of these methods. Its my first time using these types of methods so can someone point me in the right direction or tell me where I've gone wrong?
Firstly, using Bundle b when you've already got Button b isn't really a good idea if for no other reason than it gets confusing, ;)
Secondly, you don't need to use a Bundle to pass a string and an int. Just add them to your Intent directly...
Intent i = new Intent(myContext, OverlayActivity.class);
i.putExtra("name", tempName);
i.putExtra("id", tempID);
startActivity(i);
To retrieve them in your OverlayActivity use...
Intent i = getIntent();
String name = i.getStringExtra("name");
int id = i.getIntExtra("id", -1); // -1 in this case is a default value to return if id doesn't exist
Why not just do this:
Intent i = new Intent();
i.setClass(myContext, OverlayActivity.class);
Log.i(TAG, "Setting extras: 1:"+tempName+" and 2:"+tempID);
i.putExtra("name", tempName);
i.putExtra("id", tempID);
startActivity(i);
and then you can fetch them with:
String name = getIntent().getStringExtra("name", "");
int id = getIntent().getIntExtra("id", 0);

Categories

Resources