Passing an ID over an intent - java

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.

Related

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

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

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);

List view row pressed

I have a list view with couple of items and i set this function get call when a row in the list view is clicked.
I want to open new activity and send him an object from an array of objects.
I have a problem with this line :
Intent i = new Intent(this, Item_Activity.class);
because the this is now no the activity.
this is the code:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent i = new Intent(this, Item_Activity.class);
Item item = m_items.get(position);
i.putExtra("object", item);
startActivity(i);
}
});
Problem:
You are passing the wrong context in
Intent i = new Intent(this, Item_Activity.class);
Solution:
Use : YourActivityName.this instead if using simply this
eg. Intent i = new Intent(CurrentActivityName.this, Item_Activity.class);
Add ActivityName.this instead of this only,
Intent i = new Intent(ActivityName.this, Item_Activity.class);
is your Item is parcelable, if not make this object parcelable by following link:
http://prasanta-paul.blogspot.in/2010/06/android-parcelable-example.html
Your object has to be either serializable or parcelable and I don't think you can pass
an array into an intent read this - How to pass an object from one activity to another on Android
more to that
passing an array in intent android

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);

How do i use putExtra/get_Extra when working with intents?

I have a list where each item is a row in an sqlite table, i'm trying to pass the row id of the item they clicked on from one activity to the next.
Here's the method im trying to set up in activity A,
public static final int REQUEST_CODE=0; //variable used when i want to startActivityForResult..
public void ListItemCommonIntent(long id, View view){
Log.i("Blah", "current item pressed is" + id);
Intent keypadIntent = new Intent(view.getContext(), Keypad.class);
keypadIntent.putExtra(Keypad.selectedRowId, id);
startActivityForResult (keypadIntent, REQUEST_CODE);
}
And here's where i'm trying to get the id in activity b and put it in selectedRowId
public Long selectedRowId;
private String findBudgetQuery = "SELECT BUDGET_AMOUNT FROM CAT_BUD_TAB WHERE _ID='" + selectedRowId + "'";
public void FindBudgetForId(){
//This method should query for current budget and..
SQLiteDatabase db = budgetData.getWritableDatabase();
selectedRowId = getIntent().getLongExtra(selectedRowId, 1);
db.rawQuery(findBudgetQuery, null);
}
However i just cant get it to work, i think i need more information, can someone explain to how to use putExtra and the get something on the otherside. I think i don't fully understand the parametres on even method.
Starting an intent with an extra field.
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(mContext, org.gpsagenda.DetailsContainer.class);
intent.putExtra("id", item.ID());
mContext.startActivity(intent);
}
Getting the extra field in the started activity.
int id = getIntent().getExtras().getInt("id");
Beware though that you can get null if the Extra is not set!
The first parameter of putExtra and getExtra should be a string that you use to identify the information you're passing. For example:
intent.putExtra("mySelectedRowId", rowId);
You can use this same key to fetch the information later, the second parameter being a default value to use if the key is not found:
selectedId = intent.getLongExtra("mySelectedRowId", 1);

Categories

Resources