I would like my child data to update in real-time when I change the data. I am new in Java programming. The error was when i tried to set the my list arraylist with new child data, there is a error for wrong 2nd argument. The Following is my code...Appreciate any helps, Thank in advance.
public class OverallResultFragment extends Fragment {
private static final String TAG = "OverallResultFragment";
private ArrayList<Booth> list = new ArrayList<>();;
private ArrayList<Booth> mkeys = new ArrayList<>();
ProductListAdapter adapter = null;
private Firebase mRef;
ListView gridView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Firebase.setAndroidContext(this.getContext());
View view = inflater.inflate(R.layout.activity_votingresult, container, false);
mRef = new Firebase("https://myfb.firebaseio.com/myfb");
gridView = (ListView) view.findViewById(R.id.gridView);
adapter = new ProductListAdapter(this.getContext(), R.layout.list_product_item, list);
gridView.setAdapter(adapter);
com.firebase.client.Query Queryref = mRef.orderByValue();
Queryref.addChildEventListener(new com.firebase.client.ChildEventListener() {
#Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
String boothname = dataSnapshot.getKey();
list.add(new Booth(boothname, value));
mkeys.add(new Booth(boothname));
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
String boothname = dataSnapshot.getKey();
int index = mkeys.indexOf(boothname);
list.set(index, value);//error on "value" -> wrong 2nd argument.
adapter.notifyDataSetChanged();
}
}
And this is my Booth class:
public class Booth {
String rating;
String Boothname;
int index;
public Booth(String boothname, String Rating){
this.Boothname = boothname;
this.rating= Rating;
}
public String getBoothName(){
return Boothname;
}
public void setProductId(String boothname){
this.Boothname = boothname;
}
public String getRating(){
return rating;
}
public void setRating(String rating){
this.rating = rating;
}
}
Error is because it's not a string type 2nd Argument.
Replace that line with this:
list.set(index, new Booth(boothname,value));
It will work for you
Thanks and happy coding.
EDITED
Replace this line :
int index = mkeys.indexOf(boothname);
With this:
int index = mkeys.indexOf(new Booth(boothname));
It will solve your crash issue.
Related
I have an array of data which I am retrieving from firebase. I am using a recyclerview to display the data but my adapter is not working correctly.I tried adding the arraylist in the adapter but this is not working.
It is saying the adapter is not attached and I am having a blank activity.
Any help on this ?
Here are my details.
Modal Class
public class Order {
private String ProductId;
private String ProductName;
private String Quantity;
public Order() {
}
public String getProductId() {
return ProductId;
}
public void setProductId(String productId) {
ProductId = productId;
}
public String getProductName() {
return ProductName;
}
public void setProductName(String productName) {
ProductName = productName;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public Order(String productId, String productName, String quantity) {
ProductId = productId;
ProductName = productName;
Quantity = quantity;
}
}
Adapter
public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersViewHolder> {
List<Order> myfoods;
public AllOrdersAdapter(List<Order> myfoods) {
this.myfoods = myfoods;
}
#NonNull
#Override
public AllOrdersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.allorders_layout,parent,false);
return new AllOrdersViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull AllOrdersViewHolder holder, int position) {
holder.foodname.setText(myfoods.get(position).getProductName());
holder.foodquantity.setText(myfoods.get(position).getQuantity());
holder.foodId.setText(myfoods.get(position).getProductId());
}
#Override
public int getItemCount() {
return myfoods.size();
}
}
Test Class
public class Test extends AppCompatActivity {
FirebaseDatabase db;
DatabaseReference requests;
RecyclerView lstFoods;
RecyclerView.LayoutManager layoutManager;
TextView food_id,food_quan,food_name;
// List foods = new ArrayList<>();
// RecyclerView.Adapter<AllOrder> adapter;
// List<String> myOrders = new ArrayList<String>();
// ArrayList<String> foods=new ArrayList<>();
List<String> myfoods = new ArrayList<String>();
AllOrdersAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
//firebase
db = FirebaseDatabase.getInstance();
requests= db.getReference().child("Requests");
lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
lstFoods.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
lstFoods.setLayoutManager(layoutManager);
loadOrderss();
}
private void loadOrderss() {
requests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if (postSnapshot.getValue() != null) {
// List ingredients = new ArrayList<>();
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
// String data = String.valueOf(postSnapshot.getValue(Order.class));
myfoods.add(ing.child("quantity").getValue(String.class));
myfoods.add(ing.child("productName").getValue(String.class));
myfoods.add(ing.child("productId").getValue(String.class));
// myfoods.add(String.valueOf(Order.class));
System.out.println("Gained data: " + ing.child("productName").getValue(String.class));
}
}
}
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
lstFoods.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
There seems to be a couple things wrong with the code. As it is posted I would be surprised if it compiles.
In your Adapter you have:
List<Order> myfoods;
and
public AllOrdersAdapter(List<Order> myfoods) {
this.myfoods = myfoods;
}
but in your activity code you pass:
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
one is a ArrayList of String the other of Order !
You also need to change your adapter class to something like:
public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersAdapter.AllOrdersViewHolder> {
private static final String TAG = AllOrdersAdapter.class.getSimpleName();
private ArrayList<Order> mData;
public class AllOrdersViewHolder extends RecyclerView.ViewHolder {
public TextView mTvFoodname;
public TextView mTvFoodQuantity;
public TextView mTvFoodId;
public AllOrdersViewHolder(View v){
super(v);
// TODO: You need to assign the appropriate View Id's instead of the placeholders ????
mTvFoodQuantity = v.findViewById(R.id.????);
mTvFoodname = v.findViewById(R.id.????);
mTvFoodId = v.findViewById(R.id.????);
}
}
public AllOrdersAdapter(ArrayList<Order> data){
this.mData = data;
}
#Override
public AllOrdersViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.business_list_card_view, parent, false);
return new AllOrdersViewHolder(itemView);
}
#Override
public void onBindViewHolder(final AllOrdersViewHolder holder, final int position){
//TODO: You need to decide whether you want to pass a string or order object
Order data = mData.get(position);
final String name = data.getProductName();
final String quantity = data.getQuantity();
final String id = data.getProductId();
holder.mTvFoodname.setText(name);
holder.mTvFoodQuantity.setText(quantity );
holder.mTvFoodId.setText(id)
}
#Override
public int getItemCount(){
return mData.size();
}
}
Note: That since I can not know, whether an ArrayList of String or of Order should be used the parameters in either the Activity or Adapter will need to be changed. Also how you assign the data to the RecyclerView will be affected in the onBindViewHolder method.
You should also follow the advice given by Frank.
EDIT
Change your onDataChange() method to this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if (postSnapshot.getValue() != null) {
List ingredients = new ArrayList<>();
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
String name = ing.child("productName").getValue(String.class);
String quantity = ing.child("quantity").getValue(String.class);
String productId = ing.child("productId").getValue(String.class);
// Using your overloaded class constructor to populate the Order data
Order order = new Order(productId, name, quantity);
// here we are adding the order to the ArrayList
myfoods.add(order);
Log.e(TAG, "Gained data: " + name)
}
}
}
adapter.notifyDataSetChanged();
}
In your Activity you will need to change the ArrayList class variable "myfoods" to this:
ArrayList(Order) myfoods = new ArrayList<>();
and in your onCreate() method you can now change:
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
to simply this:
adapter = new AllOrdersAdapter(myfoods);
Also notice that I have made some changes in my original code above.
You'll want to create the adapter, and attach it to the view, straight in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
//firebase
db = FirebaseDatabase.getInstance();
requests= db.getReference().child("Requests");
lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
lstFoods.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
lstFoods.setLayoutManager(layoutManager);
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
lstFoods.setAdapter(adapter);
loadOrders();
}
This also means you should declare myfoods as a ArrayList<String>, which saves you from having to downcast it. Something like:
ArrayList<String> myfoods = new ArrayList<String>();
Now in loadOrders you simple add the items to the list, and then notify the adapter that its data has changed (so that it repaints the view):
private void loadOrders() {
requests.child("foods").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot ing: postSnapshot.getChildren()) {
myfoods.add(ing.child("quantity").getValue(String.class));
myfoods.add(ing.child("productName").getValue(String.class));
myfoods.add(ing.child("productId").getValue(String.class));
}
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
I'm trying to display another list inside my custom listview like in the image below. I have successfully display the first three child(name, sport and town). But when i add the coverage child i got this error 'failed to convert value of type arraylist to string' in main activity.
Error message
Failed to convert value of type java.util.ArrayList to String
This is the display im trying to achieve
This is what im trying to achieve
This is my firebase database structure
db structure
I got this code below for my main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView)findViewById(R.id.cusListView);
mTextView = (TextView)findViewById(R.id.textV);
mRef = FirebaseDatabase.getInstance().getReference().child("Person");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot){
ArrayList<PeopleGetSet> array = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
PeopleGetSet arr = ds.getValue(PeopleGetSet.class);
array.add(arr);
ViewDatabase adapter = new ViewDatabase(this, R.layout.adapter_view_layout, array);
mListView.setAdapter(adapter);
}
}
This it my code for Adapter
public class ViewDatabase extends ArrayAdapter<PeopleGetSet> {
private static final String TAG="ViewDatabase";
private Context mContext;
int mResource;
public ViewDatabase(#NonNull Context context, int resource, #NonNull List<PeopleGetSet> objects) {
super(context, resource, objects);
this.mContext=context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String name =getItem(position).getName();
String sport =getItem(position).getSport();
String town =getItem(position).getTown();
String Coverage =getItem(position).getCoverage();
PeopleGetSet person = new PeopleGetSet(name,sport, town, Coverage);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView=inflater.inflate(mResource, parent, false);
TextView tvName = (TextView)convertView.findViewById(R.id.textView);
TextView tvSport = (TextView)convertView.findViewById(R.id.textView2);
TextView tvTown = (TextView)convertView.findViewById(R.id.textView3);
TextView tvCoverage = (TextView)convertView.findViewById(R.id.textView4);
tvName.setText(name);
tvSport.setText(sport);
tvTown.setText(town);
tvCoverage.setText(Coverage);
return convertView;
}
}
And this is my code for Getter and setter
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private String Coverage;
public PeopleGetSet() {
}
public PeopleGetSet(String name, String sport, String town, String Coverage) {
this.name = name;
this.sport = sport;
this.town = town;
this.Coverage = Coverage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getCoverage() {
return Coverage;
}
public void setCoverage(String coverage) {
Coverage = coverage;
}
}
I mean like this:
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private Coverage coverage;
... default code
}
public class Coverage {
private ArrayList<String> names;
... default code
}
Problem is in your Getter Setter class Add Coverage as Hashmap in your PeopleGetSet class. Coverage is not string its array so to read array from firebase you should use HashMap
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private HashMap<String,String> Coverage ;
public PeopleGetSet() {
}
public PeopleGetSet(String name, String sport, String town, HashMap<String, String> Coverage) {
this.name = name;
this.sport = sport;
this.town = town;
this.Coverage = Coverage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public String getTown() {
return town;
}
public HashMap<String,String> getCoverage() {
return Coverage;
}
There is a simple way to inflate multiple views inside one ListView. Here's my example code.
public class MyExampleCode extends ArrayAdapter<Object> {
private static final int TYPE_1 = 0;
private static final int TYPE_2 = 1;
private Context context;
private List<Object> objectList;
public MyExampleCode(Context context, List<Object> objectList) {
super(context,layout,objectList);
this.context = context;
this.objectList = objectList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (getItemViewType(position) == TYPE_1) {
PeopleGetSet peopleGetSet = (PeopleGetSet)objectList.get(position);
//handle code for first object, inflate layout and fill it
} else {
Coverage coverage = (Coverage)objectList.get(position);
//handle code for second object, inflate layout and fill it
}
}
#Override
public int getItemViewType(int position) {
if (getItem(position) instanceof PeopleGetSet) {
return TYPE_1;
} else {
return TYPE_2;
}
}
#Nullable
#Override
public Object getItem(int position) {
return objectList.get(position);
}
#Override
public int getCount() {
return objectList.size();
}
}
#Edit
Let update your code
private void showData(DataSnapshot dataSnapshot){
List<Object> array = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
PeopleGetSet arr = ds.getValue(PeopleGetSet.class);
Coverage arr2 = arr.getCoverage();
array.add(arr);
array.add(arr2);
}
ViewDatabase adapter = new ViewDatabase(this, array);
mListView.setAdapter(adapter);
}
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");
I want to sort an ArrayList of HashMaps
ArrayList < HashMap < String,Object>>
in the following class:
public class NotificationFragment extends ListFragment {
private static final String TAG = "NotificationFragment";
private DatabaseReference mDatabaseReference;
private ProgressBar mProgressBar;
String[] from = {"TITLE","BODY","TIME"};
int[] to = {R.id.single_notification_row_title,
R.id.single_notification_row_body,
R.id.single_notification_row_time};
ArrayList<HashMap<String,Object>> data;
SimpleAdapter adapter;
public NotificationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_notification, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Set Activity title
getActivity().setTitle(R.string.Notifications);
mDatabaseReference = FirebaseDatabase.getInstance().getReference()
.child("Notification").child("Android");
Query query = mDatabaseReference.orderByChild("title");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
getNewData((Map<String,Object>)dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), R.string.Something_went_wrong_retry, Toast.LENGTH_SHORT).show();
}
});
}
private void cancelNotification(Activity activity, int notifyId) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) activity.getSystemService(ns);
nMgr.cancel(notifyId);
}
private void getNewData (Map<String,Object> mapDatabase){
mProgressBar = (ProgressBar)getActivity().findViewById(R.id.progressBarNotifications);
data = new ArrayList<>();
try{
//Iterate through each notification
for(Map.Entry<String,Object> entry : mapDatabase.entrySet()){
Log.e(TAG, "ForEach entered");
Map singleNotification = (Map)entry.getValue();
//Fill the list
String title = (String) singleNotification.get("title");
String body = (String) singleNotification.get("body");
String time = (String) singleNotification.get("time");
String timeLong = (String) singleNotification.get("timeStamp");
HashMap<String,Object> map = new HashMap<>();
map.put("TITLE", title);
map.put("BODY", body);
map.put("TIME", time);
map.put("timeLong", timeLong);
data.add(map);
Log.d(TAG,"data.add(map)");
Log.d(TAG,"data.size = " + data.size());
}
for(HashMap<String, Object> myMap: data) {
for(Map.Entry<String, Object> mapEntry: myMap.entrySet()) {
String key = mapEntry.getKey();
String value = (String) mapEntry.getValue();
if(key.equals("timeLong")){
Log.d(TAG,"timeLong = " + value);
//?????????HOW TO SORT by LONG VALUE ??????????
}
}
}
//Adapter
adapter = new SimpleAdapter
(getActivity(),data,R.layout.single_notification_row ,from,to);
setListAdapter(adapter);
Log.d(TAG,"setListAdapter(adapter)");
}catch (NullPointerException e){
Toast.makeText(getActivity(), R.string.No_Notifications, Toast.LENGTH_SHORT).show();
}
if(mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.GONE);
}
cancelNotification(getActivity(), 0);
}
#Override
public void onStart() {
super.onStart();
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "HI", Toast.LENGTH_SHORT).show();
}
});
}
}
I get the following sorting order:
Screenshot
Please note that I have one single Long item (called "timeLong") in every ArrayList item.
Thank you in advance,
Gaetano
,I suggest you to create a class which contains 4 properties :
String title;
String body;
String time;
long timeLong;
Lets say the name of the class is Instance. When you get the data, create an instance of this class and set the properties of this instance instead of having 4 string values.
Change your ArrayList to this ArrayList<Instance> myList = ArrayList();
Create a class
public class SortingClass implements Comparator<Instance>
{
public int compare(Instance left, Instance right){
return left.timeLong < right.timeLong ? 1 : -1;
}
And for sorting
Collections.sort(myList,new SortingClass())
Thanks in advance for the help, my code below is taken in a Text File and Displaying it in a ListView, i have Name and youtube in one Line inside the text field.
but what i am looking at trying to do is get the youtube String inside the text file and pass that to my new Activity class as a webview to play the video
just wondering how can this be done, how can i pass this String into my Setters inside my Model class in order to get an Instance of it, do i need to convert String to ArrayListString ?
public class menuFragment extends ListFragment {
ArrayList<model> songList = new ArrayList<model>();
public String[] listSongs = new String[]{};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
loadSongs();
return view;
}
public void loadSongs() {
try {
Resources ResFiles = getResources();
InputStream ReadDbFile = ResFiles.openRawResource(R.raw.songs);
byte[] Bytes = new byte[ReadDbFile.available()];
ReadDbFile.read(Bytes);
String DbLines = new String(Bytes);
listSongs = DbLines.split(",");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, listSongs);
setListAdapter(adapter);
} catch (Exception e) {
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent i = new Intent(getActivity(), playVid.class);
model selectedSong = MainController.getInstance().getSongs().get(position);
i.putExtra("selectedSong", selectedSong);
startActivity(i);
}
public class model implements Serializable {
private String name;
private String url;
public model(String name, String url) {
this.name=name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl(){
return url;
}
public void setUrl(String url){
this.url = url;
}
public class MainController
{
private static MainController instance;
private ArrayList<model> songList;
private MainController()
{
this.songList = new ArrayList<model>();
}
public static MainController getInstance()
{
if(instance == null)
{
instance = new MainController();
}
return instance;
}
public void addFlight(String name, String singer, String url)
{
model f = new model(name,singer,url);
this.songList.add(f);
}
public ArrayList<model> getSongs()
{
return this.songList;
}
Suggestion class name should be start with capital - Model.
You have only three variables to pass to another activity, so you can have three putExtra with your intent no need for ArrayList, Sir.
Model selectedSong = MainController.getInstance().getSongs().get(position);
i.putExtra("name", selectedSong.getName());
i.putExtra("singer", selectedSong.getSinger());
i.putExtra("url", selectedSong.getUrl());
startActivity(i);
And inside onCreate of another Activity, we can access these three values like this way,
Intent mIntent = getIntent();
String name = mIntent.getStringExtra("name");
String singer = mIntent.getStringExtra("singer");
String url = mIntent.getStringExtra("url");