0

Today i discovered really dumb problem.

Here is my mainactivity:

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private CoinRecyclerViewAdapter coinRecyclerViewAdapter;
    private List<Coin> coinList;
    private RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        queue= Volley.newRequestQueue(this);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        recyclerView=findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        coinList=new ArrayList<>();

        Prefs prefs = new Prefs(MainActivity.this);
        String search = prefs.getSearch();
        getCoins(search);

    }

    //get coins
    public List<Coin> getCoins(
            String searchTerm
    ){
        coinList.clear();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                Constants.URL_LEFT
                //searchTerm+Constants.URL_RIGHT
                , new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    JSONArray coinsArray=response.getJSONArray("data");

                    for (int i = 0; i < coinsArray.length(); i++){

                        JSONObject coinObj = coinsArray.getJSONObject(i);

                        Coin coin = new Coin();
                        coin.setName(coinObj.getString("name"));
                        coin.setSymbol(coinObj.getString("symbol"));
                        coin.setPrice(coinObj.getDouble("price"));
                        coin.setRank(coinObj.getInt("rank"));
                        coin.setPercentChange24h(coinObj.getDouble("percent_change_24h"));
                        coin.setMarketCap(coinObj.getDouble("market_cap"));
                        //coin.setPriceBtc(coinObj.getFloat("price_btc"));
                        coin.setTotalSupply(coinObj.getLong("total_supply"));
                        Log.d("kreten","kreten");
                        Log.d("coins:",String.valueOf(coin.getPrice()));


                    }

                }catch (JSONException e){
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(jsonObjectRequest);
        return coinList;
    }






    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
} 

I need to parse data from this api to my application https://api.coinmarketcap.com/v2/ticker/

I found problem when tried to compile and get data from json object but when i tried Log.d("Coins",coin.getName()); i don't get any names i get this Value: and whole json data (that is not what i wanted , i need only names so i think i made mistake in MainActivity where i try to grab "data" object i think i am getting it but i don't get full objects because i think i need code to read random numbers above coins id in api or below "data"

So my question is how to get price,rank ,symbol etc from api i think i made mistake here :

  //get coins
    public List<Coin> getCoins(
            String searchTerm
    ){
        coinList.clear();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                Constants.URL_LEFT
                //searchTerm+Constants.URL_RIGHT
                , new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    JSONArray coinsArray=response.getJSONArray("data");

                    for (int i = 0; i < coinsArray.length(); i++){

                        JSONObject coinObj = coinsArray.getJSONObject(i);

                        Coin coin = new Coin();
                        coin.setName(coinObj.getString("name"));
                        coin.setSymbol(coinObj.getString("symbol"));
                        coin.setPrice(coinObj.getDouble("price"));
                        coin.setRank(coinObj.getInt("rank"));
                        coin.setPercentChange24h(coinObj.getDouble("percent_change_24h"));
                        coin.setMarketCap(coinObj.getDouble("market_cap"));
                        //coin.setPriceBtc(coinObj.getFloat("price_btc"));
                        coin.setTotalSupply(coinObj.getLong("total_supply"));
                        Log.d("kreten","kreten");
                        Log.d("coins:",String.valueOf(coin.getPrice()));


                    }

Thanks guys for time to help me.

p.s. my second question doesn't belongs here but i don't know why i can not compile android when i import PICASSO LIBARY ,, really strange thing...

If someone wanna join me on project message me here or on skype: drvenapila

ColdFire
  • 6,764
  • 6
  • 35
  • 51
Čika Tuna
  • 43
  • 2
  • 3
  • 8

1 Answers1

0

Your line

 JSONArray coinsArray=response.getJSONArray("data");

..wants to parse the data object as an array. If we look at the first lines of the JSON response from coinmarketcap.com/v2/ticker we see

{
"data": {
    "1": {
        "id": 1, 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "website_slug": "bitcoin", 
        "rank": 1, 

..but if it was an array, it would go like "data": [ {

"data" instead contains a Map<String,Object> where the Keys are the current ranking of the coin. E.g. 1 : Bitcoin, 2 : Ethereum, 3 : Ripple

So what you probably want is to get this Map out of "data" and then get the Object for each key(s) you desire.

This may help you: Convert JSON to Map

Trivia: Funny how each Coin-Object has an "id" which matches the keys of the map.. Indeed one would expect an array here.

Gewure
  • 1,208
  • 18
  • 31
  • May i ask you how can i then import that to my source ? what to use what command , where to put it ? please help me to fix this.. i think i should used gson instead of volley,but i am now too far away to switch to gson..can you explain me on instance how to put these values into map ? – Čika Tuna May 03 '18 at 01:49
  • hum. something like `HashMap result = new ObjectMapper().readValue(response.get("data"), HashMap.class);` – Gewure May 03 '18 at 01:53
  • I really don't get what i need to put instead of Also i don't get why i don't have that method ObjectMapper, Where i need to put code , in onResponse in MainActivity or where? Can you add me on gmail cikatuna@gmail.com or skype: drvenapila and try to teach me this, i am willing to pay you for your time. – Čika Tuna May 03 '18 at 01:57
  • i emailed you, need to sleep now. – Gewure May 03 '18 at 02:03