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);
Related
I need to delete an item permanently from ListView and then from database. I have a DatabaseHandler.java class, which has the delete function as:
// Deleting single contact, in DatabaseHandler.java class
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
Then I have a FriendList.java class, when the user's friends are displayed as an item in ListView. When I long press on an item, then I get the option of "Delete" and "Cancel" in Dialog Box. Now, when I click on delete, the item is deleted from the ListView, but, not from the database. How can I delete it from database as well?
The code for getting the option of "Delete" and "Cancel"
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
Intent i = new Intent(FriendList.this, Delete_Confirm.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
//I am sending position of listitem in putExtra below//
i.putExtra("position", position);
startActivityForResult(i,CONFIRM);
item2 = (String) arg0.getItemAtPosition(position);
//Toast.makeText(FriendList.this, "Clicked"+item2, Toast.LENGTH_SHORT).show();
int l = item2.length();
c=0;
for(int j=0; j<=l; j++){
if(item2.charAt(j) != '9' || item2.charAt(j+1) != '1'){
c++;
}
else {
//Do nothing
break;
}
num = item2.substring(c, l);
}
Toast.makeText(FriendList.this, "Clicked: "+num, Toast.LENGTH_SHORT).show();
return true;
}
});
The corresponding code for onActivityResult is as follows:
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (CONFIRM) :
if(resultCode==RESULT_OK){
int posi = data.getIntExtra("position",0);
Log.d("msg","position is " + posi);
Log.d("msg","Do we reach here?");
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
//db.deleteContact(posi);
list.remove(posi);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
break;
}}
Please suggest how can I delete it from database as well. Any help would be highly appreciated.
EDIT:
On uncommenting db.deleteContact(posi), I get the following error:
The method deleteContact(Contact) in the type DatabaseHandler is not applicable for the arguments (int)
Note that the function deleteContact has contact variable of the type Contact.
Its a compilation error.
You need to pass a Contact object to the method, not an integer.
When you delete.... Try Deleting first from database then from ListView..
example:
db.deleteContact(list.get(posi)); // this will get string
list.remove(posi);
DatabaseHandler class.......
public void deleteContact(String name){
Log.d("Name:",""+ name);
db.delete(TABLE_CONTACTS, KEY_NAME + " = ?", new String[] { name });
}
You can delete from database first then from ListView. And suggest Iterator to remove list element.
I think the problem is that position is not the corresponding id in the database. A possible solution would be to add a tag with the database id of the contact you have in this listitem. And when you remove it you get the tag with the id and delete the item from the database.
Edit (added clarification):
I would add in your listviewadapter something like:
yourcontactview.setTag(contact.getId());
in which you add to your view a tag with the database id of the corresponding contact.
Then where you delete the contact I would get the contact you want to delete with something like this:
Contact deletecontact = db.getContact(view.getTag());
db.deleteContact(deletecontact);
Of course you could change your
deleteContact(Contact contact) to a method in which you give the id instead of the contactobject.
This should hopefully work.
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);
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.
I want to open an activity depends on the value user select on a ListView. If user select a list item that have type1 value it should open acitvity1 (activity1.class), if the list item belongs to type2 it should open acitvity2 (activity2.class). I still wants to get the id value.
Can some one please help me to get more than one values in a list. (not just the id value) or a work around for this.
following is my code;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//TODO:need to assign the value here
String mEdit = .......;
if (mEdit.equals("type1")){
Intent i = new Intent(this, activity1.class);
i.putExtra(DbAdapter.KEY_ROWID, id );
startActivityForResult(i, ACTIVITY_EDIT);
}else if (mEdit.equals("type2")){
Intent i = new Intent(this, activity2.class);
i.putExtra(KEY_ROWIDA, id );
startActivityForResult(i, ACTIVITY_EDIT);
};
}
Thanks in advance
You can call getListView().getItemAtPosition(int) on your ListActivity and give it the index of the list item. You can then cast it to whatever the backing object is and perform any operations on that Object. Example from one of my own apps:
ForumDescriptor selected = (ForumDescriptor) getListView().getItemAtPosition(position);
ForumDescriptor has some information about an individual subforum (it's a forums viewer for a website). Each one is an item in my list.
This could work on the situation,
...
//TODO:need to assign the value here
TextView tv = (TextView)v.findViewById(R.id.itemname);
String category = tv.getText().toString();
...
The 'R.id.itemname' is the id attribute of list item defined in layout xml.
Here is the working code;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//TODO:need to assign the value here
Cursor mycursor = (Cursor) getListView().getItemAtPosition(position);
//1 is the field position
String mEdit = mycursor.getString(1);
if (mEdit.equals("type1")){
Intent i = new Intent(this, activity1.class);
i.putExtra(DbAdapter.KEY_ROWID, id );
startActivityForResult(i, ACTIVITY_EDIT);
}else if (mEdit.equals("type2")){
Intent i = new Intent(this, activity2.class);
i.putExtra(KEY_ROWIDA, id );
startActivityForResult(i, ACTIVITY_EDIT);
};
}
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);