Unable to pass Recycleview position to another activity - java

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

Related

I cannot add items to my RecyclerView from another intent

I have two intents.
Main Activity: Containing the Recycler View, showing some default items to make sure it works. An ArrayList is set to the Recycler View, which is the List containing those default items.
Second Activity: A button which will collect the data on the same page and put the data into an object, the object will be added into the Arraylist which set to the Recycler View of the Main Activity.
I made some Toast Message to confirm the object in the 2nd Activity was added to the ArrayList.
//My item
public item(int id, int money, String date, String category, String
description) {
this.id = id;
Money = money;
Date = date;
Category = category;
Description = description;
}
Then I created a class to control my ArrayList
//Building ArrayList
public Util(){
Log.d(TAG, "Util: Start");
if(IncomeItems==null){
IncomeItems = new ArrayList<>();
initIncomeItems();
}
}
private static void initIncomeItems() {
Log.d(TAG, "initIncomeItems: initI");
int Iid = 0
int Money= 0;
String Date = "";
String Category= "";
String Description = "";
Iid++;
IncomeItems.add(new item(Iid, 10000, "8-Jun-2019", "Salary",
"Salary"));
}
//adding item to ArrayList
public boolean addIncomeItem(item Item){
Log.d(TAG, "addIncomeItem: addI");
return IncomeItems.add(Item);
}
//getting ArrayList
public static ArrayList<item> getIncomeItems() {
Log.d(TAG, "getIncomeItems: getI");
return IncomeItems;
}
I set my ArrayList to the RecyclerView in the Main Activity
//Recycler View in Main Activity
RVAdapter IncomeAdapter = new RVAdapter(this);
Util util = new Util();
MainIncomeRV.setAdapter(IncomeAdapter);
MainIncomeRV.setLayoutManager(new GridLayoutManager(this, 1));
IncomeAdapter.notifyDataSetChanged();
IncomeAdapter.setItems(util.getIncomeItems());
In the 2nd Activity, I have a button to create a new item by getting data from the user.(I skipped some Widgets intitiation code here). At last I add the item to the ArrayList which set to the Recycler View in the Main Activity.
//Button in 2nd Activity
SubmitIncomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date = date_day.getSelectedItem().toString() +"-" +
date_month.getSelectedItem().toString() + "-" +
date_year.getSelectedItem().toString();
id++;
item IncomeItem = new item(id,
Integer.parseInt(Money.getText().toString()), Date,
IncomeCategories.getSelectedItem().toString(),
Description.getText().toString());
util=new Util();
util.addIncomeItem(IncomeItem);
Toast.makeText(IncomePage.this, IncomeItem.toString(),
Toast.LENGTH_SHORT).show();
Toast.makeText(IncomePage.this,
String.valueOf(util.getIncomeItems().size()), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onClick: addI");
}
});
}
No error occurred, but the item(IncomeItem) created in the 2nd Activity cannot be added to the Main Activity.
I expected the item will show in the Recycler view when I return to the Main Activity. Is it the problem that I use the return button to go back to the Main Activity?
Following two points should work for you:
You should use same util object which is used in MainActivity
instead of creating new in submit button under 2nd Activity, So pass util object to
2nd activity.
Also pass adapter object to 2nd Activity, so that you can call NotifyDatasetChanged()
function after adding item.
This is how it should work. First create an arrayList in your 2ndActivity.
ArrayList<Item> str = new ArrayList<Item>();
In SubmitIncomeBtn,
SubmitIncomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date = date_day.getSelectedItem().toString() +"-" + date_month.getSelectedItem().toString() + "-" + date_year.getSelectedItem().toString();
id++;
item IncomeItem = new item(id,Integer.parseInt(Money.getText().toString()), Date, IncomeCategories.getSelectedItem().toString(),Description.getText().toString());
str.add(IncomeItem) // add IncomeItem to arrayList
}
});
In 2ndActivity, you need to have this code to pass arrayList to MainActivity.
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("mylist", str);
setResult(1, intent);
}
Finally in MainActivity, add this code to receive data from 2ndActivity
onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
ArrayList<Item> myList = (ArrayList<Item>) getIntent().getSerializableExtra("mylist");
}
}
}

How to show income in intent string array at recyclerview android?

In my application I have draft messages which I can edit. Some of my drafts include attachments which I try to send to my edit activity and show it at recyclerview. In general I have managed to send my string arraylist and get it at my activity. But I can't show my attached files, especially their names at the recyclerview. I tried to make smth like that:
adapter.notifyDataSetChanged();
but it didn't help me.
So, firstly I get from my message names of attached files:
file_name = Objects.requireNonNull(response.body()).getAttachesNames();
then put this names into arraylist:
nameList = new ArrayList<>(Arrays.asList(file_name));
such result I can see in my logs:
W: [eZV9f.jpg, index.html]
and then I send my list via intent to another activity:
intent2.putStringArrayListExtra("attached_files", (ArrayList<String>) nameList);
receiving data from intent:
Intent intent = getIntent();
extras = intent.getExtras();
if (extras != null) {
if (extras.containsKey("attached_files")) {
draft_files = getIntent().getStringArrayListExtra("attached_files");
Log.w("MY_TAG", String.valueOf(draft_files));
}
}
results from logcat:
W: [eZV9f.jpg, index.html]
initialising of my adapter and recyclerview:
adapter = new AttachedFileAdapter(mNames);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(WriteResponseMess.this, LinearLayoutManager.VERTICAL, false));
and then I try to get single element from this list and add to my ArrayList<>:
for (int i = 0; i < draft_files.size(); i++) {
mNames.addAll(Collections.singleton(draft_files.get(i)));
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}
all previous pieces of code are used at my onCreate() method and as a result of all these actions I would like to see income data from another activity. Sometimes I managed to do it, but one element contained all income data and looked like this:
[eZV9f.jpg, index.html]
and it was wrong for me. I try to create the list which will contain all elements separately. I also tried to use some info from this link which is connected with Collections, but I didn't manage to reach the goal of my task. In general I'm sure that the solution is very simple but I can't see it.
update
all my activity class has more than 1000 lines and I will share all code which is connected with adding attachments and show attached data at my writing form:
Here is my dialog for getting directory list and choosing some files:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(WriteResponseMess.this, android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
dialog.setContentView(R.layout.dialog_layout);
dialog.setCanceledOnTouchOutside(true);
Toolbar toolbar = dialog.findViewById(R.id.toolbar_d);
toolbar.setTitle("Add a new file.");
textFolder = dialog.findViewById(R.id.folder);
buttonUp = dialog.findViewById(R.id.up);
buttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = dialog.findViewById(R.id.dialoglist);
final Dialog finalDialog1 = dialog;
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
File selected = new File(curFolder, fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
if (selected.isFile()) {
if (array.size() == 0) {
array = uploadFiles(array, selected.getName(), convertFileToString(selected.getPath()));
adapter.notifyDataSetChanged();
getImages();
} else {
if (array.toString().contains(selected.getName())) {
Toast.makeText(WriteResponseMess.this, R.string.attaching_message, Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
getImages();
} else {
array = uploadFiles(array, selected.getName(), convertFileToString(selected.getPath()));
adapter.notifyDataSetChanged();
getImages();
}
}
finalDialog1.dismiss();
ms.setArray(array);
}
}
});
break;
}
return dialog;
}
and method for showing attached list, and in general this method works when I create a new message and attach a new file, it works fine:
private void getImages() {
mNames.clear();
adapter.notifyDataSetChanged();
for (int i = 0; i < array.size(); i++) {
JsonObject object = array.get(i).getAsJsonObject();
if (extras != null) {
if (extras.containsKey("attached_files")) {
for (int j = 0; j < draft_files.size(); j++) {
mNames.clear();
mNames.add(draft_files.get(j));
adapter.notifyDataSetChanged();
//Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}
mNames.add(object.get("filename").toString().substring(1, object.get("filename").toString().length() - 1));
adapter.notifyDataSetChanged();
//Log.w("MY_TAG", Arrays.toString(draft_files));
Log.w("MY_TAG", Arrays.toString(new ArrayList[]{mNames}));
} else {
mNames.add(object.get("filename").toString().substring(1, object.get("filename").toString().length() - 1));
adapter.notifyDataSetChanged();
Log.w("MY_TAG", String.valueOf(mNames));
}
}
}
}
no need to set Adapter twice . remove this line
recyclerView.setAdapter(adapter);
From
for (int i = 0; i < draft_files.size(); i++) {
mNames.addAll(Collections.singleton(draft_files.get(i)));
adapter.notifyDataSetChanged();
//recyclerView.setAdapter(adapter); no need
Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}

Add values to ArrayList from different activity

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

Cannot make a static reference to the non-static method in onitemclicklistener on custom listview adapter fetching data from sqlite database

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.

Passing parameters between activities not working

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.

Categories

Resources