ir.isilearning.lmsapp.fragment.CategorySelectionFragment.java Source code

Java tutorial

Introduction

Here is the source code for ir.isilearning.lmsapp.fragment.CategorySelectionFragment.java

Source

/*
 * Copyright 2015 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ir.isilearning.lmsapp.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ir.isilearning.lmsapp.R;
import ir.isilearning.lmsapp.activity.QuizActivity;
import ir.isilearning.lmsapp.activity.SignInActivity;
import ir.isilearning.lmsapp.adapter.CategoryAdapter;
import ir.isilearning.lmsapp.helper.ConnectionHelper;
import ir.isilearning.lmsapp.helper.PreferencesHelper;
import ir.isilearning.lmsapp.helper.TransitionHelper;
import ir.isilearning.lmsapp.model.Category;
import ir.isilearning.lmsapp.model.JsonAttributes;
import ir.isilearning.lmsapp.webservice.UserUtils;
import ir.isilearning.lmsapp.webservice.caller.GetUserExamsCaller;
import ir.isilearning.lmsapp.webservice.caller.SetActiveExamCaller;
import ir.isilearning.lmsapp.webservice.gmodel.gLogin;
import ir.isilearning.lmsapp.webservice.gmodel.gUserExamDetail;
import ir.isilearning.lmsapp.widget.OffsetDecoration;

public class CategorySelectionFragment extends Fragment {

    private static final int REQUEST_CATEGORY = 0x2300;
    public static String strSetActiveExamCaller = "";
    public static gUserExamDetail[] gUserExamDetails;
    private CategoryAdapter mAdapter;
    private Boolean ERR = false;

    public static CategorySelectionFragment newInstance() {
        return new CategorySelectionFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.activity_category_selection, container, false);
        final SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.contentView);
        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    setUpQuizGrid((RecyclerView) view.findViewById(R.id.categories));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        return inflater.inflate(R.layout.fragment_categories, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        try {
            setUpQuizGrid((RecyclerView) view.findViewById(R.id.categories));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        super.onViewCreated(view, savedInstanceState);
    }

    private void setUpQuizGrid(RecyclerView categoriesView) throws InterruptedException {
        final int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_nano);
        categoriesView.addItemDecoration(new OffsetDecoration(spacing));
        Context context = getActivity().getApplicationContext();
        gLogin logStatus = UserUtils.CheckUserStatus(context);
        ///////////////
        if (ConnectionHelper.hasActiveInternetConnection(context)) {

            if (logStatus.getStatusID() == 1) {
                //GET USER EXAMS CALLER
                try {
                    GetUserExamsCaller getUserExamsCaller = new GetUserExamsCaller(
                            getActivity().getApplicationContext());
                    getUserExamsCaller.setGetUserExamsCaller("START");
                    getUserExamsCaller.join();
                    getUserExamsCaller.start();
                    try {
                        while (getUserExamsCaller.getGetUserExamsCaller().equals("START")) {
                            Thread.sleep(15);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //                    if (!getUserExamsCaller.getRESULT().equals( "ERROR" )) {
                    gUserExamDetails = getUserExamsCaller.getUserExamDetailList();
                    //                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setTitle("");
                alertDialog.setMessage(logStatus.getStatusMessage());
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
            }
        } else {
            AlertDialog alertDialog = new AlertDialog.Builder(context).create();
            alertDialog.setTitle("");
            alertDialog.setMessage("    ");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        }
        //////////////////////

        List<gUserExamDetail> userExamDetailList = null; //// fill thissssss ......
        try {
            if (gUserExamDetails != null) {
                userExamDetailList = new ArrayList<>(Arrays.asList(gUserExamDetails));
            }
        } catch (Exception e) {
            Intent myIntent = new Intent(getActivity(), SignInActivity.class);
            getActivity().startActivity(myIntent);
            PreferencesHelper.signOut(getContext());
            ERR = Boolean.TRUE;
        }
        //something else
        if (!ERR && gUserExamDetails != null) {
            mAdapter = new CategoryAdapter(getActivity(), userExamDetailList);
            mAdapter.setOnItemClickListener(new CategoryAdapter.OnItemClickListener() {
                @Override
                public void onClick(View v, int position) {
                    Activity activity = getActivity();
                    startQuizActivityWithTransition(activity, v.findViewById(R.id.category_title),
                            mAdapter.getItem(position));
                    try {
                        mrSetActiveExam(Integer.parseInt(mAdapter.getItem(position).getId()));
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            });

            categoriesView.setAdapter(mAdapter);
        }
        ERR = false;
    }

    private void mrSetActiveExam(int examID) {
        Context context = getActivity().getApplicationContext();
        gLogin logStatus = null;
        try {
            logStatus = UserUtils.CheckUserStatus(context);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ///////////////
        if (ConnectionHelper.hasActiveInternetConnection(context)) {
            if (logStatus != null) {
                if (logStatus.getStatusID() == 1) {
                    try {
                        SetActiveExamCaller setActiveExamCaller = new SetActiveExamCaller(
                                getActivity().getApplicationContext());
                        setActiveExamCaller.setExamID(examID);
                        strSetActiveExamCaller = "START";
                        setActiveExamCaller.join();
                        setActiveExamCaller.start();
                        while (strSetActiveExamCaller.equals("START")) {
                            try {
                                Thread.sleep(15);
                            } catch (Exception ignored) {
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(context, logStatus.getStatusID() + ":" + logStatus.getStatusMessage(),
                            Toast.LENGTH_LONG).show();
                }
            }
        } else {
            AlertDialog alertDialog = new AlertDialog.Builder(context).create();
            alertDialog.setTitle("");
            alertDialog.setMessage("    ");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        }
        //////////////////////
    }

    @Override
    public void onResume() {
        getActivity().supportStartPostponedEnterTransition();
        super.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CATEGORY && resultCode == R.id.solved) {
            mAdapter.notifyItemChanged(data.getStringExtra(JsonAttributes.ID));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void startQuizActivityWithTransition(Activity activity, View toolbar, Category category) {

        final Pair[] pairs = TransitionHelper.createSafeTransitionParticipants(activity, false,
                new Pair<>(toolbar, activity.getString(R.string.transition_toolbar)));
        @SuppressWarnings("unchecked")
        ActivityOptionsCompat sceneTransitionAnimation = ActivityOptionsCompat
                .makeSceneTransitionAnimation(activity, pairs);

        // Start the activity with the participants, animating from one to the other.
        final Bundle transitionBundle = sceneTransitionAnimation.toBundle();
        Intent startIntent = QuizActivity.getStartIntent(activity, category, mAdapter);
        ActivityCompat.startActivityForResult(activity, startIntent, REQUEST_CATEGORY, transitionBundle);
    }

}