-1

I have a ListView and I can show data of list using ArrayList and ArrayAdapter. But I want to show my ArrayList using JSONArray, what should I do? I have this list.

private void setData(){
    coinsList=new ArrayList<>();
    coinsList.add("BTC");
    coinsList.add("ETH");
    coinsList.add("LTC");
    val= new ArrayList<>();
    val.add("$"+mytext1);
    val.add("$"+mytext2);
    val.add("$"+mytext3);
    val2=new ArrayList<>();
    val2.add(mytext4+"%");
    val2.add(mytext5+"%");
    val2.add(mytext6+"%");
    flags= new ArrayList<>();
    flags.add(R.drawable.bit);
    flags.add(R.drawable.eth);
    flags.add(R.drawable.ltc);
    bell= new ArrayList<>();
    bell.add(R.drawable.ring);
    bell.add(R.drawable.ring);
    bell.add(R.drawable.ring);
}

This is my Adapter Class using ArrayAdapter to show data in listview but i want to show my list using jsonArray not only with Arraylist.i want to make ease when will i parse my data from server.

 public class Adapter_list extends ArrayAdapter<String> {

private MainActivity activity;
private List<String> coinsList;
private List<String> mval;
private List<String> mval2;
private List<Integer> mflags;
private List<Integer> mbell;


public Adapter_list(MainActivity context, int resource, ArrayList<String> coinsList, List<String> val, ArrayList<String> val2, ArrayList<Integer> flags, ArrayList<Integer> bell) {
    super(context, resource,coinsList);
    this.activity = context;
    this.coinsList=coinsList;
    this.mval=val;
    this.mval2=val2;
    this.mflags=flags;
    this.mbell=bell;
}
@Override
public int getCount() {
    return coinsList.size();
}

@Override
public String getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    // If holder not exist then locate all view from UI file.
    if (convertView == null) {
        // inflate UI from XML file
        convertView = inflater.inflate(R.layout.list, parent, false);
        // get all UI view
        holder = new ViewHolder(convertView);
        // set tag for holder
        convertView.setTag(holder);
    } else {
        // if holder created, get tag from view
        holder = (ViewHolder) convertView.getTag();
    }

    holder.coin.setText(coinsList.get(position));
    holder.price.setText(mval.get(position));
    holder.price2.setText(mval2.get(position));
    holder.imageView.setImageResource(mflags.get(position));
    holder.imageView2.setImageResource(mbell.get(position));
    //get first letter of each String item
    return convertView;
}

// Filter method
 private class ViewHolder {
    private ImageView imageView,imageView2;
    private TextView coin,price,price2;

    public ViewHolder(View v) {
        imageView = (ImageView) v.findViewById(R.id.imageView);
        imageView2=(ImageView)v.findViewById(R.id.imageView2);
        coin = (TextView) v.findViewById(R.id.textView8);
        price = (TextView) v.findViewById(R.id.textView9);
        price2=(TextView)v.findViewById(R.id.textView10);
    }
}
}
gourav manuja
  • 47
  • 1
  • 7

2 Answers2

1

This is how you can create JSONArray

     try {
        JSONArray coinsList = new JSONArray();
        coinsList.put("BTC");
        coinsList.put("ETH");
        coinsList.put("LTC");

        JSONArray val1 = new JSONArray();
        val1.put("$"+mytext1);
        val1.put("$"+mytext2);
        val1.put("$"+mytext3);

        JSONArray val2 = new JSONArray();
        val2.put(mytext4+"%");
        val2.put(mytext5+"%");
        val2.put(mytext6+"%");

        JSONArray flags = new JSONArray();
        flags.put(R.drawable.bit);
        flags.put(R.drawable.eth);
        flags.put(R.drawable.ltc);

        JSONArray bell = new JSONArray();
        bell.put(R.drawable.ring);
        bell.put(R.drawable.ring);

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

Alternate Suggestion

       // Create your list like this
        ArrayList<DataClass> data = new ArrayList<>();
        DataClass d1 = new DataClass("BTC", "$"+mytext1, mytext4+"%", R.drawable.bit, R.drawable.ring);
        DataClass d2 = new DataClass("ETH", "$"+mytext2, mytext5+"%", R.drawable.eth, R.drawable.ring);
        DataClass d3 = new DataClass("LTC", "$"+mytext3, mytext6+"%", R.drawable.ltc, R.drawable.ring);

        data.add(d1);
        data.add(d2);
        data.add(d3);


        // In your adapter fetch data like this
        holder.coin.setText(data.get(position).getCoins());
        holder.price.setText(data.get(position).getVal());
        holder.price2.setText(data.get(position).getVal2());
        holder.imageView.setImageResource(data.get(postion).getFlags());
        holder.imageView2.setImageResource(data.get(position).getBell());

Create a java file like below DataClass.java

public class DataClass {
    String coins;
    String val;
    String val2;
    int flags;
    int bell;


    public DataClass(String coins, String val, String val2, int flags, int bell) {
        this.coins = coins;
        this.val = val;
        this.val2 = val2;
        this.flags = flags;
        this.bell = bell;
    }

    public int getBell() {
        return bell;
    }

    public String getCoins() {
        return coins;
    }

    public int getFlags() {
        return flags;
    }

    public String getVal() {
        return val;
    }

    public String getVal2() {
        return val2;
    }

    public void setBell(int bell) {
        this.bell = bell;
    }

    public void setCoins(String coins) {
        this.coins = coins;
    }

    public void setFlags(int flags) {
        this.flags = flags;
    }

    public void setVal(String val) {
        this.val = val;
    }

    public void setVal2(String val2) {
        this.val2 = val2;
    }
}

Now using this. You just need to pass your DataClass arrayList to adapter and you will get all your data there And your adapter should extend this class, ArrayAdapter<DataClass>

Building JSONArray with dataClass

         try {
            JSONArray jsonArray = new JSONArray();

            JSONObject obj1 = new JSONObject();
            obj1.put("coins", "BTC");
            obj1.put("val", "$"+mytext1);
            obj1.put("val2", mytext4+"%");
            obj1.put("flags", R.drawable.btc);
            obj1.put("bell", R.drawable.ring);

            JSONObject obj2 = new JSONObject();
            obj2.put("coins", "ETH");
            obj2.put("val", "$"+mytext2);
            obj2.put("val2", mytext5+"%");
            obj2.put("flags", R.drawable.eth);
            obj2.put("bell", R.drawable.ring);

            JSONObject obj3 = new JSONObject();
            obj3.put("coins", "LTC");
            obj3.put("val", "$"+mytext3);
            obj3.put("val2", mytext6+"%");
            obj3.put("flags", R.drawable.ltc);
            obj3.put("bell", R.drawable.ring);


            jsonArray.put(obj1);
            jsonArray.put(obj2);
            jsonArray.put(obj3);

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


        // Accesing it like this
        for(int i=0;i<jsonArray.length();i++) {
            String coins = jsonArray.getJSONObject(i).getString("coins");
            String val = jsonArray.getJSONObject(i).getString("val");
            String val2 = jsonArray.getJSONObject(i).getString("val2");
            String flags = jsonArray.getJSONObject(i).getString("flags");
            String bell = jsonArray.getJSONObject(i).getString("bell");
        }
Arshad
  • 1,262
  • 16
  • 25
  • let me post an alternale solution for your arraylist, so you can do all this using single array list – Arshad May 11 '18 at 06:14
  • JSONArray jsonArray = new JSONArray(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.getJSONObject(i); can i do something like that...??? – gourav manuja May 11 '18 at 06:44
  • yes. but in this case you are storing string in jsonarray so it will be String obj = jsonArray.getString(i); – Arshad May 11 '18 at 06:51
  • now i have created my jsonlist like that but i want to know about change of my Adapter class – gourav manuja May 11 '18 at 06:58
  • in your adapter you fetch it the same way you are doing now. just use coinsJsonArray.getString(position); – Arshad May 11 '18 at 07:16
  • but the way you have done its not recommended. Passing multiple list and fetch with position index. Its better to use the alternate way which I have given. – Arshad May 11 '18 at 07:17
  • i am using now alternative suggestion list i declare this list in adapter class and i put ArrayAdapter like that and i written into oncreate JSONArray jsonArray = new JSONArray(); for (int i = 0; i < jsonArray.length(); i++) { try { String obj = jsonArray.getString(i); } catch (JSONException e) { e.printStackTrace(); } } – gourav manuja May 11 '18 at 07:24
  • if you are using alternate way. you will not need jsonArray. you can directly pass the DataClass list which i have shown in above code. – Arshad May 11 '18 at 07:25
  • if you are converting DataClass to JsonArray it will be a bit different then my sample JsonArray creating code – Arshad May 11 '18 at 07:26
  • @gouravmanuja check my updated answer on building JsonArray with DataClass type structure – Arshad May 11 '18 at 07:33
  • actually i am new in android so that's why now am going confuse because you declare list 3 times in actual i just want to show data in listview using JSONArray but now m going confuse that how should i declare list please let me clear. what should i do. and i am using when data.add(d1) then there showing cannot resolve symbol so let me clear which list should i declare and at where because i am working first time like this. – gourav manuja May 11 '18 at 07:49
  • Anyone will be fine. Can you show your code where you are creating the list and how you are accessing it in your adapter – Arshad May 11 '18 at 10:18
  • its done thnku but same showing at that time reason of behind this,u put same name in obj look at your code obj1 obj1 obj1 otherwise everything is good thanku sir. – gourav manuja May 11 '18 at 11:33
  • @gouravmanuja cool....and my bad for the typo. If I helped marked my answer as correct also. Thankx – Arshad May 11 '18 at 11:36
0

You can directly pass your ArrayList to your adapter constructor and access it there.

Here is an example.

public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.ViewHolder> {

private Context context;
private ArrayList<String> coinslist;
private ArrayList<String> bell;

 //Constructor
public MyCustomAdapter(Activity context, ArrayList<String> coinslist, ArrayList<String> bell) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.coinslist = coinslist;
    this.bell = bell;
    this.activity = context;
}
}

First you declare your arraylist in the beginning of you jave class. I will declare 2 arraylists as a reference.

private ArrayList<String> coinslist;
private ArrayList<String> bell;

Then when you get the data in JSONArray, you parse it like this.

           //Get the Json array from the object.
            JSONArray my_array = json_object.getJSONArray("my_array");

            //If there is at least one item in the array then loop through the array
            //and get the individual item details.
            if (my_array.length() > 0) {

                coinslist = new ArrayList<String>();
                bell = new ArrayList<String>();
                for (int i = 0; i < my_array.length(); i++) {

                    //Get all the strings.
                    String coin_name = my_array.getJSONObject(i).getString("coin_name");
                    String bell_name = my_array.getJSONObject(i).getString("bell_name");

                       coinslist.add(coin_name);
                       bell.add(bell_name);
                         }
                      }

Now in your java class where you are setting the adapter, you can initialize the adapter and simply set the adapter on your list/recycler view.

 // Initialize the custom recycler adapter.
                my_custom_adapter = new MyCustomAdapter(getActivity(), coinslist, bell);

                // Set the adapter on my list view.
                my_list_view.setAdapter(my_custom_adapter);

Here instead of my list, you can pass your coinslist, val etc.

mxs2649
  • 71
  • 2
  • 7
  • i know i can do directly pass and i have already done this but i want to show my data using jsonArray,like whenever we fetch data from server using jsonArray but now i want to fetch data from my mainactivity class in jsonarray. – gourav manuja May 11 '18 at 06:48
  • Well, any specific reason for using only JSONArray ?? you can create an array list by parsing your json array and pass that instead since it works efficiently with list adapters. – mxs2649 May 11 '18 at 07:27
  • yeah specific reason that is now i am parsing data direct but i will work from server so at that time will be ease for me to access data from server and will no need to more change in my code. – gourav manuja May 11 '18 at 07:53
  • Ok but it is better for you to declare an arraylist and add json array data to that and use it with adapter. Declare an empty arraylist, Loop through your json array and add values to your arraylist and pass that. It is pretty simple. – mxs2649 May 11 '18 at 08:55
  • Check my updated answer. I have updated the code. Json_object is the object you get from server and my_Array is the array name you have in that object. – mxs2649 May 11 '18 at 10:32