My database is like this from firebase
I was figuring out how to combine this two as set1 and set2 on graph but the first problem I encounter is when I use the Date as x it must be in int.
gIncomeDatabase= FirebaseDatabase.getInstance().getReference().child("IncomeData").child(uid);
gExpenseDatabase= FirebaseDatabase.getInstance().getReference().child("ExpenseData").child(uid);
How can I convert the month into number where in I will use the number on x axis(1f) in here
#Override
public void onStart() {
super.onStart();
ArrayList<BarEntry> values1 = new ArrayList<>();
ArrayList<BarEntry> values2 = new ArrayList<>();
values1.add(new BarEntry(1f, 20));
values2.add(new BarEntry(1f, 20));
BarDataSet set1= new BarDataSet(values1,"Income");
BarDataSet set2= new BarDataSet(values2,"Expense");
BarData barData = new BarData(set1,set2);
set1.setValues(values1);
set2.setValues(values2);
barinc.setData(barData);
And is it also possible to put the name of the months below them?
Thank you so much
I would recommend you to make use of the: https://github.com/PhilJay/MPAndroidChart for displaying the bar graph.
Once you retrieve the data from the Firebase database and update the chart:
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get the data from the snapshot
Map<String, Long> data = (Map<String, Long>) dataSnapshot.getValue();
// Prepare the data for the chart
List<BarEntry> entries = new ArrayList<>();
int index = 0;
for (Map.Entry<String, Long> entry : data.entrySet()) {
entries.add(new BarEntry(index++, entry.getValue()));
}
// Create the chart
BarDataSet dataSet = new BarDataSet(entries, "Data");
BarData barData = new BarData(dataSet);
BarChart chart = (BarChart) findViewById(R.id.bar_chart);
chart.setData(barData);
chart.invalidate();
}
#Override
public void onCancelled(DatabaseError error) {
// Handle errors
}
});
Related
I'm trying to update the AnyChart pie chart with data provided through an input field, I want to have the pie chart update to reflect the added data.
Here's my code:
//Initialize the PieChart
AnyChartView anyChartView;
//Data Structures for Pie Chart
List<String> drinks = new ArrayList<>(Arrays.asList("Water", "Orange Juice", "Pepsi"));
List<Double> quantity = new ArrayList<>(Arrays.asList(50.5,20.2,15.2));
//Input fields
EditText drinkNameInput;
EditText drinkAmountInput;
//Button
Button addDrinkButton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intakechart);
drinkNameInput = findViewById(R.id.drinkNameArea);
drinkAmountInput = findViewById(R.id.drinkAmountArea);
addDrinkButton = findViewById(R.id.addDrinkButton);
anyChartView = findViewById(R.id.any_chart_view);
Pie pie = AnyChart.pie();
List<DataEntry> dataEntries = new ArrayList<>();
for(int i = 0; i < drinks.size(); i++)
dataEntries.add(new ValueDataEntry(drinks.get(i), quantity.get(i)));
pie.data(dataEntries);
anyChartView.setChart(pie);
addDrinkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
dataEntries.add(new ValueDataEntry(
drinkNameInput.getText().toString(),
Double.parseDouble(drinkAmountInput.getText().toString())
));
Log.v("Data: ", dataEntries.toString());
}
});
}
Whenever I add to the drinks and quantity lists from the inputted data, the pie chart does not update to reflect the changes. The lists however do contain the added drink and amount, so I know the button onClickListener is working. Does anyone see what's wrong?
Your chart has no reference to drinks or quantity. You will need to hold global reference to your dataEntries list and update that instead.
private List<DataEntry> dataEntries = new ArrayList<>();
public void onClick(View view) {
dataEntries.add(new ValueDataEntry(
drinkNameInput.getText().toString(),
Double.parseDouble(drinkAmountInput.getText().toString())));
pie.data(dataEntries);
}
I have a recycler view with flight information, and I am searching using the flight number on the search bar. When I search, the recyclerview is updated dynamically for which the logic is there in my filter function, however when I clear the search, the recycler view is completely empty. How can I fix this issue?
search filter function
private void filter(String text) {
ArrayList<FlightItem> filteredList = new ArrayList<>();
for(FlightItem item : flightItems) {
if(item.getFlightNumber().toLowerCase().contains(text.toLowerCase())){
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
flightItems.clear();
flightItems.addAll(filteredList);
}
}
keep a copy of flightItems, as you are clearing it before adding filtered items
ArrayList<FlightItem> flightItems = new ArrayList<>();
ArrayList<FlightItem> flightItemsCopy = new ArrayList<>();
private void filter(String text) {
if(text.trim() == ""){
clearSearch()
return
}
ArrayList<FlightItem> filteredList = new ArrayList<>();
for(FlightItem item : flightItems) {
if(item.getFlightNumber().toLowerCase().contains(text.toLowerCase())){
filteredList.add(item);
}
}
flightItemsCopy.clear(); //clear copy
flightItemsCopy.addAll(flightItems); // make a copy here
mAdapter.filterList(filteredList);
flightItems.clear();
flightItems.addAll(filteredList);
}
}
private void clearSearch(){
flightItems.clear();
flightItems.addAll(flightItemsCopy);
mAdapter.notifyDataSetChanged();
}
void filter(String text){
List<DataHolder> temp = new ArrayList();
for(DataHolder d: displayedList){
//or use .equal(text) with you want equal match
//use .toLowerCase() for better matches
if(d.getEnglish().contains(text)){
temp.add(d);
}
}
//update recyclerview
disp_adapter.updateList(temp);
}
updateList method :
public void updateList(List<DataHolder> list){
displayedList = list;
notifyDataSetChanged();
}
How to display new data at the top position of an adapter? Here are the coding:-
Sorry just now, I wrongly copy the coding, now I just noticed. Sorry my bad. The issues now is I want to display the latest advertisement at the top of the adapter....
mDatabase.child("Advertisement").child(mAuth.getUid()).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
//iterating through all the values in database
mChildrenList = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
Advertisement advertisement = postSnapshot.getValue(Advertisement.class);
mChildrenList.add(advertisement);
}
//Creating adapter
mAdapter = new AdvertisementAdapter(getApplicationContext(), mChildrenList, "AddAds");
//Adding adapter to recyclerview
mRecyclerView.setAdapter(mAdapter);
//mAdapter.notifyItemChanged(0);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
This line:
tuitionPackageList.add(0, new TuitionPackage(tuitionPackageList));
you get an error because you are instantiating a TuitionPackage object with tuitionPackageList as a parameter and I believe this is not correct.
Earlier in the code you made the same instantiation with just:
TuitionPackage tuitionPackage = new TuitionPackage();
and you added the item to the end of the list.
Is it this item that you wanted to add at position 0?
Edit change to this:
else {
TuitionPackage tuitionPackage = new TuitionPackage();
tuitionPackage.setPrice(mPriceView.getText().toString());
tuitionPackageList.add(0, tuitionPackage);
mPackageAdapter.notifyItemInserted(0);
}
replace last else block with this
TuitionPackage tuitionPackage = new TuitionPackage();
tuitionPackage.setPrice(mPriceView.getText().toString());
tuitionPackageList.add(tuitionPackage);
mPackageAdapter.notifyDataSetChanged();
Here are my answer with the help from the above coding to sort the first ads at the top position:-
//Iterating through all the values in database
mChildrenList = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
Advertisement advertisement = postSnapshot.getValue(Advertisement.class);
mChildrenList.add(0, advertisement);
}
//Creating adapter
mAdapter = new AdvertisementAdapter(getApplicationContext(), mChildrenList, "AddAds");
//Adding adapter to recyclerview
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyItemInserted(0);
I am trying to display my list of alarms in the ListActivity but it does not work. There rows appear but there is no text visible. I'm not sure if it's retrieving the data from the HashMap and inserting into the rows correctly.
Here is my code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_list);
List<Alarm> list;
Database db = new Database(AlarmListActivity.this);
list = db.getAllAlarms();
List<HashMap<String, String>> alarmMap = new ArrayList<HashMap<String, String>>();
for (Alarm alarm: list) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(Integer.toString(alarm.getID()), alarm.toString());
alarmMap.add(map);
}
if(!list.isEmpty() && list != null)
{
System.out.println("inside list");
System.out.println(list);
ListAdapter adapter = new SimpleAdapter(
AlarmListActivity.this,
alarmMap,
R.layout.list_item,
new String[] { "id", "hour"},
new int[] { R.id.id, R.id.time});
setListAdapter(adapter);
}
else
{
Toast.makeText(AlarmListActivity.this, "No Alarms Set",
Toast.LENGTH_SHORT).show();
}
}
This is what I get. You can vaguely see the lines of each row. But there is no text or anything. All the System.out.println() work as expected which print out the HashMap. It's just nothing is being displayed in the list. I've even added: android:text="Testing" to no avail
I'm new to Android and I have Adapter - ListView model to display array.
I set it's value's so:
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.bank_list,
new String[] { TAG_NAME, TAG_central_office_address }, new int[] {
R.id.bank_name, R.id.central_office_address});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, android.view.View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), BankExchangersListActivity.class);
in.putExtra("Bank_id", TAG_ID);
startActivity(in);
}
});
I get my values from JSON:
url = "http://192.168.1.4:3000/banks.json";
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
banks = json.getJSONArray(TAG_BANKS);
// looping through All Contacts
for(int i = 0; i < banks.length(); i++){
JSONObject c = banks.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String central_office_address = c.getString(TAG_central_office_address);
// Phone number is agin JSON Object
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_central_office_address, name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
As you can see in JSON I have ID field, but i didn't set it in ListView. For next query I click on ListView element and go to other activity, but I need to get TAG_ID of this element. Maybe I did something wrong? How to get element's TAG_ID on which I click, without displaying it on ListView?
JUST send tag_id of clicked item!
The position parameter of the onItemClick method gives the index of the selected item in the adapted list. So you can find the TAG_ID of the original item at
((Map<String, String>) adapter.getItem(position)).get(TAG_ID)
make the adapter final so that you can reference it inside the listener:
final ListAdapter adapter = ...
Hope this helps you.
you can get Postion of ListSelectedItemId and passed it with Intentand get it in SecondActivity now Here get FirstActivity HashMap with define it static
now use foreachloop to get all values from HashMap like
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
now with specific position of ListSelectedItemId you can get values from currentList
or like
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}