I got a problem. I want to add an object named Transactions which is this one:
public class Transaction {
private float value;
private int transaction_date;
private String description;
public Transaction(float value, int transaction_date, String description){
super();
this.value = value;
this.transaction_date = transaction_date;
this.description = description;
}
public float getValue(){
return value;
}
public int getTransaction_date(){
return transaction_date;
}
public String getDescription(){
return description;
}
to an ArrayList in my main activity.
Okay as far not that much of a problem. But how can I do this from another activity where I want to set the required variables (in my case the value, transaction_date and description)?
Here is my Activity where I want to set the values (yes I know that there are no variable inputs yet):
public class AddMoneyTransaction extends AppCompatActivity {
EditText depositInputSix;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_money_transaction);
//transaction list
populateTransactionList();
populateListView();
//setup the button
Button addDepositButton;
addDepositButton = (Button)findViewById(R.id.addDepositButton);
//make it work
addDepositButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view) {
}
});
}
//populated transaction list
protected void populateTransactionList() {
myTransactions.add(new Transaction(1,19,"monday"));
myTransactions.add(new Transaction(2,20,"tuesday"));
myTransactions.add(new Transaction(3,21,"wednesday"));
}
//populated list view
private void populateListView() {
ArrayAdapter<Transaction> adapter = new AssetsOverview.LastTransactionsListAdapter();
ListView list = (ListView) findViewById(R.id.last_transactions_listView);
list.setAdapter(adapter);
}
private class LastTransactionsListAdapter extends ArrayAdapter<Transaction>{
public LastTransactionsListAdapter(){
super(AddMoneyTransaction.this, R.layout.transaction_list_view, myTransactions);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
//make sure there is a view to work with (maybe null)
View itemView = convertView;
if (itemView == null){
itemView = getLayoutInflater().inflate(R.layout.transaction_list_view, parent, false);
}
//find a transaction to work with
Transaction currentTransaction = myTransactions.get(position);
// fill the view:
// value
TextView valueView = (TextView) itemView.findViewById(R.id.transactionValueView);
valueView.setText(currentTransaction.getValue() + "$");
// date
TextView dateView = (TextView) itemView.findViewById(R.id.transactionDateView);
dateView.setText(currentTransaction.getTransaction_date() + "");
// description
TextView descriptionView = (TextView) itemView.findViewById(R.id.transactionDesciptionView);
descriptionView.setText(currentTransaction.getDescription());
return itemView;
}
}
I hope someone can please help me with this since I did not find anything helpful. Please tell me if you need more information...
I assume your myTransactions list is defined inside parent class AppCompatActivity. The problem in
addDepositButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
}
});
seems to be that myTransactions is not defined as a final variable.
When you create a new anonymous OnClickListener, what the compiler does is it provides to OnClickListener constructor a reference to your myTransactions, if myTransactions is used inside the onClick method. This myTransactions cannot be changed later and must therefore be final.
So for the solution, I would try adding final keyword in the definition of myTransactions.
Related
I need some help for a summer project
This is my Events fragment
This is my MyList fragment
I'm using a RecyclerView+Cardview to display the Events. The idea is that the user can click the big plus on the right side of each card, and the card would be displayed in the MyList fragment. I would like to ask if it's possible to transfer a card directly from one fragment to another? Also, both fragments are contained within the same activity, which makes it a little trickier(I haven't found any available solutions).
If that is not possible, another way is to transfer the reference type object contained in the CardView to the MyList fragment. However, this is even less straightforward. This is because the button is inflated in the adapter, but there is no reference type object created here. I have seen many tutorials on using the Parcelable interface, however, I don't know how to implement it here when I'm unable to even create the object in the adapter. The reference object is created in another activity and stored in Firebase before it is read and displayed.
I'm going to attach my EventsAdapter.java and EventsItem.java and EventsFragment.java code below, but please let me know if I should include more code to describe the problem.
Thanks for reading my very long post!!
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsViewHolder> implements Filterable {
private ArrayList<EventsItem> mEventsList;
private ArrayList<EventsItem> mEventsListFull;
private EventsAdapter.OnItemClickListener mListener;
private Context mContext;
private DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.UK);
public interface OnItemClickListener {
void onItemClick(int position);
}
//the ViewHolder holds the content of the card
public static class EventsViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public ImageView mAddButton;
public TextView mTextView1;
public TextView mTextView2;
public TextView mTextView3;
public TextView mTextView4;
public TextView mTextView5;
public EventsViewHolder(Context context, View itemView, final EventsAdapter.OnItemClickListener listener) {
super(itemView);
final Context context1 = context;
mImageView = itemView.findViewById(R.id.imageView);
mAddButton = itemView.findViewById(R.id.image_add);
mTextView1 = itemView.findViewById(R.id.title);
mTextView2 = itemView.findViewById(R.id.event_description);
mTextView3 = itemView.findViewById(R.id.date);
mTextView4 = itemView.findViewById(R.id.location);
mTextView5 = itemView.findViewById(R.id.time);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str1 = mTextView1.getText().toString();
String str2 = mTextView2.getText().toString();
String str3 = mTextView3.getText().toString();
String str4 = mTextView4.getText().toString();
String str5 = mTextView5.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("title", str1);
bundle.putString("event description", str2);
bundle.putString("date", str3);
bundle.putString("location", str4);
bundle.putString("time", str5);
MylistFragment mlf = new MylistFragment();
mlf.setArguments(bundle);
}
});
}
}
//Constructor for EventsAdapter class. This ArrayList contains the
//complete list of items that we want to add to the View.
public EventsAdapter(Context context, ArrayList<EventsItem> EventsList) {
mEventsList = EventsList;
mContext = context;
mEventsListFull = new ArrayList<>(EventsList); // copy of EventsList for SearchView
}
//inflate the items in a EventsViewHolder
#NonNull
#Override
public EventsAdapter.EventsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_item, parent, false);
EventsAdapter.EventsViewHolder evh = new EventsAdapter.EventsViewHolder(mContext, v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventsAdapter.EventsViewHolder holder, int position) {
EventsItem currentItem = mEventsList.get(position);
holder.mImageView.setImageResource(currentItem.getProfilePicture());
holder.mTextView1.setText(currentItem.getTitle());
holder.mTextView2.setText(currentItem.getDescription());
holder.mTextView3.setText(df.format(currentItem.getDateInfo()));
holder.mTextView4.setText(currentItem.getLocationInfo());
holder.mTextView5.setText(currentItem.getTimeInfo());
}
#Override
public int getItemCount() {
return mEventsList.size();
}
public class EventsItem implements Occasion, Parcelable {
//fields removed for brevity
//constructor removed for brevity
}
public EventsItem() {
}
public EventsItem(Parcel in) {
profilePicture = in.readInt();
timeInfo = in.readString();
hourOfDay = in.readInt();
minute = in.readInt();
locationInfo = in.readString();
title = in.readString();
description = in.readString();
}
public static final Creator<EventsItem> CREATOR = new Creator<EventsItem>() {
#Override
public EventsItem createFromParcel(Parcel in) {
return new EventsItem(in);
}
#Override
public EventsItem[] newArray(int size) {
return new EventsItem[size];
}
};
//getter methods have been removed for brevity
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(profilePicture);
dest.writeString(timeInfo);
dest.writeString(locationInfo);
dest.writeString(title);
dest.writeString(description);
dest.writeString(df.format(dateInfo));
dest.writeInt(hourOfDay);
dest.writeInt(minute);
}
}
public class EventsFragment extends Fragment {
ArrayList<EventsItem> EventsItemList;
FirebaseDatabase mDatabase;
DatabaseReference mDatabaseReference;
ValueEventListener mValueEventListener;
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private EventsAdapter mAdapter;
private View rootView;
public FloatingActionButton floatingActionButton;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events, container, false);
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference().child("Events");
createEventsList();
buildRecyclerView();
floatingActionButton = rootView.findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), EventsAdder.class);
startActivity(intent);
}
});
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
EventsItemList.add(snapshot.getValue(EventsItem.class));
}
EventsAdapter eventsAdapter = new EventsAdapter(getActivity(), EventsItemList);
mRecyclerView.setAdapter(eventsAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
mDatabaseReference.addValueEventListener(mValueEventListener);
setHasOptionsMenu(true);
Toolbar toolbar = rootView.findViewById(R.id.events_toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
return rootView;
}
public void createEventsList() {
EventsItemList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = rootView.findViewById(R.id.recyclerview);
mLayoutManager = new LinearLayoutManager(getContext());
mAdapter = new EventsAdapter(getActivity(), EventsItemList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
}
If you would like to see the same CardView within the MyListFragment, you could have the MyListFragment contain a RecyclerView, and reuse the same EventsAdapter and EventsViewHolder. The only difference is that rather than populating the adapter with all the children of the "Events" from your database, you would only populate it with the single Event that you want.
Also, since you have made your Event class implement parcelable, you do not need to manually create the bundle when clicking the plus button.
I am assuming you have a single Activity, and you simply want to replace the EventsFragment with the MyListFragment. Checkout the docs for replacing one fragment with another.
Step 1:
Extend your onItemClickListener to look like:
public interface OnItemClickListener {
void onItemClick(int position);
void onPlusButtonClick(int position);
}
and adjust the code in your EventsViewHolder constructor to look like this when the plus button is clicked:
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
// no need to manually create the bundle here
// you already have all the information you need
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onPlusButtonClick(position);
}
}
}
});
Step 2:
Implement our new method onPlusButtonClick. As per our discussion in the comments, it seems you do not implement this interface anywhere. You can implement it inside the constructor to your EventsAdapter:
public EventsAdapter(Context context, ArrayList<EventsItem> EventsList) {
mEventsList = EventsList;
mContext = context;
mEventsListFull = new ArrayList<>(EventsList); // copy of EventsList for SearchView
mListener = new OnItemClickListener() {
#Override
public void onItemClick() {
// handle clicking the entire view holder
// NOTE: inside your EventsViewHolder, it looks like you call this method on the entire itemView. This could 'swallow' the click on the plus button. You may need to adjust your code to handle this.
}
#Override
public void onPlusButtonClick(int position) {
MyListFragment myListFragment = new MyListFragment();
Event event = mEventsList.get(position);
Bundle bundle = new Bundle();
bundle.putExtra("event", event); // this will work due to implementing parcelable
myListFragment.setArguments(bundle);
// use mContext since im assuming we areinside adapter
// if in an Activity, no need to use context to get the fragment manager
FragmentTransaction transaction = mContext.getSupportFragmentManager().beginTransaction();
// Replace the EventsFragment with the MyListFragment
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, myListFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
Step 3:
Inside your MyListFragments onCreateView() method:
#Override
public View onCreateView (
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
) {
Bundle bundle = getArguments();
Event event = bundle.getExtra("event"); // again, will work due to implementing parcelable
// from here you should bind to a recycler view, and you can even reuse your adapter like so:
List<EventsItem> singleEventList = new List<EventsItem>();
singleEventList.add(event);
EventsAdapter adapter = new EventsAdapter(getActivity(), singleEventList);
// be sure to inflate and return your view here...
}
and you should be good to go!
I have left out bits of code here and there for simplicity.. but I hope this is understandable.
As a side note.. in your firebase database listener, it is bad practice to create a new EventsAdapter every single time your data is updated. Instead, you should update the data in the adapter with the new values. Do this by creating a public method inside the adapter such as replaceEvents(List<EventsItem> newEvents), and inside, replace mEventsList with the new events, then call notifyDataSetChanged().
So I have a fragment with three speedview gauges in it. Picture of fragment They used to be in the fragment directly and would work fine, but after I needed to add the textviews, I couldn't get everything to fit on the screen so I decided to create a custom layout and use a list view to display them.
It used to be very easy to update the speedometers and everythign worked fine.
After adding everything to a listview the only way I can think to get everything to update is to use notifyDataSetChanged() on the adapter, but when I do this, the gauge indicator snaps to 0 and goes up to the desired number from there. I have tried using a holder to maybe fix the problem, but no luck.
This is the fragment's code on how I create the adapter
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
OEEsegmentList = (ListView) view.findViewById(R.id.OEEplusLV);
qualitySegment = new OEEListSegment("Quality", OEEqualityValueString, "Bad parts: "+OEEqualityBadPartsValueString, "Total parts: "+OEEqualityTotalPartsValueString);
availabilitySegment = new OEEListSegment("Availability", OEEavailabilityValueString, "Downtime: "+OEEavailabilityDowntimeValueString, "Next time: "+OEEavailabilityNextTimeValueString);
performanceSegment = new OEEListSegment("Performance", OEEperformanceValueString, "Act time: "+OEEperformanceActTimeValueString, "Takt time: "+OEEperformanceTaktTimeValueString);
OEEsegmentArrayList = new ArrayList<>();
OEEsegmentArrayList.add(qualitySegment);
OEEsegmentArrayList.add(availabilitySegment);
OEEsegmentArrayList.add(performanceSegment);
OEEadapter = new OEEListAdapter(getActivity(), R.layout.oee_list_layout, OEEsegmentArrayList);
OEEsegmentList.setAdapter(OEEadapter);
}
and here is one of the update functions, they're all basically the same code with different names. I call them in the main activity when I recieve a message about the particular marker being changed.
public void updateOEEplusAvailability (String availability) {
OEEavailabilityValueString=availability;
availabilitySegment.setSegmentValueDial(OEEavailabilityValueString);
OEEadapter.notifyDataSetChanged();
}
this is my entire list adapter
public class OEEListAdapter extends ArrayAdapter<OEEListSegment> {
private Context mContext;
int mResource;
public ArrayList<OEEListSegment> mSegments ;
public OEEListAdapter(#NonNull Context context, int resource, #NonNull ArrayList<OEEListSegment> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
mSegments=objects;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
holder = new ViewHolder();
String name = getItem(position).getSegmentName();
String valueDial = getItem(position).getSegmentValueDial();
String valueTV1 = getItem(position).getSegmentValueTV1();
String valueTV2 = getItem(position).getSegmentValueTV2();
final OEEListSegment Segment = new OEEListSegment(name, valueDial, valueTV1, valueTV2);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView textViewName = (TextView) convertView.findViewById(R.id.textViewSegmentName);
holder.speedView = (SpeedView) convertView.findViewById(R.id.segmentSpeedView);
holder.textViewFirst = (TextView) convertView.findViewById(R.id.textViewSegmentFirst);
holder.textViewSecond=(TextView) convertView.findViewById(R.id.textViewSegmentSecond);
convertView.setTag(holder);
holder.textViewFirst.setText(mSegments.get(position).getSegmentValueTV1());
holder.textViewSecond.setText(mSegments.get(position).getSegmentValueTV2());
holder.speedView.speedTo(Float.parseFloat(mSegments.get(position).getSegmentValueDial()));
holder.speedView.clearSections();
holder.speedView.addSections(
new Section(.3f, Color.RED)
, new Section(.7f, Color.YELLOW)
, new Section(1f, Color.GREEN));
textViewName.setText(name);
holder.textViewFirst.setText(valueTV1);
holder.textViewSecond.setText(valueTV2);
holder.speedView.speedTo(Float.parseFloat(valueDial));
return convertView;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return mSegments.size();
}
public Object getItemCustom(int position) {
return mSegments.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
protected SpeedView speedView ;
private TextView textViewFirst ;
private TextView textViewSecond;
}
}
And this is the list segment code
public class OEEListSegment implements Parcelable {
private String name;
private String valueDial;
private String valueTV1;
private String valueTV2;
public OEEListSegment(String name, String valueDial, String valueTV1, String valueTV2) {
this.name=name;
this.valueDial=valueDial;
this.valueTV1=valueTV1;
this.valueTV2=valueTV2;
}
public String getSegmentName() {
return name;
}
public void setSegmentName(String name) {
this.name=name;
}
public String getSegmentValueDial() {
return valueDial;
}
public void setSegmentValueDial(String valueDial) {
this.valueDial=valueDial;
}
public String getSegmentValueTV1() {
return valueTV1;
}
public void setSegmentValueTV1(String valueTV1) {
this.valueTV1=valueTV1;
}
public String getSegmentValueTV2() {
return valueTV2;
}
public void setSegmentValueTV2(String valueTV2) {
this.valueTV2=valueTV2;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.name, this.valueDial, this.valueTV1, this.valueTV2});
}
private void readFromParcel(Parcel in) {
name = in.readString();
valueDial= in.readString();
valueTV1= in.readString();
valueTV2= in.readString();
}
public OEEListSegment(Parcel in){
String[] data = new String[4];
in.readStringArray(data);
// the order needs to be the same as in writeToParcel() method
this.name = data[0];
this.valueDial= data[1];
this.valueTV1= data[2];
this.valueTV2= data[3];
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public OEEListSegment createFromParcel(Parcel in) {
return new OEEListSegment(in);
}
public OEEListSegment[] newArray(int size) {
return new OEEListSegment[size];
}
};
}
Any solution would be appreciated. Either how to stop that initial animation (0 to desired number) from happening in the speed view or how to update the listview so that animation doesn't happen.
Or would it be best to omit the list view completely, while still getting this desired layout (there will only ever be 3 segments).
I wasn't able to do what I needed to do inside the list segment, but since I knew the exact number of times I wanted this segment to be shown, I decided to change my approach.
I added a scoll view in my main layout and then included the segment layout 3x inside it. I then needed to access all the components by ID like this to acces the segment (layout)
performanceLayout = view.findViewById(R.id.performanceSegment);
and like this to access the elements inside my segments
speedViewPerformance= performanceLayout.findViewById(R.id.segmentSpeedView);
then I could update the speeviews with funcktions like this
public void updateOEEplusPerformance (String performance) {
OEEperformanceValueString=performance;
speedViewPerformance.speedTo(Float.parseFloat(OEEperformanceValueString));
}
It's much simpler than what I was trying to do before, since I don't need an adapter or a new class, I definitely do not need to change the speedview animation and it works just like I needed it to!
So i have my a list on my main activity that i want to be able to access in another class. The second class is supposed to add more records to the list based on the users input but i don't know how to access it. Can anybody help?
Contactos.java:
This is my main class and its also where the list is kept, i did a test run on it so that's why the constructor is filled with numbers. I want to be able to add to the list from another class.
public class Contactos extends AppCompatActivity {
private Button btnReciente;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnReciente = (Button) findViewById(R.id.Reciente);
listView = (ListView) findViewById(R.id.list1);
List<contactosLista> list1 = new ArrayList<contactosLista>();
list1.add(new contactosLista("1","2","3","4","5","6"));
ContactosAdapter adapter = new ContactosAdapter(this,list1);
listView.setAdapter(adapter);
ContactosAdapter.java: This is where i inflate the list, i use it so i can use a .xml file to better display the values in the list.
public class ContactosAdapter extends BaseAdapter
{
private Context mContext;
private List<contactosLista>mListaContactos;
public ContactosAdapter(Context context, List<contactosLista> list)
{
mContext = context;
mListaContactos = list;
}
#Override
public int getCount() {
return mListaContactos.size();
}
#Override
public Object getItem(int position) {
return mListaContactos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
contactosLista entrada = mListaContactos.get(position);
if(convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.contactos_row,null);
}
TextView Contact = (TextView) convertView.findViewById(R.id.Contacto);
Contact.setText(entrada.getmName() + " -- " + entrada.getmEmpresa());
return convertView;
}
}
contactosLista.java: This the class that defines the elements that the list needs. i made a constructor that accommodates all the strings and made all the setters & getters
public class contactosLista
{
private String mName;
private String mEmpresa;
private String mRazon;
private String mDireccion;
private String mEstatus;
private String mPaquete;
public contactosLista(String mName, String mEmpresa, String mRazon, String mDireccion, String mEstatus, String mPaquete)
{
this.mName = mName;
this.mEmpresa = mEmpresa;
this.mRazon = mRazon;
this.mDireccion = mDireccion;
this.mEstatus = mEstatus;
this.mPaquete = mPaquete;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmEmpresa() {
return mEmpresa;
}
public void setmEmpresa(String mEmpresa) {
this.mEmpresa = mEmpresa;
}
public String getmRazon() {
return mRazon;
}
public void setmRazon(String mRazon) {
this.mRazon = mRazon;
}
public String getmDireccion() {
return mDireccion;
}
public void setmDireccion(String mDireccion) {
this.mDireccion = mDireccion;
}
public String getmEstatus() {
return mEstatus;
}
public void setmEstatus(String mEstatus) {
this.mEstatus = mEstatus;
}
public String getmPaquete() {
return mPaquete;
}
public void setmPaquete(String mPaquete) {
this.mPaquete = mPaquete;
}
}
createContact.java: finally this is the class where i want to be able to access the list from Contactos.java, I have a layout file that has a bunch of Edit text so that i can record input from the user. When the user clicks on the button to save i want my void "GuardarCon" to save the input from the user to strings and then i want to use those strings as parameters for my list. This is where the problem arises, i don't know how to call the list. PLS help.
public class createContact extends AppCompatActivity
{
EditText nombre;
EditText empresa;
EditText razon;
EditText direccion;
EditText estatus;
EditText paquete;
String snombre;
String sempresa;
String srazon;
String sdireccion;
String sestatus;
String spaquete;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_contact);
nombre = (EditText) findViewById(R.id.nombreT);
empresa = (EditText) findViewById(R.id.empresaT);
razon = (EditText) findViewById(R.id.razonSocialT);
direccion = (EditText) findViewById(R.id.direccionT);
estatus = (EditText) findViewById(R.id.EstatusT);
paquete = (EditText) findViewById(R.id.paqueteT);
}
public void GuardarCon(View view)
{
snombre = nombre.getText().toString();
sempresa = empresa.getText().toString();
srazon = razon.getText().toString();
sdireccion = direccion.getText().toString();
sestatus = estatus.getText().toString();
spaquete = paquete.getText().toString();
}
Create a singleton class and access and modify data as you want !
public class DataHolder{
public static final DataHolder instance = new DataHolder();
private List<Your_Data_Type> data;
//Your methods goes here...
}
You could use startActivityForResult method to start createContact from Contactos activity and after the addition process is done use setResult method to return the added item to the Contactos activity and handle adding the item to the list in onActivityResult.
take a look at this link for further info:
https://developer.android.com/training/basics/intents/result
I'm developing my first App ever, but I'm facing a problem that I cannot overcome.
I'm creating a ListView for restaurants in which (Name, Phone, Logo, and Location) for each one will be shown in its List Item.
Everything is going well except for the coordination.
I was able only to hardcode the coordinates in getview method, but I don't know how to change it along with the arraylist.
Is there a way to add it to the arraylist as another Arguement?
Any help will be much appreciated :)
These are my codes in which I just added a string for the location and Intent to open the fixed coordinates.
for the new object class:
public class Cell {
private String mName;
private String mPhone;
private int mLogo;
private String mLocation;
public Cell (String name, String phone, int logo, String location){
mName = name;
mPhone = phone;
mLogo = logo;
mLocation = location;}
public String getmName() {return mName;}
public String getmPhone(){return mPhone;}
public int getmLogo(){return mLogo;}
public String getmLocation() {return mLocation;}
this for the customAdapter:
public class CellAdapter extends ArrayAdapter<Cell> {
private static final String LOG_TAG = CellAdapter.class.getSimpleName();
public CellAdapter(Activity context, ArrayList<Cell> restaurant) {
super(context, 0, restaurant);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
final Cell currentNumber = getItem(position);
TextView mapView = (TextView) listItemView.findViewById(R.id.map_view);
mapView.setText(currentNumber.getmLocation());
mapView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent mapIntent = new Intent(Intent.ACTION_VIEW);
mapIntent.setData(Uri.parse("geo:47.6, -122.3"));
getContext().startActivity(mapIntent);
}
});
TextView nameView = (TextView) listItemView.findViewById(R.id.name_view);
nameView.setText(currentNumber.getmName());
TextView phoneView = (TextView) listItemView.findViewById(R.id.phone_view);
phoneView.setText(currentNumber.getmPhone());
phoneView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent call = new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel: " + currentNumber.getmPhone()));
getContext().startActivity(call);
}
});
ImageView logoView = (ImageView) listItemView.findViewById(R.id.logo_view);
logoView.setImageResource(currentNumber.getmLogo());
return listItemView;
}
and this is the activity code:
public class RestaurantsActivity extends AppCompatActivity {Intent mapIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurants);
final ArrayList<Cell> restaurant = new ArrayList<>();{
restaurant.add(new Cell("Restaurant 1", "12345", R.drawable.logo_1, "MAP"));
restaurant.add(new Cell("Restaurant 2", "67890", R.drawable.logo_2, "MAP"));
CellAdapter restaurantAdapter = new CellAdapter(this, restaurant);
ListView restaurantView = (ListView) findViewById(R.id.restaurant_view);
restaurantView.setAdapter(restaurantAdapter);
}
}
}
The final result I need is to update the data in mapIntent with different restaurants when the user click (MAP):
The following steps should help you solve this if I got your question correctly:
Add another field to Cell to represent the location URI.
Get this new field and use it to set the currently hardcoded value. e.g mapIntent.setData(currentNumber.getLocationURI());
Then, when creating the Cell objects, you need to pass in the location URI like you did for its other fields in the Cell constructor.
I made an ArrayList to populate the CustomAdapter. Everything works so far but the text of the ArrayList doesn't appear. Even the buttons update the text of the numbers on the click. If I put a breakpoint in the ArrayList it does not break there, so the whole ArrayList is not found. Why, and if it is declared in the wrong place, where should I put it.
Here is the MainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
public static ArrayList<Model> brandlist;
private CustomAdapter customAdapter;
private Button btnnext;
//public static ArrayList brandlist;
public static void onCreate(String[] args) {
ArrayList brandlist = new ArrayList<>();
brandlist.add("340ml NRB (85023)");
brandlist.add("330ml Cans (85736)");
brandlist.add("500ml Cans (85024)");
brandlist.add("440ml NRB (86798)");
brandlist.add("330ml RB (85556)");
brandlist.add("750ml RB (85021)");
brandlist.add("340ml NRB 12 pack (87009)");
brandlist.add("500ml Cans 12 Pack (85022)");
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
btnnext = (Button) findViewById(R.id.next);
brandlist = getModel();
customAdapter = new CustomAdapter(this);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager (getApplicationContext(), LinearLayoutManager.VERTICAL, false));
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (MainActivity.this,NextActivity.class);
startActivity(intent);
}
});
}
private ArrayList<Model> getModel(){
ArrayList<Model> list = new ArrayList<>();
for(int i = 0; i < 8 ; i++){
Model model = new Model();
model.setNumber(0);
model.setBrandlist(brandlist);
list.add(model);
}
return list;
}
}
And here is the CustomAdapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private LayoutInflater inflater;
private Context ctx;
public CustomAdapter(Context ctx) {
inflater = LayoutInflater.from(ctx);
this.ctx = ctx;
}
#Override
public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, int position) {
holder.tvBrand.setText((CharSequence) MainActivity.brandlist.get(position).getBrandlist());
holder.tvCases.setText(String.valueOf(MainActivity.brandlist.get(position).getNumber()));
holder.tvPallets.setText(String.valueOf(MainActivity.brandlist.get(position).getNumber()));
}
#Override
public int getItemCount() {
return MainActivity.brandlist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected Button btn_cases_plus, btn_cases_minus, btn_pallets_plus, btn_pallets_minus;
private TextView tvBrand, tvCases,tvPallets;
public MyViewHolder(View itemView) {
super(itemView);
tvBrand = (TextView) itemView.findViewById(R.id.brand_name);
tvCases = (TextView) itemView.findViewById(R.id.cases_text_view);
tvPallets = (TextView) itemView.findViewById(R.id.pallets_text_view);
btn_cases_plus = (Button) itemView.findViewById(R.id.casePlus1);
btn_cases_minus = (Button) itemView.findViewById(R.id.caseMinus1);
btn_pallets_plus = (Button) itemView.findViewById(R.id.palletsPlus1);
btn_pallets_minus = (Button) itemView.findViewById(R.id.palletsMinus1);
btn_cases_plus.setTag(R.integer.btn_cases_plus_view, itemView);
btn_cases_minus.setTag(R.integer.btn_cases_minus_view, itemView);
btn_cases_plus.setOnClickListener(this);
btn_cases_minus.setOnClickListener(this);
btn_pallets_plus.setTag(R.integer.btn_pallets_plus_view, itemView);
btn_pallets_minus.setTag(R.integer.btn_pallets_minus_view, itemView);
btn_pallets_plus.setOnClickListener(this);
btn_pallets_minus.setOnClickListener(this);
}
// onClick Listener for view
#Override
public void onClick(View v) {
if (v.getId() == btn_cases_plus.getId()){
View tempview = (View) btn_cases_plus.getTag(R.integer.btn_cases_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.cases_text_view);
int number = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(number));
MainActivity.brandlist.get(getAdapterPosition()).setNumber(number);
} else if(v.getId() == btn_cases_minus.getId()) {
View tempview = (View) btn_cases_minus.getTag(R.integer.btn_cases_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.cases_text_view);
int number = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(number));
MainActivity.brandlist.get(getAdapterPosition()).setNumber(number);
}
}
}
}
And here is the Model file:
public class Model {
private int number;
private ArrayList brandlist;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public ArrayList getBrandlist() {
return brandlist;
}
public void setBrandlist(ArrayList brandlist) {
this.brandlist = brandlist;
}
public ArrayList getbrandlist() {
return brandlist;
}
}
You have a very confusing setup here that is likely to lead to problems down the road. That being said...
First, this method doesn't do anything:
public static void onCreate(String[] args) {
ArrayList brandlist = new ArrayList<>();
brandlist.add("340ml NRB (85023)");
brandlist.add("330ml Cans (85736)");
brandlist.add("500ml Cans (85024)");
brandlist.add("440ml NRB (86798)");
brandlist.add("330ml RB (85556)");
brandlist.add("750ml RB (85021)");
brandlist.add("340ml NRB 12 pack (87009)");
brandlist.add("500ml Cans 12 Pack (85022)");
}
There's no lifecycle method with this signature, so unless you're calling it manually, it will never be invoked. It looks like you copied a non-Android program's main() method and changed the name to onCreate().
Even if you do manually invoke this method, it won't do anything. The first line (ArrayList brandlist = ...) is creating a list and assigning it to a local variable. It is not initializing your MainActivity.brandlist.
In your real onCreate() method (the second one), you initialize MainActivity.brandlist with the results of the getModel() call. At the time you call this method, MainActivity.brandlist is null, so you are essentially building up a list of eight items all with number = 0 and brandlist = null.
From there you create your adapter etc, which all looks fine.
I recommend taking a step back and thinking about what you're trying to accomplish. Probably you will eventually wind up re-writing the majority of this code. Perhaps a colleague or a teacher could help with this.