2

I am trying to make list view in android .I am able to make simple list view using static data .Now I take json file in asset folder . Then I read contend from json file and display on list view .It is working fine.

I do like this

public class MainActivity extends Activity {
    ListView listView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);

        Log.d("==", loadJSONFromAsset());
        String arr[];
        try {
            JSONArray js = new JSONArray(loadJSONFromAsset());
            arr = new String[js.length()];
            for (int i = 0; i < js.length(); i++) {
                JSONObject obj = js.getJSONObject(i);
                arr[i] = obj.getString("name");
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arr);
            listView.setAdapter(adapter);

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

    public String loadJSONFromAsset() {
        String json = null;
        try {

            InputStream is = getAssets().open("data.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }


}

It is working fine But I need to do different task .I need to read json file from asset folder . and create as same number of column as in json array

This is new json file

{"coulmns":[
  {
    "name": "Test_1"
  },
  {
    "name": "Test_2"
  },
  {
    "name": "Test_3"
  },
  {
    "name": "Test_4"
  }
]}

I need to create four column of equal width (because there is four object).If it is three than it show three column of equal width .can we do in android ?

any idea..?

how to do with grid view ?

user944513
  • 12,247
  • 49
  • 168
  • 318

2 Answers2

0

A GridView is a specific type of ListView that is designed to put your list into multiple columns, or a grid. It's just as easy to use as a ListView, except that you need to specify the number of columns you have. Try this:

  1. Replace the instance of ListView in your XML file with GridView
  2. Replace the ListView in your activity with GridView
  3. Set the number of columns you want. You can make this dynamic by changing it depending on your data.

public class MainActivity extends Activity { GridView gridView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    gridView = (ListView) findViewById(R.id.grid_view);

    Log.d("==", loadJSONFromAsset());
    String arr[];
    try {
        JSONArray js = new JSONArray(loadJSONFromAsset());
        arr = new String[js.length()];
        for (int i = 0; i < js.length(); i++) {
            JSONObject obj = js.getJSONObject(i);
            arr[i] = obj.getString("name");
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arr);
        gridView.setAdapter(adapter);
        gridview.setNumColumns(4);
        //You can replace 4 with a formula if you want it to be variable

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

Also see: http://developer.android.com/reference/android/widget/GridView.html

Scott
  • 3,663
  • 8
  • 33
  • 56
  • Thanks for answering ..let supose this answer work ..you set number of columns is 4 which is coming from data ..how to create text view 4 to set the value .if it is 3 column than how to set three text view to set the value of text view – user944513 Aug 15 '15 at 13:15
  • In your code, I don't know where to see how many columns you want... Actually, looking at your question it seems like you don't want columns so much as you want a horizontal ListView. That's possible to accomplish with a RecyclerView, but it's much more complicated and I don't think it's a design pattern that's recommended. However see this answer (http://stackoverflow.com/questions/3240331/horizontal-listview-in-android) or look up horizontal ListView if that's the direction you want to go. – Scott Aug 15 '15 at 13:39
0

Straight out of the box, the ArrayAdapter<MyObject> is going to populate only a TextView with values as defined by myObject.toString(). If you need a mode complex list item view you have to create your own adapter that extends ArrayAdapter and override getView(...).

For example, your adapter creation would be:

MyArrayAdapter adapter = new MyArrayAdapter(this,R.layout.my_list_item,arr);

I defined MyObject inside the adapter, but it could anywhere. The idea is that MyObject will consist of the texts from one "row" (all the column values)

A very raw version of your adapter could be:

public class MyArrayAdapter extends ArrayAdapter<MyArrayAdapter.MyObject> {

    public MyArrayAdapter(Context context, int resource, ArrayList<MyObject> objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null)
        {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
            viewHolder = new ViewHolder();
            for (int i= 0; i < MyObject.MAX_COLUMNS; i++)
                viewHolder.mTextViews[i] = (TextView)((ViewGroup)convertView).getChildAt(i);
            convertView.setTag(viewHolder);
        }
        else
        {
            viewHolder = (ViewHolder)convertView.getTag();
        }

        MyObject myObject = getItem(position);
        for (int i = 0; i < myObject.myTexts.length; i++)
        {
            viewHolder.mTextViews[i].setVisibility(View.VISIBLE);
            viewHolder.mTextViews[i].setText(myObject.myTexts[i]);
        }
        for (int i = myObject.myTexts.length; i < MyObject.MAX_COLUMNS; i++)
            viewHolder.mTextViews[i].setVisibility(View.GONE);

        return convertView;
    }

    private static class ViewHolder {
        public TextView[] mTextViews = new TextView[MyObject.MAX_COLUMNS];
    }


    public static class MyObject {
        public static int MAX_COLUMNS = 4;
        public MyObject(String[] texts) {
            myTexts =  texts;
        }
        public String[] myTexts;
    }
}

And your item layout (with four TextViews, but add/remove if your max columns is different):

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
</LinearLayout>

In case you don't have a way to know the max number of your columns, you have to construct the item layout dynamically instead of inflating it from a resource and more importantly the ViewHolder pattern is pretty much useless.

N.T.
  • 2,601
  • 1
  • 14
  • 20