com.devgmail.mitroshin.totutu.controllers.ListFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.devgmail.mitroshin.totutu.controllers.ListFragment.java

Source

package com.devgmail.mitroshin.totutu.controllers;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;

import com.devgmail.mitroshin.totutu.R;
import com.devgmail.mitroshin.totutu.model.Station;
import com.devgmail.mitroshin.totutu.util.DatabaseHelper;
import com.devgmail.mitroshin.totutu.util.StationCursorAdapter;

import static com.devgmail.mitroshin.totutu.hosts.ListActivity.EXTRA_DIRECTION_TYPE;

/**
 Copyright 2017 Mitroshin Dmitry (mitroshin.develop@gmail.com)
    
 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.
 */

// ? ?? fragment_list.xml

public class ListFragment extends Fragment implements AdapterView.OnItemClickListener {

    private ListView mListView;
    private DatabaseHelper mDatabaseHelper;
    private Cursor mCursor;

    //     ?
    private EditText mSearchEditText;

    //    ? 
    private StationCursorAdapter stationsCursorAdapter;

    //       ?? ?
    private String mDirectionType;

    //        ? ??,  ???  .

    private static Station mStation;
    //      ?  ,     .
    private Cursor mStationCursor;
    private Cursor mCityCursor;

    //      ?     ?  ? .
    private Long mCityId;

    //     ?  ?
    public static final String EXTRA_REQUEST_STATION_OBJECT = "com.devgmail.mitroshin.totutu."
            + "extra_request_station_object";
    //     ?  ?
    public static final String EXTRA_REQUEST_DIRECTION_TYPE = "com.devgmail.mitroshin.totutu."
            + "extra_request_direction_type";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDatabaseHelper = new DatabaseHelper(getActivity().getApplicationContext());
        mDatabaseHelper.open();
    }

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

        View view = inflater.inflate(R.layout.fragment_list, container, false);

        mListView = (ListView) view.findViewById(R.id.list_list_view);
        mListView.setOnItemClickListener(this);

        mSearchEditText = (EditText) view.findViewById(R.id.list_edit_search);

        //          ??    ?    ,   ??
        //          . ? ? ?  ?? ?  
        mDirectionType = (String) getActivity().getIntent().getSerializableExtra(EXTRA_DIRECTION_TYPE);

        //         ? ?    ? ?  ? ??  
        //         ,   ?? ? ?   
        //         ?  ? Info.
        mCursor = mDatabaseHelper.database.rawQuery(generateDefaultQuery(mDirectionType), null);

        //          ? ?  ?  .
        //         ? ?  ,   ?   ??.
        stationsCursorAdapter = new StationCursorAdapter(getActivity().getApplicationContext(), mCursor);

        if (!mSearchEditText.getText().toString().isEmpty()) {
            stationsCursorAdapter.getFilter().filter(mSearchEditText.getText().toString());
        }

        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            //   ?   ,  ??? ?
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                System.out.println("    *** Text Change *** ");
                stationsCursorAdapter.getFilter().filter(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        stationsCursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            @Override
            public Cursor runQuery(CharSequence constraint) {

                System.out.println("    *** Run Query *** ");

                if (constraint == null || constraint.length() == 0) {

                    System.out.println("    *** Constraint == null || or length == 0 *** ");

                    return mDatabaseHelper.database.rawQuery(generateDefaultQuery(mDirectionType), null);
                } else {

                    System.out.println("    *** Constraint != null *** ");

                    return mDatabaseHelper.database.rawQuery(generateSearchQuery(mDirectionType),
                            new String[] { "%" + constraint.toString() + "%" });
                }
            }
        });

        mListView.setAdapter(stationsCursorAdapter);

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mDatabaseHelper.database.close();
        mCursor.close();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long stationId) {

        //         ?  ?  mStation  ????   ?,
        //            ?? ??   ?.
        //         ?   ??? ?
        createModelByStationId(stationId);

        //        ??  ? ? :
        //        *    Back - RESULT_CANCELED
        //        *   ? ?? - RESULT_OK
        //        ?   ,   ? ? ?  ?,
        //            ? ?  ? ?  .
        Intent data = new Intent();
        data.putExtra(EXTRA_REQUEST_STATION_OBJECT, mStation);
        data.putExtra(EXTRA_REQUEST_DIRECTION_TYPE, mDirectionType);
        getActivity().setResult(Activity.RESULT_OK, data);
        getActivity().finish();
    }

    //    ?    ? ???? ? ? ListActivity   .
    //    .. ?? ?        
    //    ?  ,    ? ? ? ?  .
    //    ? ?? ?, ?    ?  ,
    //     ??  ?  .
    //    ? ?  ? ?  
    public static Station resultStationObject(Intent result) {
        return result.getParcelableExtra(EXTRA_REQUEST_STATION_OBJECT);
    }

    public static String resultDirectionType(Intent result) {
        return result.getStringExtra(EXTRA_REQUEST_DIRECTION_TYPE);
    }

    //           ??   ??  ,  ??   ?
    //         ??  ?? ? ? ??   .
    //              ,    ?? ,  
    //         ?? ?.  ?? City  ??   ?.
    public void createModelByStationId(Long stationId) {

        mStationCursor = mDatabaseHelper.database.rawQuery("SELECT * FROM " + mDatabaseHelper.STATIONS_TABLE
                + " WHERE " + mDatabaseHelper.STATION_ID + " = '" + stationId + "'", null);
        mStationCursor.moveToFirst();

        mCityId = mStationCursor.getLong(mStationCursor.getColumnIndexOrThrow(mDatabaseHelper.STATION_CITY_ID));

        mCityCursor = mDatabaseHelper.database.rawQuery("SELECT * FROM " + mDatabaseHelper.CITIES_TABLE + " WHERE "
                + mDatabaseHelper.CITY_CITY_ID + " = '" + mCityId + "'", null);

        mCityCursor.moveToFirst();

        //         ?   ? City  Station ?? ?  
        //         ?   ,   ? ?? ?
        mStation = new Station(mStationCursor, mCityCursor);
    }

    //    ?  ? ?
    private String generateDefaultQuery(String directionType) {
        return firstPartOfQuery(directionType) + secondPartOfQuerty();
    }

    //     ?  ,    ? ? ,  ? ?.
    //      ?     ? - ?  ? ? ?
    private String generateSearchQuery(String directionType) {
        return firstPartOfQuery(directionType) + searchPartOfQuery() + secondPartOfQuerty();
    }

    //    ? ? ?.     ?  ??  ??? ? 
    private String firstPartOfQuery(String directionType) {
        return "SELECT " + mDatabaseHelper.COUNTRY_TITLE + ", " + mDatabaseHelper.CITY_TITLE + ", "
                + mDatabaseHelper.STATION_TITLE + ", " + mDatabaseHelper.STATIONS_TABLE + "."
                + mDatabaseHelper.STATION_ID + " FROM " + mDatabaseHelper.CITIES_TABLE + ", "
                + mDatabaseHelper.STATIONS_TABLE + " WHERE (" + mDatabaseHelper.CITY_DIRECTION + " LIKE '"
                + directionType + "' OR " + mDatabaseHelper.CITY_DIRECTION + " LIKE 'Both') AND ("
                + mDatabaseHelper.STATION_DIRECTION + " LIKE '" + directionType + "' OR "
                + mDatabaseHelper.STATION_DIRECTION + " LIKE 'Both') AND (" + mDatabaseHelper.CITIES_TABLE + "."
                + mDatabaseHelper.CITY_CITY_ID + " = " + mDatabaseHelper.STATION_CITY_ID + ")";
    }

    //    ? ?, ?  ?
    private String secondPartOfQuerty() {
        return " ORDER BY " + mDatabaseHelper.COUNTRY_TITLE + ", " + mDatabaseHelper.CITY_TITLE;
    }

    //    ? ?, ?  ? ?
    private String searchPartOfQuery() {
        return " AND (" + mDatabaseHelper.STATION_TITLE + " LIKE ? )";
    }
}