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.
Related
I am building an expense tracker app. I got stuck in a problem where I couldn't pass my adapter position to another activity. The thing that bothers me more that I am able to pass my id from adapter to activity but couldn't pass the position. I have pasted the code below for better understanding. Can someone help me on this?
public void onBindViewHolder(#NonNull UltAdapter.MyViewHolder holder, int position) {
TransactionModel MyModel = myViewsList.get(position);
Log.d("checkTag -> ", MyModel.getType());
holder.amount.setText(MyModel.getAmount());
if(Objects.equals(MyModel.getType(), "Income"))
{
holder.amount.setTextColor(Color.GREEN);
holder.priority.setBackgroundResource(R.drawable.mark);
}
else
{
holder.amount.setTextColor(Color.RED);
holder.priority.setBackgroundResource(R.drawable.redmark);
}
final int pos = holder.getAdapterPosition();
holder.date.setText(MyModel.getDate());
holder.note.setText(MyModel.getNote());
holder.Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context,Update_transaction.class);
i.putExtra("key",myViewsList.get(pos).getId());
i.putExtra("pos",pos);
context.startActivity(i);
}
});
}
I've seen your previous question where you are retrieving data like this :
Bundle bundle = getIntent().getExtras();
Update_db = new DataSaver(this);
if(bundle != null)
{
id = bundle.getString("key");
pos = bundle.getString("pos");
Toast.makeText(this, "pos : " + pos, Toast.LENGTH_SHORT).show();
}
Instead Did you tried to get data like this :
int pos = getIntent().getIntExtra("pos", -1 /* default value */)
and For key I assume that your key is a string
String key = getIntent().getStringExtra("key");
I had this probleme before, the Type of position is an Int, and in retreiving it's suppose to be a String, so there is a solution
In passing data :
Intent i = new Intent(context,Update_transaction.class);
i.putExtra("key",myViewsList.get(pos).getId());
i.putExtra("pos",String.valueOf(pos));
context.startActivity(i);
In retreiving data:
int pos;
id = bundle.getString("key");
pos = Integer.parseInt(bundle.getString("pos"));
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);
}
});
I'm trying to create an app like shopping cart
Using this to access my database http://www.tutecentral.com/restful-api-for-android-part-2/
And i'm stuck at adding products to cart, so far I understand that the selected products go to arraylist in a few tutorials. In the code below I have two Activities, the MaterialView (this shows the details of the materials and has the option to add to cart), and the MaterialCart (shows the list of selected products.)
this is the block of code in MaterialView to send the values to MaterialCart
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
Intent i=new Intent(MaterialView.this, MaterialCart.class);
i.putExtra("mID", mid);
i.putExtra("name", Name.getText().toString());
i.putExtra("qty", Qty.getText().toString());
i.putExtra("price", Price.getText().toString());
i.putExtra("stock", Stock.getText().toString());
i.putExtra("rqQty", RqQty.getText().toString());
startActivity(i);
Toast.makeText(MaterialView.this, "Added Succesfully.", Toast.LENGTH_LONG).show();
}
} );
I have used Intent to pass the values (I'm pretty sure this method is wrong, I also tried calling the MaterialCart class itself to access the arrayList so I can add values and it didn't work)
This is the block of codes in my MaterialCart to receive the values
public class MaterialCart extends Activity {
final ArrayList<PropertyCartTable> materialProperties = new ArrayList<>();
#SuppressLint("LongLogTag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cart);
Intent i = new Intent();
Bundle extras = getIntent().getExtras();
try{
String Name = extras.getString("name");
String Qty = extras.getString("qty");
String Price = extras.getString("price");
String Stock = extras.getString("stock");
String RqQty = extras.getString("rqQty");
String ID = extras.getString("mID");
Log.d("EXTRAS:", Name + " " + Qty + " " + ID);
materialProperties.add(new PropertyCartTable( ID,Name,Qty,Price,Stock,RqQty));
getIntent().removeExtra("Name");
getIntent().removeExtra("Qty");
getIntent().removeExtra("Price");
getIntent().removeExtra("Stock");
getIntent().removeExtra("RqQty");
getIntent().removeExtra("MID");
}
catch (Exception h){
Log.d("Exception!",h.toString());
}
// materialProperties.add(array);
Log.d("MaterialView.Cart isEmpty", String.valueOf(materialProperties.isEmpty()));
if(materialProperties.isEmpty()) {
Toast.makeText(this, "You have no materials to request.", Toast.LENGTH_LONG).show();
i = new Intent(MaterialCart.this, ProductDetails.class);
startActivity(i);
}else{
ArrayAdapter<PropertyCartTable> adapter = new propertyArrayAdapter(this, 0, materialProperties);
ListView listView = (ListView) findViewById(R.id.lv_materialcart);
listView.setAdapter(adapter);
}
}
The codes work for receiving the values, but when I go back to the materialView (or choose another product) the ArrayList doesn't append the values.
What I'm trying to achieve here is to add the values from the MaterialView (even if the user adds many prodducts) to MaterialCart's ArrayList.
You can let your Application contain the data:
public class MyApp extends Application {
private static List<String> data = new ArrayList<>();
public static void addItem(String item) {
data.add(item);
}
public static List<String> getData() {
return data;
}
}
And when button is clicked:
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
MyApp.addItem(your item);
Intent i=new Intent(MaterialView.this, MaterialCart.class);
startActivity(i);
}
} );
And in MaterialCart.class:
List<String> data = MyApp.getData();
But remember:data will be clear when app is closed.And if you want save it locally,you need to use SharedPreferences
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);
Application Structure first:
//This class has a listview which will be populated from custom adapter
public class Transactions_show extends Activity implements OnItemClickListener
//This class is custom adapter which returns custom view for each row to be populated in above listview using sqlite database
public class CustomAdapter extends BaseAdapter
//Here all is working fine
//Now
//setting onitemclicklistener on each item of listview
public class Transactions_show extends ListActivity implements
OnItemClickListener {
List<Transactions> all_transactions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_transactions);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
all_transactions = db.get_all_transactions();
size_of_transaction = all_transactions.size();
ListView all_transactions_list = (ListView) findViewById(R.id.all_transaction_show_list);
CustomAdapter adapter = new CustomAdapter(this, all_transactions);
all_transactions_list.setAdapter(adapter);
try {
all_transactions_list.setOnItemClickListener(this);
} catch (NullPointerException e) {
Log.e("null pointer exception at item click", e.getMessage());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Transactions single_transaction = new Transactions();
single_transaction = all_transactions.get(position);
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Intent.putExtra("phone_number", p_n);
startActivity(intent);
/*
* Toast toast = Toast.makeText(getApplicationContext(), "Item " +
* (position + 1) + ": " +single_transaction.get_phone_number() ,
* Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM |
* Gravity.CENTER_HORIZONTAL, 0, 0); toast.show();
*/
}
}
error is occuring here
Intent.putExtra("phone_number", p_n);
Which is : Cannot make a static reference to the non-static method putExtra(String, int) from the type Intent
Finding and trying on stack overflow for days and following google developers , decided to make a bundle as given in Passing a Bundle on startActivity()?
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Transactions single_transaction = new Transactions();
single_transaction = all_transactions.get(position);
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Bundle extras = intent.getExtras();
try {
extras.putInt("phone_number", p_n);
} catch (NullPointerException e) {
Log.e("Null exception at putint", e.getMessage());
}
Intent.putExtra("phone_number", p_n);
startActivity(intent);
}
Error removed but when application runs but crashes at extras.puInt ,although next activity starts well if don't pass this bundle.
So thought about taking complete custom view row and extract field of phone number
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(this, transacee_summary.class);
TextView textv = (TextView) findViewById(R.id.phone_number_show);
int p_n = Integer.parseInt( textv.getText().toString());
Intent.putExtra("phone_number", p_n);
startActivity(intent);
}
now error comes again same.
What goes around comes around!
It should probably be:
intent.putExtra("phone_number", p_n);
intent (the instance), not Intent (the class), since putExtra is indeed an instance method.
Problem is with this piece of code:
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Intent.putExtra("phone_number", p_n);
You need to replace Class Intent refrence with Object Intent refrence as putExtra is not a static method it is an instance method
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
intent.putExtra("phone_number", p_n); // see starts with small i
Hope this helps.