简体   繁体   中英

Displaying JSON Data Through fragment?

I was Given A Project as : please read it

SAMPLE JSON --

[ { "slot":"A" , "name":"Dummy Subject 1", "code":"SCD1", "class number":"12345", "total students": "67" }, { "slot":"B", "name":"Dummy Subject 2", "code":"SCD2", "class number":"12346", "total students": "29" }, { "slot":"C", "name":"Dummy Subject 3", "code":"SCD3", "class number":"12347", "total students": "41" }, { "slot":"D", "name":"Dummy Subject 4", "code":"SCD4", "class number":"12348", "total students": "65" }, { "slot":"E", "name":"Dummy Subject 5", "code":"SCD5", "class number":"12349", "total students": "55" } ]

Sample JSON data which has information of 5 Dummy subjects and information related to each subject. Download this JSON data, parse the information out from it and store in Shared Preferences, as per your wish. display in an ExpandableListView with name and code as head. On expanding , show other details of it.

what i was not able to do this for N no. of objects ...if there were n no. of objects in JSON data....Please help with this question also ...

so i did This project as per instructions but now i am given same project and do it in fragment as #list item should be name and code and data should be its data ...

here's my code via using activity ...please tell how to do same using fragment ..

# json_parse_class.java

        package com.office.tracker;
    // Nikhil Verma 13BCE0037 9787029484 L-217
    import java.io.IOException;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.Activity;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.Toast;

    public class json_dpa extends Activity {
        HttpClient client;
        JSONObject dummy1;
        SharedPreferences json_spref;;
        String[] datas = null;
        TextView tv;
        public static String s1="Default^Default^Default^Default^Default^Default^Default^Default^" +
                "Default^Default^Default^Default^Default^Default^Default^Default^" +
                "Default^Default^Default^Default^Default^Default^Default^Default^Default";
        private static final String SLOT = "slot";
        static final String NAME = "name";
        static final String CODE = "code";
        static final String ClASS_NUMBER = "cno.";
        static final String TOTAL_STUDENTS = "ts";
        static final String TOTAL = "t";
        SharedPreferences.Editor editor;
        public static int ob_counter = 0;
        public String deta[] = null;
        private static final String PREFS_NAME = "json_prefname";
        int count = 0;
        final static String URL = "http://www.gdgvitvellore.com/samplejson/";

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.json);
            client = new DefaultHttpClient();
            tv = (TextView) findViewById(R.id.json_id);
            json_spref = getSharedPreferences(PREFS_NAME, 0);
        //  this.ob_counter = counter;
        String[] index = { "slot", "name", "code", "class number",
                    "total students" };
            new getdata().execute(index);
        }

        public int  async(int counter) 
        {
        this.ob_counter = counter;
        return 0;
        }

        public JSONObject gdg(int r) throws ClientProtocolException, IOException,
                JSONException {
    ob_counter=r;
            HttpGet get = new HttpGet(URL);
            HttpResponse rtr = client.execute(get);
            int status = rtr.getStatusLine().getStatusCode();
            if (status == 200) {
                HttpEntity e = rtr.getEntity();
                String data = EntityUtils.toString(e);
                JSONArray detail = new JSONArray(data);
                JSONObject dummy = detail.getJSONObject(ob_counter);
                return dummy;
            } else {
                Toast.makeText(json_dpa.this, "Error ", Toast.LENGTH_LONG);
                return null;
            }
        }

        public class getdata extends AsyncTask<String, Integer, String> {

            protected String doInBackground(String... params) {
                try {

                    dummy1 = gdg(0);
                    String mystr1 = dummy1.getString(params[0]);
                    String mystr2 = dummy1.getString(params[1]);
                    String mystr3 = dummy1.getString(params[2]);
                    String mystr4 = dummy1.getString(params[3]);
                    String mystr5 = dummy1.getString(params[4]);
                    dummy1=null;
                    dummy1 = gdg(1);
                    String mystr6 = dummy1.getString(params[0]);
                    String mystr7 = dummy1.getString(params[1]);
                    String mystr8 = dummy1.getString(params[2]);
                    String mystr9 = dummy1.getString(params[3]);
                    String mystr10 = dummy1.getString(params[4]);
                    dummy1=null;
                    dummy1 = gdg(2);
                    String mystr11 = dummy1.getString(params[0]);
                    String mystr12 = dummy1.getString(params[1]);
                    String mystr13 = dummy1.getString(params[2]);
                    String mystr14 = dummy1.getString(params[3]);
                    String mystr15 = dummy1.getString(params[4]);
                    dummy1=null;
                    dummy1 = gdg(3);
                    String mystr16 = dummy1.getString(params[0]);
                    String mystr17 = dummy1.getString(params[1]);
                    String mystr18 = dummy1.getString(params[2]);
                    String mystr19 = dummy1.getString(params[3]);
                    String mystr20 = dummy1.getString(params[4]);
                    dummy1=null;
                    dummy1 = gdg(4);
                    String mystr21 = dummy1.getString(params[0]);
                    String mystr22 = dummy1.getString(params[1]);
                    String mystr23 = dummy1.getString(params[2]);
                    String mystr24 = dummy1.getString(params[3]);
                    String mystr25 = dummy1.getString(params[4]);
                    editor = json_spref.edit();
                    editor.putString(SLOT, mystr1);
                    editor.putString(NAME, mystr2);
                    editor.putString(CODE, mystr3);
                    editor.putString(ClASS_NUMBER, mystr4);
                    editor.putString(TOTAL_STUDENTS, mystr5);
                    editor.putString(TOTAL, mystr1+"^"+mystr2+"^"+mystr3+"^"+mystr4+"^"+mystr5+"^"+mystr6+"^"+mystr7
                            +"^"+mystr8+"^"+mystr9+"^"+mystr10+"^"+mystr11+"^"+mystr12+"^"+mystr13+"^"+mystr14+"^"+mystr15
                            +"^"+mystr16+"^"+mystr17+"^"+mystr18+"^"+mystr19+"^"+mystr20+"^"+mystr21+"^"+mystr22
                            +"^"+mystr23+"^"+mystr24+"^"+mystr25);
                    editor.commit();
                    return mystr1;
                } catch (ClientProtocolException e) {

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

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

                    e.printStackTrace();
                }

                return null;
            }

            protected void onPostExecute(String result) {
                s1 = json_spref.getString(TOTAL, "defaut Slot");
                tv.setText(s1);

            }

        }

    }

list_main class.java

          package com.office.tracker;

      import android.app.Activity;
      import android.content.Intent;
      import android.os.Bundle;
      import android.view.Menu;
      import android.view.MenuInflater;
      import android.view.MenuItem;
      import android.view.View;
      import android.view.Window;
      import android.view.WindowManager;
      import android.view.View.OnClickListener;
      import android.widget.Button;
      import android.widget.ExpandableListView;

      public class json_list_main extends Activity implements OnClickListener
      { // Nikhil Verma 13BCE0037 9787029484 L-217
          ExpandableListView elv;
          Button but;

          protected void onCreate(Bundle savedInstanceState) {

              super.onCreate(savedInstanceState);
              requestWindowFeature(Window.FEATURE_NO_TITLE);
              getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
              setContentView(R.layout.json_exp_list);
              elv=(ExpandableListView) findViewById(R.id.json_exp_listID);
              but=(Button) findViewById(R.id.list_button);
              but.setOnClickListener(this);
              //json_dpa ob=new json_dpa();
              //ob.async(0);

              //String s1=ob.json_spref.getString(ob.NAME, "defaut Slot");
              elv.setAdapter(new json_exp_list_view(this));
          }

          public boolean onCreateOptionsMenu(Menu menu) {
              // TODO Auto-generated method stub
              super.onCreateOptionsMenu(menu);
              MenuInflater mf = getMenuInflater();
              mf.inflate(R.menu.cool_menu, menu);
              return true;
          }

          @Override
          public boolean onOptionsItemSelected(MenuItem item) {
              // TODO Auto-generated method stub
              switch (item.getItemId()) {
              case R.id.aboutus:
                  Intent rob = new Intent("com.office.tracker.ABOUTUS");
                  startActivity(rob);

                  break;
          //    case R.id.preferences:
                  //Intent roby = new Intent("com.office.tracker.PREFS");
                  //startActivity(roby);
                  //break;
              case R.id.exit:
                  finish();
                  break;
              }
              return false;
          }

          public void onClick(View v) {
              if(v.getId()==R.id.list_button){
                  Intent rob = new Intent("com.office.tracker.JSON_DPA");
                  startActivity(rob);

              }

          }

      }




custom adapter class.java




        package com.office.tracker;

    import android.content.Context;
    import android.graphics.Color;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseExpandableListAdapter;
    import android.widget.TextView;

        public class json_exp_list_view extends BaseExpandableListAdapter {
        private Context context;
        int i=0;
        json_dpa ob=new json_dpa();
        String ret=ob.s1;
        String i1="Slot -";
        String i2="Name -";
        String i3="Code -";
        String i4="Class No. -";
        String i5="Total Students -";

        String[] splitArray = ret.split("\\^");//split whenever at least one whitespace is encountered


        //String s1=ob.json_spref.getString(ob.NAME, "defaut Slot");
        //json_dpa ob=new json_dpa();
        //String name1=ob.name_ret();
        //String code1=ob.code_ret();
        String[] parent={i2+splitArray[1]+" , "+i3+splitArray[2],i2+splitArray[6]+" , "+i3+splitArray[7],i2+splitArray[11]+" , "+i3+splitArray[12]
                ,i2+splitArray[16]+" , "+i3+splitArray[17],i2+splitArray[21]+" , "+i3+splitArray[22]};
        String[][] child={{i1+splitArray[0],i4+splitArray[3],splitArray[4]},
                {i1+splitArray[5],i4+splitArray[8],i5+splitArray[9]}
        ,{i1+splitArray[10],i4+splitArray[13],i5+splitArray[14]},
        {i1+splitArray[15],i4+splitArray[18],i5+splitArray[19]},
        {i1+splitArray[20],i4+splitArray[23],i5+splitArray[24]}};
        public json_exp_list_view(Context context) {
            this.context=context;
        }

        @Override
        public Object getChild(int arg0, int arg1) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getChildId(int arg0, int arg1) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getChildView(int GroupPosition, int ChildPosition, boolean arg2, View arg3,
                ViewGroup arg4) {
            TextView tv=new TextView(context);
            tv.setText(child[GroupPosition][ChildPosition]);
            tv.setPadding(90, 15, 15, 15);
            tv.setTextSize(25);
            tv.setTextColor(Color.BLUE);
            return tv;
        }

        @Override
        public int getChildrenCount(int GroupPosition) {
            // TODO Auto-generated method stub
            return child[GroupPosition].length;
        }

        @Override
        public Object getGroup(int GroupPosition) {
            // TODO Auto-generated method stub
            return GroupPosition;
        }

        @Override
        public int getGroupCount() {
            // TODO Auto-generated method stub
            return parent.length;
        }

        @Override
        public long getGroupId(int GroupPosition) {
            // TODO Auto-generated method stub
            return GroupPosition;
        }

        @Override
        public View getGroupView(int GroupPosition, boolean arg1, View arg2, ViewGroup arg3) {

            TextView tv=new TextView(context);
            tv.setText(parent[GroupPosition]);
            tv.setPadding(110, 15, 15, 15);
            tv.setTextSize(27);
            tv.setTextColor(Color.GREEN);
            return tv;
        }

        @Override
        public boolean hasStableIds() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean isChildSelectable(int arg0, int arg1) {
            // TODO Auto-generated method stub
            return true;
        }

    }

To covert your JSON string to an object you need to do the following:

Go to the following link and download GSON: https://code.google.com/p/google-gson/downloads/detail?name=google-gson-1.5-release.zip&can=4&q=

Copy it in the your project

Create class that represents List of subjects

Than where you need to convert JSON to list of subjects do the following in code:

//import the packeges

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tekpub.models.Production;

//type of objct we need to convert JSON string to
Type typeOfDest = new TypeToken<List<Subjects>>(){}.getType();

Gson gson = new Gson(); 
//return the object     
return gson.fromJson(input, typeOfDest); 

Have a look at GSON , a library to easily parse JSON data to/for object. You can even parameters it

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