解析的JSON数据将在另一个CLass中使用?

时间:2017-03-08 04:34:19

标签: android json class parsing

我能够解析JSON数据并在导航抽屉Header中设置Name。我在登录java类(即家庭类)后解析了Home Activity上的数据。我在Navigation抽屉上有片段,当我点击配置文件片段时,它应该从JSON填充名称,地址。如何在One类中使用解析的JSON数据。

Home.java

public class Home extends AppCompatActivity implements View.OnClickListener {


    LinearLayout calendar, classSchedule, progressReport, profile, fee, dshboard, setting, logout, attendance;
    android.support.v4.app.FragmentManager fragmentManager;
    public static final String Navigation_URL = "http://192.168.100.5:84/api/academics/students/";
    ImageView studentprofileimage;
    TextView profilename, sprofilename;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        studentprofileimage = (ImageView) findViewById(R.id.avatar);//initilise student name
        profilename = (TextView) findViewById(R.id.profilename);// student profile name
        sprofilename = (TextView) findViewById(R.id.student_profilename);


        dshboard = (LinearLayout) findViewById(R.id.dashboard_layout);
        calendar = (LinearLayout) findViewById(R.id.calender_layout);
        fee = (LinearLayout) findViewById(R.id.view_fee);
        classSchedule = (LinearLayout) findViewById(R.id.class_schedule);
        progressReport = (LinearLayout) findViewById(R.id.progress_report);
        profile = (LinearLayout) findViewById(R.id.view_profile);
        setting = (LinearLayout) findViewById(R.id.mainsetting);
        logout = (LinearLayout) findViewById(R.id.mainlogout);
        attendance = (LinearLayout) findViewById(R.id.class_attendance);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setVisibility(View.VISIBLE);

        calendar.setOnClickListener(this);
        classSchedule.setOnClickListener(this);
        fee.setOnClickListener(this);
        dshboard.setOnClickListener(this);
        progressReport.setOnClickListener(this);
        profile.setOnClickListener(this);
        setting.setOnClickListener(this);
        logout.setOnClickListener(this);
        attendance.setOnClickListener(this);
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.container, new Dashboard());
        tx.commit();

        SessionManagement session = new SessionManagement(Home.this);
        session.checkLogin();
        String master_id = session.getMasterId();
        Log.d("TAG", "master_id:" + master_id);
        makeJsonObjectRequest(Integer.parseInt(master_id));
        Log.d("TAG", "master_id:" + master_id);
        //master_id = session.clear();


    }

    StudentInformation studentInformation;

    public void makeJsonObjectRequest(int stud_id) {
        String URL = Navigation_URL + stud_id;
        Log.d("TAG", "URL:" + URL);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            studentInformation = new StudentInformation();
                            studentInformation.Name = jsonObject.getString("NAME");
                            profilename.setText(studentInformation.Name);
                            //       sprofilename.setText(studentInformation.Name);

                        } catch (JSONException e) {
                            Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }

                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(Home.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void onClick(View v) {

        int id = v.getId();


        if (id == R.id.dashboard_layout) {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new Dashboard())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);

        } else if (id == R.id.calender_layout) {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new CalenderFragment())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.view_fee) {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new Fee())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);

        } else if (id == R.id.class_schedule) {

            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new FragmentClassSchedule())
                    .commit();


            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.progress_report) {

            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new ProgressFragment())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.class_attendance) {

            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new AttendanceStudentFragment())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.view_profile) {

            Bundle bundle1 = new Bundle();
            bundle1.putSerializable("student_obj", studentInformation);


            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new ProfileFragment())
                    .commit();
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.mainsetting) {

            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new SettingFragment())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.mainlogout) {

            SessionManagement session = new SessionManagement(Home.this);
            session.clear();
            Intent intent = new Intent(Home.this, Login.class);
            startActivity(intent);
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new Dashboard())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);

        }


    }


}

StudentInformation.java

   public class StudentInformation implements Serializable {


    String PhoneNumber;
    String DOB;
    String ClassName;
    String Gender;
    public String Image;

    public Integer getStudentId() {
        return studentId;
    }

    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }

    public Integer studentId;

    public String getImage() {
        return Image;
    }

    public void setImage(String image) {
        Image = image;
    }

    public String Name;


    public String getName() {
        return Name;
    }

    public String getDOB() {
        return DOB;
    }


    public void setDOB(String DOB) {
        this.DOB = DOB;
    }

    public String getClassName() {
        return ClassName;
    }

    public void setClassName(String className) {
        ClassName = className;
    }

    public String getPhoneNumber() {
        return PhoneNumber;

    }

    public void setPhoneNumber(String phoneNumber) {
        PhoneNumber = phoneNumber;
    }

    public void setName(String name) {
        Name = name;

    }


    public String getGender() {
        return Gender;
    }

    public void setGender(String gender) {
        Gender = gender;
    }


}

ProfileFragment.java

  public class ProfileFragment extends Fragment {

    TextView profilename; // i want to set name on this textView


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.activity_profile, container, false);
        setHasOptionsMenu(true);
        profilename = (TextView) view.findViewById(R.id.student_profilename);
        //  StudentInformation studentInformation = null;
        // studentInformation = (StudentInformation) getActivity().getIntent().getSerializableExtra("");
        // profilename.setText(studentInformation.getName());


        if(this.getArguments().getSerializable("student_obj")!=null)
        {
            Serializable student_obj_serializable = getArguments().getSerializable("student_obj");
            StudentInformation student_obj=(StudentInformation)student_obj_serializable;

            //set all value here
            profilename.setText(student_obj.getName());
        }

        return view;
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.dashboard, menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do s.th.
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


}

我无法解析要在另一个类上使用的数据吗?

3 个答案:

答案 0 :(得分:1)

将所有数据保存在模型类中,并使用setArguments(bundle)将该模型类对象传递给片段

模特课程:

    public class StudentInformation  implements Serializable {


        private String PhoneNumber;
        private String DOB;
        private String ClassName;
        private String Gender;
        private String Image;


        public String getPhoneNumber() {
            return PhoneNumber;
        }

        public void setPhoneNumber(String phoneNumber) {
            PhoneNumber = phoneNumber;
        }

        public String getDOB() {
            return DOB;
        }

        public void setDOB(String DOB) {
            this.DOB = DOB;
        }

        public String getClassName() {
            return ClassName;
        }

        public void setClassName(String className) {
            ClassName = className;
        }

        public String getGender() {
            return Gender;
        }

        public void setGender(String gender) {
            Gender = gender;
        }

        public String getImage() {
            return Image;
        }

        public void setImage(String image) {
            Image = image;
        }
    }

makeJsonObjectRequest:

    //declare global

    StudentInformation studentInformation ;

    public void makeJsonObjectRequest(int stud_id) {
    String URL = Navigation_URL + stud_id;
    Log.d("TAG", "URL:" + URL);
    StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        studentInformation = new StudentInformation();
                       // studentInformation.Name = jsonObject.getString("NAME");

                         studentInformation.setName(jsonObject.getString("NAME"));

                        profilename.setText(studentInformation.getName());
                        //       sprofilename.setText(studentInformation.Name);

                        //parse all data here and set all info to studentInformation



                    } catch (JSONException e) {
                        Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }

                }

            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(Home.this, error.toString(), Toast.LENGTH_LONG).show();
                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

  }

在个人资料按钮上点击:

if (id == R.id.view_profile) {

        Bundle bundle1 = new Bundle();
        bundle1.putSerializable("student_obj", studentInformation);

        Fragment fragment = new ProfileFragment();
        fragment.setArguments(bundle1);
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container, fragment);
        fragmentTransaction.commit();

          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

    } 

ProfileFragment:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.activity_profile, container, false);
    setHasOptionsMenu(true);
    profilename = (TextView) view.findViewById(R.id.student_profilename);
    //  StudentInformation studentInformation = null;
    // studentInformation = (StudentInformation) getActivity().getIntent().getSerializableExtra("");
    // profilename.setText(studentInformation.getName());

    if(this.getArguments().getSerializable("student_obj")!=null)
    {
        Serializable student_obj_serializable = getArguments().getSerializable("student_obj");
       StudentInformation student_obj=(StudentInformation)student_obj_serializable;

       //set all value here
       profilename.setText(student_obj.getName());
    }

    return view;
}   

答案 1 :(得分:0)

如果要将Json数据从一个活动发送到另一个活动,则创建一个类并将其扩展为可序列化并在类中创建所有参数变量。 然后创建类的对象并将所有Json数据存储在对象中,如果有多个这样的对象要发送,那么创建你创建的类型类数组并通过Intent发送它。

答案 2 :(得分:0)

是的,您可以将数据存储到模型中并获取模型上的任何操作,您将获得错误的数据,因此在主要活动时将其存储在sql lite中,然后从导航抽屉获取数据