I'm having trouble figuring out how to pass information through an Activity switch.
I currently have an Activity where I can add a client to the database, and I have an Activity to view all clients in a ListView.
What I want is that when the user clicks on a client in the ListView for it to go back to the addclient Activity, with all the fields filled in from the database.
here is the Activity where the user views the clients
public class ViewClientActivity extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.viewclient_activity);
DBHandler handler = new DBHandler(this, null, null, 1);
SQLiteDatabase db = handler.getWritableDatabase();
final Cursor ClientCursor = db.rawQuery("SELECT * FROM clients", null);
ListView allClients = (ListView) findViewById(R.id.allClients);
final ClientCursorAdapter clientAdapter = new ClientCursorAdapter(this, ClientCursor);
allClients.setAdapter(clientAdapter);
allClients.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent AddClientActivity = new Intent(getApplicationContext(), AddClientActivity.class);
startActivity(AddClientActivity);
}
});
}
}
You need to make the client class information implements Parcelable class. This way you will be able to add that information into the Intent you use to open the second Activity. From the second activity, you can get this information from the bundle obtained by calling getIntent()
To add the Parcelable data into de intent use intent.putExtra() and to get it from it use intent.getParcelableExtra()
when he clicks on a client in the listview for it to go back to the addclient activity but with all the fields filled in from the database
When you "go back", you are doing a SELECT *, so everything will be selected and updated correctly, assuming it was updated in the database.
Your task exists within the AddClientActivity to create a new DBHandler and update your data accordingly.
If you need to pass anything, it would be the ID of the row that was clicked, which you can use setTag within the ClientCursorAdapter class's getView method on the inflated view to put. Then, (Long) view.getTag() to receive in the click.
Also, please use getReadableDatabase() for CursorAdapter
This is what i ended up doing to pass the information i needed
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
IMAGES = imagesPath[0] + "|" + imagesPath[1] + "|" + imagesPath[2] + "|" +
imagesPath[3] + "|" + imagesPath[4] + "|" + imagesPath[5];
Intent intent = new Intent(AddClientActivity.this, ImageViewActivity.class);
intent.putExtra("IMAGES", IMAGES);
intent.putExtra("POSITION", position);
startActivity(intent);
}
});
Related
I am new to android and my code has got a bit messy. I have successfully created a list view extended from item_layout.xml. When I click on the list view It works exactly how I want it. However in each item of the list view I have a button that when clicked I want the item of the list to delete.
When researching I have come across that you need to create a customer adapter to do this however I have come so far in the project that I wouldn't even know where to start.
This code it used successfully to when the list items are clicked it works. This is just put in the Main Activity class
mylist.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
}
}
);
I populate the list using this function just outside the main activity class. It is needed to be written like this as It gets the items from a database and has to be called depending on different circumstances
private void populatelistView() {
Cursor res = userDb.getAllRows();
String[] fromFeildnames = new String[]{ DatabaseUser.KEY_1, DatabaseUser.KEY_2};
int[] toViewIds = new int[]{R.id.textViewNum, R.id.textViewItem};
SimpleCursorAdapter myCursorAdaptor;
myCursorAdaptor = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, res, fromFeildnames, toViewIds, 0);
//ListView mylist = (ListView) findViewById(R.id.listViewID);
mylist.setAdapter(myCursorAdaptor);
}
I would like to be able to get the button on each items to work by not changing much of what I have already written. I have tried just using the following code. But because it is in a different xml layout it display an error of null reference towards the item button
delete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
Toast.makeText(getApplicationContext(), "Button " + position, Toast.LENGTH_SHORT).show();
}
}
);
Please could someone help me make the button work without changing much code or give me a step by step tutorial on how to add an adapter but make my populateListView function do the same thing.
Ps. I have looked at so many tutorials about list adapters but can't find ones that are for my specific need
I open the IndividualCouponsActivity from the fragment foodCouponsFragment within the parent CouponsActivity. I open the IndividualCouponsActivity with an Intent. After opening it, I want to edit the textViews and ImageViews of the IndividualCouponActivity. It should be noted that the IndividualCouponActivity is not a parent of the fragment.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Coupon coupon = foodCoupons.get(position);
Intent foodCouponsIntent = new Intent(getActivity(), IndividualCouponActivity.class);
startActivity(foodCouponsIntent);
IndividualCouponActivity activity = new IndividualCouponActivity();
activity.setValue(coupon.getCouponValue());
activity.setCompany(coupon.getCompanyName());
activity.setInfo(coupon.getDescription());
activity.setPts(coupon.getPts());
activity.setQr(coupon.getPicImageResourceId());
}
});
However, when I run the app, clicking on the listView makes the app shut down. This is what the log says at that time:
FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.support.v7.app.AppCompatDelegateImplBase.
I suspect that this is rooting from my use of the new IndividualCouponActivity activity to access the class methods. Thanks!
Don't create your activity with new...
Pass the Coupon object to your activity like this:
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("coupon", coupon); // or putSerializable()
intent.putExtras(bundle);
intent.setClass(context, IndividualCouponActivity.class);
context.startActivity(intent);
In your activity in onCreate() you can get the passed coupon with:
getIntent().getExtras().getParcelable("coupon"); // or putSerializable()
Then set the values to your views.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Coupon coupon = (Coupon) adapterView.getItemAtPosition(position);
Intent foodCouponsIntent = new Intent(getActivity(), IndividualCouponActivity.class);
Bundle extras = new Bundle();
extras.put("value", coupon.getCouponValue());
extras.put("companyName", coupon.getCompanyName());
extras.put("description",coupon.getDescription());
extras.put("pts", coupon.getPts());
extras.put("picImageResourceId", coupon.picImageResourceId());
foodCouponsIntent.putExtras(extras);
startActivity(foodCouponsIntent);
}
});
and then in your IndividualCouponActivity's onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get reference to views...
textViewValue = (TextView) findViewById(R.id.textViewValue);
//do this for all views....
//if all objects are String values, if not you know what you have to do...
//here you get values from extras
Bundle data = getIntent().getExtras();
String value = data.getStringExtra("value");
String companyName = data.getStringExtra("companyName");
String description = data.getStringExtra("description");
String pts = data.getStringExtra("pts");
String picImageResourceId = data.getStringExtra("picImageResourceId");
//here update UI views
//example
textViewValue.setText(value);
//do this for all views....
}
maybe there is some typo mistake, but this is the solution...
You can pass data between both activities using "putExtra"
Intent intent = new Intent(getBaseContext(), IndividualCouponActivity.class);
intent.putExtra("COUPON_COMPANY_NAME", coupon.getCompanyName());
startActivity(intent);
I have a ListFragment that shows the names of all the shopping lists stored in my database table.
The problem is that when I add a new shopping list row to the table, the ListFragment on the UI is not automatically updated. (The change can only be seen if I close and restart the app.)
Firstly, this is the code that is executed in my DbContentProvider class when I add a shopping list:
`
// Insert the values into the table
id = db.insert(SHOPPING_LISTS_META_TABLE, null, values);
if (id > -1) {
// Construct and return the URI of the newly inserted row.
Uri insertedId = ContentUris.withAppendedId(CONTENT_URI_SHOPPING_LISTS_META, id);
// Notify any observers of the change in the data set.
Log.d(LOG_TAG, "................. notifyChange(\"" + insertedId + "\", null)");
getContext().getContentResolver().notifyChange(insertedId, null);
Log.d(LOG_TAG, "................. notifyChange() done");
return insertedId;
}
else {
return null;
}
`
...and here is the LogCat output for it...
10-28 12:29:41.133: D/SQLiteOpenHelper(19401): ................. notifyChange("content://org.example.myapp.DbContentProvider/shopping_lists_meta/12", null)
10-28 12:29:41.143: D/SQLiteOpenHelper(19401): ................. notifyChange() done
10-28 12:29:41.153: D/HomeActivity(19401): Shopping list, "My Test Shopping List" created: content://org.example.myapp.DbContentProvider/shopping_lists_meta/12
10-28 12:29:41.183: D/AbsListView(19401): unregisterIRListener() is called
10-28 12:29:41.193: E/ViewRootImpl(19401): sendUserActionEvent() mView == null
10-28 12:29:41.503: D/AbsListView(19401): unregisterIRListener() is called
In LogCat, there is no output at all from my ListFragment class when I add the new shopping list row. Here is my ListFragment class...
`
public class ShoppingListNamesListFragment extends ListFragment implements LoaderManager.LoaderCallbacks {
private final static String LOG_TAG = ShoppingListNamesListFragment.class.getSimpleName();
// This is the Adapter being used to display the list's data
public static SimpleCursorAdapter mAdapter;
// These are the Contacts rows that we will retrieve
static final String[] PROJECTION = {DbContentProvider.KEY_ID,
DbContentProvider.KEY_SHOPPING_LIST_NAME,
DbContentProvider.KEY_IS_SHOPPING_LIST_SELECTED};
// This is the select criteria
static final String SELECTION = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "................. onCreate()");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(LOG_TAG, "................. onActivityCreated()");
// For the cursor adapter, specify which columns go into which views
String[] fromColumns = {DbContentProvider.KEY_SHOPPING_LIST_NAME};
int[] toViews = {android.R.id.text1}; // The TextView in simple_list_item_1
// Create an empty adapter we will use to display the loaded data.
// We pass null for the cursor, then update it in onLoadFinished()
mAdapter = new SimpleCursorAdapter(this.getActivity(),
android.R.layout.simple_list_item_1, null,
fromColumns, toViews, 0);
setListAdapter(mAdapter);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(LOG_TAG, "................. onCreateView()");
return super.onCreateView(inflater, container, savedInstanceState);
}
// Called when a new Loader needs to be created
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(LOG_TAG, "................. onCreateLoader()");
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(getActivity(), DbContentProvider.CONTENT_URI_SHOPPING_LISTS_META,
PROJECTION, SELECTION, null, null);
}
// Called when a previously created loader has finished loading
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.d(LOG_TAG, "................. onLoaderFinished()");
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
}
// Called when a previously created loader is reset, making the data unavailable
#Override
public void onLoaderReset(Loader<Cursor> loader) {
Log.d(LOG_TAG, "................. onLoaderReset()");
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
makeToast("shopping list clicked: " + position);
Log.d(LOG_TAG, "shopping list clicked: " + position);
}
private void makeToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
}
NB - In my DbContentProvider class, I have...
public static final Uri CONTENT_URI_SHOPPING_LISTS_META = Uri.parse("content://org.example.myapp.DbContentProvider/shopping_lists_meta");
public static final String SHOPPING_LISTS_META_TABLE = "shopping_lists_meta";
I have based my code on this Android ListFragment / LoaderManager example. And none of the similar questions to this that I have found offer a solution that fixes my problem.
I am fairly new to Android, so it could be a simple mistake I've made. But, essentially, it seems to me that when notifyChange() is called in my DbContentProvider class, my ListFragment is not being notified (or there is some other error in this area). Can anyone help?
After spending hours and hours on this, I created a TestListActivity that hooked up to the native Contacts content provider - and that all worked/updated as it should, so I knew the issue was probably in my own content provider that I'd written.
I found the answer here. Turns out I had not called setNotificationUri(ContentResolver cr, Uri uri) on the cursor returned by the query() method of my content provider. (I'm sure this was never mentioned in the Reto Mauer book I was working from...) :/
Anyway, all sorted now! :)
I wish to know How to get values from selected items in a multi-column ListView in android?
and show value in a new activity.
in order to get selected item you should use appropriate event listener for example if you and to get item you clicked use this
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
+ id);
}
});
if you need to pass something from one activity to other you can do it via intent
intent.putExtra("KEY", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("KEY");
note in order to pass an object to other activity it must be serializable
regarding ot list item click listener there also might be problems with getting item focus
Passing parameters works with 2 normal activities, but when I try to pass this from the gridview to another activity, the value returns null
First Activity
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//This takes the position id of the image and change
//it to match category id
position = position + 1;
String positionId = String.valueOf(position);
System.out.println(positionId);
Toast.makeText(MenuActivity.this, "position =" + positionId + "\nid =" + id, Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(v.getContext(), MenuItemActivity.class);
myIntent.putExtra("hello", "hello");
startActivityForResult(myIntent, 0);
}
});
My secondary activity (MenuItemActivity.java)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuitem);
try{
Bundle extras = getIntent().getExtras();
String category = null;
extras.getString("Category "+extras.getString("hello"));
System.out.println("Category = "+category);
} catch(Exception e){
System.out.println("Error "+e.getMessage());
}
from here it looks like a master >> detail page. if so why are you calling
startActivityForResult(myIntent, 0);
instead of a simple
startActivity(myIntent);
can you try this and tell me if this works.
getIntent().getStringExtra("hello");
In your second activity, you need to call setResult to actually pass data back to the first activity.