简体   繁体   中英

How to parse json from a local json file into a ListView in android?

I am creating an application which uses a local json file for displaying some information.So i parsed the data and a text view which displays the data.But what i actually want is that the parsed data has to be displayed in a Listview . How to do this ?

This is my code.

        // Reading text file from assets folder
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(getAssets().open(
                    "jsonshoutdata.txt")));
            String temp;
            while ((temp = br.readLine()) != null)
                sb.append(temp);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close(); // stop reading
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        myjsonstring = sb.toString();
        // Try to parse JSON
        try {
             urlist = new ArrayList<HashMap<String, String>>();
                  // Creating JSONObject from String
            JSONObject jsonObjMain = new JSONObject(myjsonstring);

            // Creating JSONArray from JSONObject
            JSONArray jsonArray = jsonObjMain.getJSONArray("message");

            // JSONArray has four JSONObject
            for (int i = 0; i < jsonArray.length(); i++) {

                // Creating JSONObject from JSONArray
                JSONObject jsonObj = jsonArray.getJSONObject(i);

                // Getting data from individual JSONObject
                String message = jsonObj.getString("msg");

                 HashMap<String, String> map = new HashMap<String, String>();

                map.put("msg", msg );

                urlist.add(map);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

This is my customList adapter

CustomList adapter = new CustomList(MainActivity.this,urlist);
        list=(ListView)findViewById(R.id.list);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        {

             @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();

                    }
                });

This is my adapter class

public class CustomList extends ArrayAdapter<String>
{
    public final ArrayList<HashMap<String, String>> urlist;
    private Activity context;

    public CustomList(Activity context,ArrayList<HashMap<String, String>> urlist) 
    {
        super(context, R.layout.list_single);
        this.context = context;
        this.urlist=urlist;

    }
    @Override
    public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView= inflater.inflate(R.layout.list_single, null, true);

    TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
    txtTitle.setText((CharSequence) urlist);
    return rowView;

}
}

create a customList class (dont use hashmap)

change your custom list code (this is your code)

public class CustomList extends ArrayAdapter<String>
{
public final ArrayList<HashMap<String, String>> urlist;
private Activity context;

public CustomList(Activity context,ArrayList<HashMap<String, String>> urlist) 
{
    super(context, R.layout.list_single);
    this.context = context;
    this.urlist=urlist;

}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);

TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText((CharSequence) urlist);
return rowView;

 }
 }

to

public class customList extends ArrayAdapter<String>{

Context context; 
int layoutResourceId;    
ArrayList<String> data = null;

public customList(Context context, int layoutResourceId, ArrayList<String> data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    CustomHolder holder = null;

    if(row == null)
    {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);

        holder = new CustomHolder();
        holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);

        row.setTag(holder);
    }
    else
    {
        holder = (CustomHolder)row.getTag();
    }

    String s = data.get(postition);
    holder.txtTitle.setText(s);

    return row;
}

static class CustomHolder
{
    TextView txtTitle;
}
}

and change your json parsing code and parse your json like

 // JSONArray has four JSONObject

     ArrayList<String> messages = new ArrayList<String>();
        for (int i = 0; i < jsonArray.length(); i++) {

            // Creating JSONObject from JSONArray
            JSONObject jsonObj = jsonArray.getJSONObject(i);

            // Getting data from individual JSONObject
            String message = jsonObj.getString("msg");
            messages.add(message);

        }

and finally replace your this code

CustomList adapter = new CustomList(MainActivity.this,urlist);
    list=(ListView)findViewById(R.id.list);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() 
    {

         @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();

                }
            });

with this one

customList adapter = new customList(MainActivity.this,R.layout.list_single,messages);  //messagses is your arraylist in which you added string by parsing your json (see before this code mean upward)
    list=(ListView)findViewById(R.id.list);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() 
    {

         @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();

                }
            });

Solution 2

since you are showing only single text , you dont need to create your own custom adapter instead you can simply do.

 ArrayList<String> messages = new ArrayList<String>();
        for (int i = 0; i < jsonArray.length(); i++) {

            // Creating JSONObject from JSONArray
            JSONObject jsonObj = jsonArray.getJSONObject(i);

            // Getting data from individual JSONObject
            String message = jsonObj.getString("msg");
            messages.add(message);

        }

  ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1, messages);
  list=(ListView)findViewById(R.id.list);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() 
    {

         @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    Toast.makeText(MainActivity.this, "TEST.........", Toast.LENGTH_SHORT).show();

                }
            });

Use this .

 try {
        urlist = new ArrayList<HashMap<String, String>>();
        JSONObject jsonObjMain = new JSONObject(myjsonstring);

        // Creating JSONArray from JSONObject
        JSONArray jsonArray = jsonObjMain.getJSONArray("message");

        // JSONArray has four JSONObject
        for (int i = 0; i < jsonArray.length(); i++) {

            // Creating JSONObject from JSONArray
            JSONObject jsonObj = jsonArray.getJSONObject(i);

            // Getting data from individual JSONObject
            String message = jsonObj.getString("msg");

            HashMap<String, String> map = new HashMap<String, String>();

            map.put("msg", message );

            urlist.add(map);

        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Here globally declare before onCreate()

  ArrayList<HashMap<String, String>> urlist;

Now you have to pass urList arraylist to your CustomAdapter of your ListView as a parameter and after that set that adapter to your ListView .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM