This is the method that I send the data from activity to dialog fragment
MultipleColorFragment multipleColorFragment = new MultipleColorFragment();//Get Fragment Instance
Bundle data = new Bundle();//Use bundle to pass data
for(int i = 0;i<product_data_two.getColor().size();i++) {
data.putStringArrayList(i + "", product_data_two.getColor().get(i));
Log.d(TAG + " send fragment data",data.toString());
}
data.putInt("size", product_data_two.getColor().size());
multipleColorFragment.setArguments(data);//Finally set argument bundle to fragment
final FragmentManager fm=getFragmentManager();
multipleColorFragment.show(fm,"Color Set");
This is the method that I get back the data.
RecyclerView rv;
ArrayList<ArrayList<String>> getArgument;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.multiple_color_fragment_layout, container);
//RECYCER
rv = (RecyclerView) rootView.findViewById(R.id.multiple_color_recyclerview);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
rv.setLayoutManager(new GridLayoutManager(getActivity(), 6));
rv.setAdapter(new MultipleColorAdapter());
int size = getArguments().getInt("size");
Log.d( " size : " + size ,"");
for (int i = 0; i < size; i++)
getArgument.add(getArguments().getStringArrayList(i + ""));
this.getDialog().setTitle("Color Set");
return rootView;
}
I find that the data that I pass is right. However, I cannot get back the data in the fragment. Can anyoun help me to figure out the problem? Thank you very much.
Update:
ProductTypeTwo.java
public class ProductTypeTwo {
private String productName;
private String brandID;
private String description;
private String productImage;
private Long colorNo;
private String category;
private String uid;
private ArrayList<ArrayList<String>> color;
public ProductTypeTwo(String productName, String brandID, String description, String productImage, Long colorNo, String category, String uid, ArrayList<ArrayList<String>> color) {
this.productName = productName;
this.brandID = brandID;
this.description = description;
this.productImage = productImage;
this.colorNo = colorNo;
this.category = category;
this.uid = uid;
this.color = color;
}
public ProductTypeTwo()
{
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getBrandID() {
return brandID;
}
public void setBrandID(String brandID) {
this.brandID = brandID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public Long getColorNo() {
return colorNo;
}
public void setColorNo(Long colorNo) {
this.colorNo = colorNo;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public ArrayList<ArrayList<String>> getColor() {
return color;
}
public void setColor(ArrayList<ArrayList<String>> color) {
this.color = color;
}
}
message from my logcat:
D/MultipleColorFragment color set size: 0
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean > > java.util.ArrayList.add(java.lang.Object)' on a null object reference
Since product_data_two.getColor() returns an ArrayList<ArrayList<String>> , you can add it to bundle like this:
bundle.putSerializable("SOME_KEY",product_data_two.getColor());
And in your Fragment, get it like this:
getArgument = (ArrayList<ArrayList<String>>) bundle.getSerializable("SOME_KEY");
read more: Bundle
First of all add you colors in a separate ArrayList and then put it all to the bundle to be passed to the Fragment
MultipleColorFragment multipleColorFragment = new
MultipleColorFragment();//Get Fragment Instance
Bundle data = new Bundle();//Use bundle to pass data
ArrayList<String> colorArray = new ArrayList<>()
for(int i = 0; i<product_data_two.getColor().size(); i++) {
colorArray.add(product_data_two.getColor().get(i));
}
data.putStringArrayList("colorArray", colorArray);
data.putInt("size", product_data_two.getColor().size());
multipleColorFragment.setArguments(data);//Finally set argument bundle to fragment
final FragmentManager fm=getFragmentManager();
multipleColorFragment.show(fm,"Color Set");
And in your Fragment get the whole ArrayList by key Like below
ArrayList<String> colorArray =getArguments().getStringArrayList("colorArray");
Related
I have trouble getting data from adapter to fragment. I want to display some information through recycler view but the problem is that I have an error in getting the data arraylist in my VaccineAdapter.
This is my patientlogin class once the user login the account. I want to display his/her personal information as well as the his her vaccine history in a recyclerView order.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_login);
name = findViewById(R.id.fullName);
IdNo = findViewById(R.id.idNumber);
}
// Validate name
private Boolean validateName(){
String val = name.getText().toString();
if(val.isEmpty()){
name.setError("Field is Empty");
return false;
}else{
name.setError(null);
name.setEnabled(false);
return true;
}
}
// Validate ID number
private Boolean validateIdNumber(){
String val = IdNo.getText().toString();
if(val.isEmpty()){
IdNo.setError("Field cannot be empty");
return false;
}else{
IdNo.setError(null);
name.setEnabled(false);
return true;
}
}
public void loginPatient(View view){
//validate Login info
if (!validateName() | !validateIdNumber()) {
return;
}else{
isUser();
}
}
//if validation is correct
private void isUser() {
final String userEnteredIdNo = IdNo.getText().toString().trim();
final String userEnteredName = name.getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Patient List");
Query checkUser = reference.orderByChild("id").equalTo(userEnteredIdNo);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
IdNo.setError(null);
IdNo.setEnabled(false);
String IdNoFromDB = dataSnapshot.child(userEnteredIdNo).child("name").getValue(String.class);
if(IdNoFromDB.equals(userEnteredName)){
IdNo.setError(null);
IdNo.setEnabled(false);
String imageFromDB = dataSnapshot.child(userEnteredIdNo).child("image").getValue(String.class);
String idFromDB = dataSnapshot.child(userEnteredIdNo).child("id").getValue(String.class);
String nameFromDB = dataSnapshot.child(userEnteredIdNo).child("name").getValue(String.class);
String ageFromDB = dataSnapshot.child(userEnteredIdNo).child("age").getValue(String.class);
String birthdayFromDB = dataSnapshot.child(userEnteredIdNo).child("birthday").getValue(String.class);
String addressFromDB = dataSnapshot.child(userEnteredIdNo).child("address").getValue(String.class);
String vaccineNameFromDB= dataSnapshot.child(userEnteredIdNo).child("vaccine_Name").getValue(String.class);
String institutionNameFromDB = dataSnapshot.child(userEnteredIdNo).child("institution_Name").getValue(String.class);
String vaccineDateFromDB = dataSnapshot.child(userEnteredIdNo).child("vaccine_Date").getValue(String.class);
PatientInfoHelperClass helperClass = new PatientInfoHelperClass(imageFromDB , idFromDB , nameFromDB , ageFromDB , birthdayFromDB ,addressFromDB ,vaccineNameFromDB , vaccineDateFromDB , institutionNameFromDB);
Intent intent = new Intent( patientLogin.this , patientProfile.class);
Bundle bundle = new Bundle();
bundle.putParcelable("helperClass", Parcels.wrap(helperClass));
intent.putExtras(bundle);
startActivity(intent);
}
else{
name.setError("No such name exists");
name.requestFocus();
}
}
else{
IdNo.setError("Wrong Id Number");
IdNo.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
This is my VaccineAdapter this is the adapter
public VaccineAdapter(Context context, List<PatientInfoHelperClass> mList) {
this.mList = mList;
this.context = context;
}
#NonNull
#Override
public VaccineAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.vaccine_list,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull VaccineAdapter.MyViewHolder holder, int position) {
//get data
String vName = mList.get(position).getVaccine_Name();
String iName = mList.get(position).getInstitution_Name();
String vDate = mList.get(position).getVaccine_Date();
//set data
holder.vaccine_Name.setText(vName);
holder.institution_Name.setText(iName);
holder.vaccine_Date.setText(vDate);
}
#Override
public int getItemCount() {
return mList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView vaccine_Name, institution_Name, vaccine_Date;
public MyViewHolder(View itemView){
super(itemView);
vaccine_Name = itemView.findViewById(R.id.vaccineName);
institution_Name = itemView.findViewById(R.id.institutionName);
vaccine_Date = itemView.findViewById(R.id.vaccineDate);
}
}
This is my HistoryFragment connected to vaccine adapter where I want to display vaccine history in a recyclerview order.
RecyclerView recyclerView;
List<PatientInfoHelperClass> mList;
VaccineAdapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public HistoryFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HistoryFragment.
*/
// TODO: Rename and change types and number of parameters
public static HistoryFragment newInstance(String param1, String param2) {
HistoryFragment fragment = new HistoryFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_PARAM1, param1);
bundle.putString(ARG_PARAM2, param2);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getActivity().getIntent().getExtras();
View v = inflater.inflate(R.layout.fragment_history, container, false);
recyclerView = v.findViewById(R.id.historyRecyclerView);
mList = args.getParcelable("helperClass");
adapter = new VaccineAdapter (getActivity(), mList);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return v;
}
This is my PatientInfoHelperClass
#Parcel
public class PatientInfoHelperClass {
String image, name, id, age, birthday, address, institution_Name, vaccine_Name, vaccine_Date;
public PatientInfoHelperClass() {
}
public PatientInfoHelperClass(String image, String name, String id, String age, String birthday, String address, String institution_Name, String vaccine_Name, String vaccine_Date) {
this.image = image;
this.name = name;
this.id = id;
this.age = age;
this.birthday = birthday;
this.address = address;
this.institution_Name = institution_Name;
this.vaccine_Name = vaccine_Name;
this.vaccine_Date = vaccine_Date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getInstitution_Name() {
return institution_Name;
}
public void setInstitution_Name(String institution_Name) {
this.institution_Name = institution_Name;
}
public String getVaccine_Name() {
return vaccine_Name;
}
public void setVaccine_Name(String vaccine_Name) {
this.vaccine_Name = vaccine_Name;
}
public String getVaccine_Date() {
return vaccine_Date;
}
public void setVaccine_Date(String vaccine_Date) {
this.vaccine_Date = vaccine_Date;
}
}
I want to display the vaccine_Name, institution_Name, and vaccine_Date that I call in my adapter. but don't know how to get the data from my vaccineAdapter to the HistoryFragment.
This is the error I get.
This is the design of the app. Once I clicked the history in the bottomNavigation the error will appear.
The error is in your fragment in the line mList = getActivity().getIntent();
The getIntent() method essentially returns intent not a list so you can't equate your mList to getActivity().getIntent()! getIntent() is used to pass data from activity to activity/fragment to activity. It returns the intent that started the activity.
Example of getIntent(),
If you start an Activity with some data,
String someData = "StackOverflow is awesome";
Intent intent = new Intent(context, SomeActivity.class);
intent.putExtra("someKey", someData);
you can retrieve this data using getIntent in the receiver activity:
Intent intent = getIntent();
if (intent != null)
String gotBackSomeKey = intent.getExtra("someKey");
Now for passing data between fragments or from an activity to a fragment, we use Bundle.(Your case)
Example of Bundle,
Bundle bundle = new Bundle();
bundle.putParceableArrayList("YourListTag",mList);
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Make sure, unlike String or Int, you cannot pass List to your Bundle/Intent directly if you have a customized list. You will have to make your object of the list Parcelable or Serializable and then pass it like above example. You can read how to implement Parcelable/Serializable here
https://developer.android.com/reference/android/os/Parcelable
https://developer.android.com/reference/java/io/Serializable
AuctionList.java
public class AuctionList extends AppCompatActivity {
ListView mListView;
ArrayList<Model> mList;
AuctionListAdapter mAdapter = null;
DatabaseHelperUpload mDBUpload;
TextView txtName,txtDescription,txtDuration,txtPrice;
ImageView imageViewIcon;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.auction_list);
mDBUpload = new DatabaseHelperUpload(this);
mListView = findViewById(R.id.listView);
mList = new ArrayList<>();
mAdapter = new AuctionListAdapter(this,R.layout.row,mList);
mListView.setAdapter(mAdapter);
txtName = findViewById(R.id.txtName);
txtDescription = findViewById(R.id.txtDescription);
txtDuration = findViewById(R.id.txtDescription);
txtPrice = findViewById(R.id.txtPrice);
}
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = txtName.getText().toString();
String description = txtDescription.getText().toString();
String price = txtPrice.getText().toString();
String duration = txtDuration.getText().toString();
Intent intent5 = new Intent(AuctionList.this,BuyerHome.class);
intent5.putExtra("name",name);
intent5.putExtra("description",description);
intent5.putExtra("price",price);
intent5.putExtra("duration",duration);
startActivity(intent5);
}
});
Activity.java
Bundle bundle = getIntent().getExtras();
String duration = bundle.getString("duration");
String price = bundle.getString("price");
TextView durationLog = (TextView)findViewById(R.id.text_view_countdown);
TextView priceLog = (TextView)findViewById(R.id.textPrice);
durationLog.setText(duration);
priceLog.setText(price);
Model.java
public class Model {
private int id;
private String name;
private String duration;
private String description;
private String price;
private byte[] image;
public Model(int id, String name,String description,String price,String duration, byte[] image) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.duration = duration;
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
The activity.java codes are partial as I am still trying out. So I am just trying to get two data(duration and price).
However, I am having error and my app kept crashing. May I kindly ask what is wrong with my codes. I actually have a Model code as shown.
The error is:
2019-03-23 00:30:58.046 11048-11048/com.example.jianminmong.aucon E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jianminmong.aucon, PID: 11048
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at com.example.jianminmong.aucon.AuctionList$1.onItemClick(AuctionList.java:63)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
at android.widget.AbsListView$3.run(AbsListView.java:4052)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Really appreciate some help here as this is the last part for my final year project. I am a amateur here by the way,so the more I am in need of help.
I basically just want to retrieve the data from the listview accordingly and just initialise the values, &&& it should not keep resetting the data back whenever i press it,because the activity requires it to run in the background(such as the timer)
Problem with your Textview when you getText from Textview that time any one Textview is not bind with xml that's why your app was crashed.
mListView.setOnItemClickListener(new.
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
String name = txtName.getText().toString();
String description =
txtDescription.getText().toString();
String price = txtPrice.getText().toString();
String duration = txtDuration.getText().toString();
Intent intent5 = new Intent(AuctionList.this,BuyerHome.class);
intent5.putExtra("name",name);
intent5.putExtra("description",description);
intent5.putExtra("price",price);
intent5.putExtra("duration",duration);
startActivity(intent5);
}
});
I am having trouble with RecyclerView and cuscom Apdapter and I don't know why. My code isn't throwing error when I'm building but a
E/RecyclerView: No adapter attached; skipping layout
is showing at Run Logs.
I already watch a lot youtube tutorials and read other answers here at stockoverflow but still I am not able to fix my problem.
Here are my codes:
AccountFragment.java
public class AccountFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: MY VARIABLES
private RecyclerView listAccounts;
private ArrayList<Account> arrayAccount = new ArrayList<>();
private AdapterAccount adapterAccount;
private RecyclerView.LayoutManager layoutAccount;
private Context context;
private static final String accountURL = "LINK";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public AccountFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static AccountFragment newInstance(String param1, String param2) {
AccountFragment fragment = new AccountFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public void loadJSON(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, accountURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray accounts = new JSONArray(response);
for (int i = 0; i < accounts.length(); i++) {
JSONObject accountsObject = accounts.getJSONObject(i);
int id = accountsObject.optInt("accntID");
String username = accountsObject.optString("accntName");
String type = accountsObject.optString("accntType");
int station = accountsObject.optInt("statID");
String name = accountsObject.optString("lastName");
String address = accountsObject.optString("homeAddress");
String email = accountsObject.optString("emailAddress");
int contact = accountsObject.optInt("contactNumber");
Account account = new Account();
account.accountEntry(id, username, type, station, name, address, email, contact);
arrayAccount.add(account);
}
adapterAccount = new AdapterAccount(getContext());
listAccounts.setAdapter(adapterAccount);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
listAccounts = view.findViewById(R.id.accountRV);
layoutAccount = new LinearLayoutManager(getActivity());
listAccounts.setLayoutManager(layoutAccount);
loadJSON();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
AdapterAccount.java:
public class AdapterAccount extends RecyclerView.Adapter<AdapterAccount.ViewHolderAdapterAccount> {
private ArrayList<Account> arrayAccount = new ArrayList<>();
private LayoutInflater layoutInflater;
private Context context;
public AdapterAccount(Context context) {
this.context = context;
}
public AdapterAccount(ArrayList<Account> arrayAccount) {
this.arrayAccount = arrayAccount;
}
#Override
public ViewHolderAdapterAccount onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.profile_item, parent, false);
ViewHolderAdapterAccount viewHolder = new ViewHolderAdapterAccount(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderAdapterAccount holder, int position) {
Account currentAccount = arrayAccount.get(position);
holder.accountID.setText(currentAccount.getId());
holder.accountUsername.setText((currentAccount.getUsername()));
holder.accountType.setText(currentAccount.getType());
holder.accountStation.setText((currentAccount.getStation()));
holder.accountName.setText(currentAccount.getName());
holder.accountAddress.setText(currentAccount.getAddress());
holder.accountEmail.setText((currentAccount.getEmail()));
holder.accountContact.setText(currentAccount.getContact());
}
#Override
public int getItemCount() {
return arrayAccount.size();
}
static class ViewHolderAdapterAccount extends RecyclerView.ViewHolder {
private TextView accountID;
private TextView accountUsername;
private TextView accountType;
private TextView accountStation;
private TextView accountName;
private TextView accountAddress;
private TextView accountEmail;
private TextView accountContact;
public ViewHolderAdapterAccount(View accountView) {
super(accountView);
accountID = (TextView) itemView.findViewById(R.id.idPlaceXML);
accountUsername = (TextView) itemView.findViewById(R.id.usernamePlaceXML);
accountType = (TextView) itemView.findViewById(R.id.typePlaceXML);
accountStation = (TextView) itemView.findViewById(R.id.stationPlaceXML);
accountName = (TextView) itemView.findViewById(R.id.namePlaceXML);
accountAddress = (TextView) itemView.findViewById(R.id.addressPlaceXML);
accountEmail = (TextView) itemView.findViewById(R.id.emailPlaceXML);
accountContact = (TextView) itemView.findViewById(R.id.contactPlaceXML);
}
}
}
Account.java:
public class Account {
private int id;
private String username;
private String type;
private int station;
private String name;
private String address;
private String email;
private int contact;
public void accountEntry(int id,String username,String type,int station,String name,String address,String email,int contact){
this.id = id;
this.username = username;
this.type = type;
this.station = station;
this.name = name;
this.address = address;
this.email = email;
this.contact = contact;
}
public int getId(){
return id;
}
public String getUsername(){
return username;
}
public String getType() {
return type;
}
public int getStation() {
return station;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getEmail() {
return email;
}
public int getContact() {
return contact;
}
}
Add following method in AdapterAccount:
public setAccountList(ArrayList<Account> arrayAccount) {
this.arrayAccount = arrayAccount;
}
Change onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
listAccounts = view.findViewById(R.id.accountRV);
layoutAccount = new LinearLayoutManager(getActivity());
listAccounts.setLayoutManager(layoutAccount);
adapterAccount = new AdapterAccount(getContext());
listAccounts.setAdapter(adapterAccount);
loadJSON();
return view;
}
Change onResponse
public void onResponse(String response) {
try {
...
for (int i = 0; i < accounts.length(); i++) {
...
arrayAccount.add(account);
}
adapterAccount.setAccountList(arrayAccount);
adapterAccount.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I have a simple problem (I think), that I cannot solve, even after much research. So for the first time I decided to post. I apologize if this is basic, or I cannot explain well. I'm a beginner.
I am devoloping a project, where I must connect to a database of movies, and get information through json.
At this point, I have my app running a list of playing now movies as other lists.
My goal (and problem) now is: When offline, show the last list displayed on the screen.
For that, I must somehow save that list to a database (I've never worked with db), and delete and update to a new one whenever i change screens on my app, so that the last list is displayed when online.
After that, I must show that last saved list (updated db).
Questions: where to code for insert (update) database?
How to convert that list into a db class? I think I must do that...
How to do the otherwise to insert that in a listview?
I use the same xml for that ListView? Since have the same params I think so...
So, here part of my code for this:
Fragment
public class NowPlayingMoviesFragment extends BaseFragment{
private ListView listMovies;
private Button buttonGetMore;
private List<Movie> movieList;
private int currentPage=1;
private MovieAdapter movieAdapter;
private ListView listOfflineMovies;
public static NowPlayingMoviesFragment newInstance() {
Bundle args = new Bundle();
NowPlayingMoviesFragment fragment = new NowPlayingMoviesFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.now_playing_movies_fragment, container, false);
findViews(v);
executeNowPlayingMoviesRequest();
addListeners();
return v;
}
private void executeNowPlayingMoviesRequest() {
new GetNowPlayingMoviesAsyncTask(getActivity(), String.valueOf(currentPage), getResources().getString(R.string.language)) {
#Override
protected void onResponseSuccess(MoviesResponse moviesResponse) {
DLog.d(tag, "onResponseSuccess " + moviesResponse);
// create the adapter
if (movieAdapter != null) {
List<Movie> movies = moviesResponse.getMovies();
for (int i = 0; i < movies.size(); i++) {
movieList.add(movies.get(i));
}
movieAdapter.notifyDataSetChanged();
**//is it here i save into db??**
} else {
movieList = moviesResponse.getMovies();
movieAdapter = new MovieAdapter(getActivity(), movieList);
listMovies.setAdapter(movieAdapter);
}
}
#Override
protected void onNetworkError () {
DLog.d(tag, "onNetworkError ");
// Here i now that some error occur when processing the request,
// possible my internet connection if turned off
//OfflineMovieDbEntity();
//MoviesItemDbEntity offlineMovies = new MoviesItemDbEntity(getActivity(),Movie.getOriginalTitle());
// MoviesItemDbEntity offlineMovies = offlineMovies.findById(offLineMovies.class,1)
}
}.execute();
}
private void findViews(View v) {
listMovies = (ListView) v.findViewById(R.id.now_playing_movies_list_view);
buttonGetMore = (Button) v.findViewById(R.id.get_more_button_movies_now);
listOfflineMovies = (ListView) v.findViewById(R.id.offline_movies_screen_list_view);
}
private void addListeners() {
buttonGetMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage=currentPage+1;
executeNowPlayingMoviesRequest();
}
});
}
}
---------------------------------------------------------------
# Movie Adapter #
public class MovieAdapter extends ArrayAdapter<Movie> {
public MovieAdapter(#NonNull Context context, #NonNull List<Movie> objects) {
super(context, 0, objects);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v;
final ViewHolder holder;
final Movie item = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.movie_item, parent, false);
holder = new ViewHolder(v);
v.setTag(holder);
} else {
v = convertView;
holder = (ViewHolder) v.getTag();
}
holder.movieTitle.setText(item.getTitle());
//See movie details onclick
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), MovieDetailsScreen.class);
intent.putExtra("Movie", item);
getContext().startActivity(intent);
}
});
return v;
}
static class ViewHolder {
private TextView movieTitle;
public ViewHolder(View v) {
movieTitle = (TextView) v.findViewById(R.id.movie_item_title);
}
}
}
------------------------------------------------------------------------
#movie entitie#
public class Movie implements Parcelable {
#SerializedName("poster_path")
private String posterPath;
#SerializedName("overview")
private String overview;
#SerializedName("release_date")
private String releaseDate;
#SerializedName("original_title")
private String originalTitle;
#SerializedName("original_language")
private String originalLanguage;
#SerializedName("title")
private String title;
#SerializedName("backdrop_path")
private String backdropPath;
#SerializedName("popularity")
private Double popularity;
#SerializedName("vote_count")
private Integer voteCount;
#SerializedName("vote_average")
private Double voteAverage;
public String getPosterPath() {
return posterPath;
}
public String getOverview() {
return overview;
}
public String getReleaseDate() {
return releaseDate;
}
public String getOriginalTitle() {
return originalTitle;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public String getTitle() {
return title;
}
public String getBackdropPath() {
return backdropPath;
}
public Double getPopularity() {
return popularity;
}
public Integer getVoteCount() {
return voteCount;
}
public Double getVoteAverage() {
return voteAverage;
}
public Movie() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.posterPath);
dest.writeString(this.overview);
dest.writeString(this.releaseDate);
dest.writeString(this.originalTitle);
dest.writeString(this.originalLanguage);
dest.writeString(this.title);
dest.writeString(this.backdropPath);
dest.writeValue(this.popularity);
dest.writeValue(this.voteCount);
dest.writeValue(this.voteAverage);
}
protected Movie(Parcel in) {
this.posterPath = in.readString();
this.overview = in.readString();
this.releaseDate = in.readString();
this.originalTitle = in.readString();
this.originalLanguage = in.readString();
this.title = in.readString();
this.backdropPath = in.readString();
this.popularity = (Double) in.readValue(Double.class.getClassLoader());
this.voteCount = (Integer) in.readValue(Integer.class.getClassLoader());
this.voteAverage = (Double) in.readValue(Double.class.getClassLoader());
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel source) {
return new Movie(source);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
-----------------------------------------------------------------
#movies response#
public class MoviesResponse {
#SerializedName("page")
private Integer page;
#SerializedName("results")
private List<Movie> movies = new ArrayList<>();
#SerializedName("total_pages")
private Integer totalPages;
public Integer getPage() {
return page;
}
public Integer getTotalPages() {
return totalPages;
}
public List<Movie> getMovies() {
return movies;
}
}
-----------------------------------------------------------
MovieAsyncTask
public abstract class GetNowPlayingMoviesAsyncTask extends ExecuteRequestAsyncTask<MoviesResponse> {
private static final String PATH = "/movie/now_playing";
private static final String LANGUAGE_KEY = "language";
private static final String PAGE_KEY = "page";
private String page;
private String language;
public GetNowPlayingMoviesAsyncTask(Context context, String page, String language) {
super(context);
this.page=page;
this.language=language;
}
#Override
protected String getPath() {
return PATH;
}
#Override
protected void addQueryParams(StringBuilder sb) {
addQueryParam(sb, LANGUAGE_KEY, language);
addQueryParam(sb, PAGE_KEY, page);
}
#Override
protected Class<MoviesResponse> getResponseEntityClass() {
return MoviesResponse.class;
}
}
-----------------------------------------
#Movie Database#
public class MoviesItemDbEntity extends SugarRecord {
public static final String TITLE_COLUMN_NAME = "movie_title_column";
private String title;
public MoviesItemDbEntity() {
}
public MoviesItemDbEntity(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String setTitle() {
return title;
}
}
---------------------------------------------------------
#Movie Item xml#
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center_horizontal">
<TextView
android:id="#+id/movie_item_title"
style="#style/ItemListStyle"
android:text="lalalala"/>
</LinearLayout>
---------------------------------------------------------------
#now playing ListView xml#
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="#+id/now_playing_movies_title"
style="#style/TitleStyle"
android:text="#string/movies"/>
<Button
android:id="#+id/get_more_button_movies_now"
style="#style/ButtonMoreStyle"/>
<ListView
android:id="#+id/now_playing_movies_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/now_playing_movies_title">
</ListView>
</RelativeLayout>
I have my ArrayList
ArrayList<Item> itemList = new ArrayList<Item>();
It is then populated with Items.
Later on, I want to access the items attributes in a loop to get data but
Item[] itemArr = (Item[]) itemList.toArray();
This gives me error:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to com.raynemartin.SAAndroidAppCompetition.Item[]
If this is destined to fail, how else can I access attributes of Items?
The Items are in an ArrayList so they can populate and android ListView. Now I want to sort the ArrayList, but need to access the .getRating() method of my Item class.
Item[] itemArr= (Item[])itemList.toArray();
for(int i =0;i<itemArr.length;i++){
for(int j=i;i<itemArr.length;j++){
if(itemArr[j].getRating()>itemArr[i].getRating()){
Item temp = itemArr[j];
itemArr[j] = itemArr[i];
itemArr[i] = temp;
}
}
}
}
EDIT - here is item class code
public class Item {
private String title;
private String category;
private String downloads;
private double rating;
private Bitmap icon;
public Item(String title, String category, String downloads,double rating,Bitmap icon) {
this.title = title;
this.category = category;
this.downloads = downloads;
this.icon = icon;
this.rating = rating;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDownloads() {
return downloads;
}
public void setDownloads(String downloads) {
this.downloads = downloads;
}
public Bitmap getIcon() {
return icon;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}
To sort you can try the below.
In your Item class implement toString
public String toString()
{
return String.valueOf(rating);
}
Implement a Comparator
class SortingRating implements Comparator<Item>
{
#Override
public int compare(Item arg0, Item arg1) {
if (arg0.getRating() < arg1.getRating()) return -1;
if (arg0.getRating() > arg1.getRating()) return 1;
return 0;
}
}
Then sort your list
Collections.sort(itemList, new SortingRating());
Example : Correct me if i am wrong.
public class MainClass {
static ArrayList<Item> aa = new ArrayList<Item>();
public static void main(String[] args) {
Item i1 = new Item("soap","sales","yes",4.0);
aa.add(i1);
Item i2 = new Item("soap","sales","yes",5.2);
aa.add(i2);
Item i3 = new Item("soap","sales","yes",3.8);
aa.add(i3);
Item i4 = new Item("soap","sales","yes",5.1);
aa.add(i4);
Collections.sort(aa, new SortingRating());
for(int i=0;i<aa.size();i++)
{
System.out.println("Title : " +aa.get(i).getTitle()+"--"+"Category : "+aa.get(i).getCategory()+"--"+"Downlaods : "+aa.get(i).getDownloads()+"--"+"Rating : "+aa.get(i).getRating());
}
}
}
class SortingRating implements Comparator<Item>
{
#Override
public int compare(Item arg0, Item arg1) {
if (arg0.getRating() < arg1.getRating()) return -1;
if (arg0.getRating() > arg1.getRating()) return 1;
return 0;
}
}
Item class. Left out Bitmap icon
public class Item {
private String title;
private String category;
private String downloads;
private double rating;
public Item(String title, String category, String downloads,double rating) {
this.title = title;
this.category = category;
this.downloads = downloads;
this.rating = rating;
}
public String toString()
{
return String.valueOf(rating);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDownloads() {
return downloads;
}
public void setDownloads(String downloads) {
this.downloads = downloads;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}
Output
Title : soap--Category : sales--Downlaods : yes--Rating : 3.8
Title : soap--Category : sales--Downlaods : yes--Rating : 4.0
Title : soap--Category : sales--Downlaods : yes--Rating : 5.1
Title : soap--Category : sales--Downlaods : yes--Rating : 5.2
Let the class Item implement the interface Comparable and use
Collections.sort(itemList);
to sort your collection. So you don't have to construct an array and sort it yourself.
If you really need to access the elements as an array you would be better using
itemList.toArray(new Item[0]);
or
itemList.toArray(new Item[itemList.size()]);
as this will give you an array of type Item rather than an array of object. There is lots of discussion on this issue else where on the web.