0

I am newbie android developer and i have a list of different currency items and I should open a new screen with chart of clicked item.

when user clicks on a list item a new screen should be opened which shows the exchange rate chart of the selected currency for the last 7 days based on USD. I should request every time the currency data gets updated for the last 7 days.

Example request for getting currency history in a given period between USD and CAD:

https://api.exchangeratesapi.io/history?start_at=2019-11-27&end_at=2019-12-03&base=USD&symbols=CAD

Here is My code:

MainActivity

 public class MainActivity extends AppCompatActivity {
        private ProgressBar progressBar;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            progressBar = findViewById(R.id.progress_bar);
            new GetServerData(this).execute();

        }

        private static class GetServerData extends AsyncTask<Integer, Void, List<CurrencyRate>> {
            private static final int TIMEOUT = 30000;
            private static final String BASE_URL = "https://api.exchangeratesapi.io/latest?base=USD";
            private WeakReference<MainActivity> activityReference;

            GetServerData(MainActivity context) {
                activityReference = new WeakReference<>(context);
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                MainActivity activity = activityReference.get();
                if (activity == null || activity.isFinishing()) {
                    return;
                }
                activity.progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            protected List<CurrencyRate> doInBackground(Integer... integers) {
                List<CurrencyRate> currencyList = new ArrayList<>();
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(true)
                        .build();
                Request request = new Request.Builder()
                        .url(BASE_URL)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    Log.d("Response", response.toString());
                    long tx = response.sentRequestAtMillis();
                    long rx = response.receivedResponseAtMillis();
                    System.out.println("response time : " + (rx - tx) + " ms");
                    JSONObject object = new JSONObject(Objects.requireNonNull(response.body()).string());
                    JSONObject rates = object.getJSONObject("rates");
                    Iterator<String> iterator = rates.keys();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        String value = rates.getString(key);
                        CurrencyRate data = new CurrencyRate(key, value);
                        currencyList.add(data);
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    Log.d("MainActivity", e.toString());
                }
                return currencyList;
            }

            @Override
            protected void onPostExecute(final List<CurrencyRate> result) {
                final MainActivity activity = activityReference.get();
                if (activity == null || activity.isFinishing()) {
                    return;
                }
                ListView listView = activity.findViewById(R.id.list_view);
                CurrencyAdapter adapter = new CurrencyAdapter(activity, result);
                listView.setAdapter(adapter);
                listView.smoothScrollToPosition(0);
                adapter.notifyDataSetChanged();
                activity.progressBar.setVisibility(View.GONE);
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Toast.makeText(activity.getApplicationContext(), result.get(i).getName()+" Clicked", Toast.LENGTH_SHORT).show();
                        /*Which code should be here to open a new screen with exchange chart for last 7 days of clicked item??*/
                    }
                });
            }
        }

    }

CurrencyRate class

public class CurrencyRate {
    private String name;
    private String value;

    public CurrencyRate(String name, String value) {
        super();
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

My emulator screen

enter image description here

so as you see the items,i want to show chart of clicked item (chart of currency in a given period 7 days between USD and Clicked item)

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Mohammed Qadah
  • 75
  • 1
  • 10
  • Isn’t your question very broad? Where is your search? Your attempt, your research? Asking without knowing Android programming (only good at Java). – Ole V.V. Dec 15 '19 at 09:35
  • @OleV.V. I have my own app in Github for news,you can take a look and see if i'm only good in ***JAVA*** :) [Github Link](https://github.com/moha-93/my-newsApp). – Mohammed Qadah Dec 16 '19 at 12:05
  • @OleV.V. I already solved this problem but what you told me about the `LocaleDate` i still can't convert it to `long` value i made a long array. `LocalDate date1 = LocalDate.parse(keyDate); int []date = new int[]{date1.getYear(),date1.getMonthValue(),date1.getDayOfMonth()}; StringBuilder builder = new StringBuilder(); for (int i :date) { builder.append(i); } long v = Long.parseLong(builder.toString());` and the result is **20191127**!!! how do i convert this number to 2019-11-27 without `String`. – Mohammed Qadah Dec 16 '19 at 14:31
  • @OleV.V. I think that i should format the value by using `XAxis` like that `xAxis.setValueFormatter(here i should use a class);` i should find similar to this question [Stackoverflow](https://stackoverflow.com/questions/47903716/format-date-labels-on-x-axis-in-mpandroidchart). – Mohammed Qadah Dec 16 '19 at 15:27

1 Answers1

1

I think that i should format the value by using XAxis like that xAxis.setValueFormatter(here i should use a class);

Elaborating on my answer to your other question and not knowing MPAndoirdChart, it would seem to me from the documentation that you need to make your own subclass of ValueFormatter and override getFormattedValue(float) to return something like LocalDate.ofEpochDay(Math.round(value)).toString(). Instead of toString you may want to use a DateTimeFormatter.

Here’s a quick attempt, not tested:

public class DateValueFormatter extends ValueFormatter {

    @Override
    String getFormattedValue(float value) {
        int epochDay = Math.round(value);
        LocalDate date = LocalDate.ofEpochDay(epochDay);
        return date.toString();
    }

}

My humble and tentative suggestion is that you instantiate an object of this class and pass it to xAxis.setValueFormatter().

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Thanks a lot for your help this is good idea but in this line which `value` i should pass `Date in String or in float`? `barEntries.add(new BarEntry(here i mean, Float.parseFloat(value)));` – Mohammed Qadah Dec 16 '19 at 16:08
  • I believe you can just pass `epochDayLong` from my first answer to the `BarEntry` constructor. Java will automatically convert from `long` to `float`. The idea is that the count of days since the epoch will be the unit that your chart uses on the *x* axis. I still recommend that you forget everything about the poorly designed and long outdated `Date` class. – Ole V.V. Dec 16 '19 at 16:29
  • Thank you! finally i got the correct Date,You are Amazing :) – Mohammed Qadah Dec 16 '19 at 17:24
  • How can i become a successful Android Developer Can you give me some advice please? – Mohammed Qadah Dec 16 '19 at 17:58
  • The information and suggestions that you can already find on Internet will serve you much better than what I can dream up here. Also in the end, the path that works for one person may not work for someone else, so you will need to find your own variant. Good luck! – Ole V.V. Dec 16 '19 at 18:02
  • Hi, can you please help me with this question [link](https://stackoverflow.com/questions/60075224/how-to-redirect-to-homepage-url-after-login) because only your answer healing my wounds :) – Mohammed Qadah Feb 05 '20 at 12:42