dev.ronlemire.contactclientcloud.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for dev.ronlemire.contactclientcloud.MainActivity.java

Source

/*
 * Copyright 2011 The Android Open Source Project
 *
 * 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 dev.ronlemire.contactclientcloud;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;

import dev.ronlemire.contactclientcloud.R;
import android.support.v4.app.FragmentManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class MainActivity extends SherlockFragmentActivity {
    public static final String TAG = "MainActivity";
    public static final String SHARED_PREFERENCES_NAME = "prefs";
    public static final String MULTIPLE_CONTACT_URL_KEY = "multiple_contact_url";
    public static final String SINGLE_CONTACT_URL_KEY = "single_contact_url";
    private static final int COL_VALUE_IX = 3;
    private ContactListLoadedReceiver contactListLoadedReceiver;
    private ContactListReceiver contactListReceiver;
    private ContactAddedReceiver contactAddedReceiver;
    private ContactUpdatedReceiver contactUpdatedReceiver;
    private ContactLoadedReceiver contactLoadedReceiver;
    private ContactDeletedReceiver contactDeletedReceiver;
    private IntentFilter contactListLoadedFilter;
    private IntentFilter contactListFilter;
    private IntentFilter contactAddedFilter;
    private IntentFilter contactUpdatedFilter;
    private IntentFilter contactLoadedFilter;
    private IntentFilter contactDeletedFilter;
    private static FragmentManager myFragmentManager;
    private Contact contactLoaded = null;
    private String contactSelectedId;
    public static Context mainContext;
    private ContentResolver cr;
    private static String multipleContactUrl;
    private static String singleContactUrl;
    private LayoutImpl layoutImpl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.v(TAG, "in MainActivity onCreate");
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        FragmentManager.enableDebugLogging(true);
        setContentView(R.layout.main);

        mainContext = this;
        myFragmentManager = getSupportFragmentManager();
        if (isMultiPane()) {
            layoutImpl = new LayoutW1200Impl(myFragmentManager);
        } else {
            layoutImpl = new LayoutNormalImpl(myFragmentManager);
        }

        contactListLoadedReceiver = new ContactListLoadedReceiver();
        contactListLoadedFilter = new IntentFilter(ListFragment.CONTACT_LIST_LOADED_INTENT);

        contactListReceiver = new ContactListReceiver();
        contactListFilter = new IntentFilter(ListFragment.CONTACT_SELECTED_INTENT);

        contactAddedReceiver = new ContactAddedReceiver();
        contactAddedFilter = new IntentFilter(AddFragment.CONTACT_ADDED_INTENT);

        contactUpdatedReceiver = new ContactUpdatedReceiver();
        contactUpdatedFilter = new IntentFilter(UpdateFragment.CONTACT_UPDATED_INTENT);

        contactLoadedReceiver = new ContactLoadedReceiver();
        contactLoadedFilter = new IntentFilter(ViewFragment.CONTACT_LOADED_INTENT);

        contactDeletedReceiver = new ContactDeletedReceiver();
        contactDeletedFilter = new IntentFilter(DeleteFragment.CONTACT_DELETED_INTENT);

        if (areUrlsSet() == true) {
            if (savedInstanceState == null) {
                createListFragment();
            }
        } else {
            Toast.makeText(this, R.string.msgSetupPrefs, Toast.LENGTH_LONG).show();
            startActivity(new Intent("dev.ronlemire.configadmin.ConfigAdminActivity"));
        }
        setSupportProgressBarIndeterminateVisibility(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(contactListLoadedReceiver, contactListLoadedFilter);
        registerReceiver(contactListReceiver, contactListFilter);
        registerReceiver(contactAddedReceiver, contactAddedFilter);
        registerReceiver(contactUpdatedReceiver, contactUpdatedFilter);
        registerReceiver(contactLoadedReceiver, contactLoadedFilter);
        registerReceiver(contactDeletedReceiver, contactDeletedFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(contactListLoadedReceiver);
        unregisterReceiver(contactListReceiver);
        unregisterReceiver(contactAddedReceiver);
        unregisterReceiver(contactUpdatedReceiver);
        unregisterReceiver(contactLoadedReceiver);
        unregisterReceiver(contactDeletedReceiver);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Exiting Application");
        alertDialog.setMessage("Are you sure?");
        alertDialog.setIcon(android.R.attr.alertDialogIcon);
        alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                finish();
            }
        });
        alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                return;
            }
        });
        alertDialog.show();

        //      new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK)
        //            .setIconAttribute(android.R.attr.alertDialogIcon)
        //            .setTitle(R.string.exitingApplication)
        //            .setMessage(R.string.shortMessage)
        //            .setPositiveButton(R.string.alert_dialog_ok,
        //                  new DialogInterface.OnClickListener() {
        //                     public void onClick(DialogInterface dialog,
        //                           int whichButton) {
        //                        finish();
        //                     }
        //                  })
        //            .setNegativeButton(R.string.alert_dialog_cancel,
        //                  new DialogInterface.OnClickListener() {
        //                     public void onClick(DialogInterface dialog,
        //                           int whichButton) {
        //                        return;
        //                     }
        //                  }).create().show();
    }

    // *****************************************************************************
    // ActionBar
    // *****************************************************************************
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        this.getSupportMenuInflater().inflate(R.menu.actionmenu, menu);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            createListFragment();
            createEmptyFragment();
            contactLoaded = null;
            return true;
        case R.id.prefsItem:
            startActivity(new Intent("dev.ronlemire.configadmin.ConfigAdminActivity"));
            return true;
        case R.id.addContactItem:
            createAddFragment();
            return true;
        case R.id.editContactItem:
            createUpdateFragment();
            return true;
        case R.id.deleteContactItem:
            createDeleteFragment();
            return true;
        case R.id.menu_refresh:
            createListFragment();
            createEmptyFragment();
            contactLoaded = null;
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    // *****************************************************************************
    // Fragment Creation
    // *****************************************************************************
    public void createListFragment() {
        setSupportProgressBarIndeterminateVisibility(true);
        layoutImpl.createListFragment();
    }

    private void createAddFragment() {
        layoutImpl.createAddFragment();
    }

    private void createDeleteFragment() {
        if (isContactLoaded()) {
            layoutImpl.createDeleteFragment(contactLoaded);
        }
    }

    public void createEmptyFragment() {
        layoutImpl.createEmptyFragment();
    }

    private void createUpdateFragment() {
        if (isContactLoaded()) {
            layoutImpl.createUpdateFragment(contactLoaded);
        }
    }

    // *****************************************************************************
    // BroadcastReceivers
    // *****************************************************************************
    class ContactListLoadedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("ContactListLoadedReceiver", "ContactList has been loaded");
            Toast.makeText(context, "ContactList has been loaded", Toast.LENGTH_SHORT).show();
            setSupportProgressBarIndeterminateVisibility(false);
        }
    }

    class ContactLoadedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            contactLoaded = (Contact) intent.getSerializableExtra(ViewFragment.CONTACT_LOADED);
            Log.d("ContactLoadedReceiver", "Selected Id: " + contactLoaded.getId());
        }
    }

    class ContactListReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            contactSelectedId = intent.getStringExtra(ListFragment.CONTACT_SELECTED_ID);
            Log.d("ContactListReceiver", "Selected Id: " + contactSelectedId);

            layoutImpl.createViewFragment(contactSelectedId);
        }
    }

    class ContactAddedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newContactId = intent.getStringExtra(AddFragment.CONTACT_ID);
            Log.d("ContactAddedReceiver", "New Contact Id: " + newContactId);

            createListFragment();
            createEmptyFragment();
            contactLoaded = null;
        }
    }

    class ContactUpdatedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String existingContactId = intent.getStringExtra(UpdateFragment.CONTACT_UPDATED_ID);
            Log.d("ContactUpdatedReceiver", "Existing Contact Id: " + existingContactId);

            createListFragment();
            createEmptyFragment();
            contactLoaded = null;
        }
    }

    class ContactDeletedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String deleteContactId = intent.getStringExtra(DeleteFragment.CONTACT_DELETED_ID);
            Log.d("ContactDeletedReceiver", "Delete Contact Id: " + deleteContactId);

            createListFragment();
            createEmptyFragment();
            contactLoaded = null;
        }
    }

    // *****************************************************************************
    // Helper methods
    // *****************************************************************************
    public boolean isMultiPane() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels > 1200;
    }

    // *****************************************************************************
    // Make sure URLs are setup before doing any REST calls
    // *****************************************************************************
    private boolean areUrlsSet() {
        cr = mainContext.getContentResolver();
        multipleContactUrl = GetSetting("MULTIPLE_CONTACT_URL");
        singleContactUrl = GetSetting("SINGLE_CONTACT_URL");

        if (multipleContactUrl == null || multipleContactUrl == ""
                || multipleContactUrl.equals("No records in cursor") == true || singleContactUrl == null
                || singleContactUrl.equals("No records in cursor") == true || singleContactUrl == "") {
            return false;
        } else {
            return true;
        }
    }

    private String GetSetting(String name) {
        String settingName = name;
        String msg = "";
        try {
            Resources res = mainContext.getResources();
            Uri content_uri = Uri.parse(res.getString(R.string.config_provider));
            Cursor c = cr.query(content_uri, null, "name=?", new String[] { settingName }, null);
            if (c == null) {
                msg += "Null cursor";
            } else if (c.moveToFirst()) {
                String vl = c.getString(COL_VALUE_IX);
                msg += vl;
            } else {
                msg += "No records in cursor";
            }
        } catch (Exception ex) {
            msg += "Database Exception";
        }

        return msg;
    }

    private boolean isContactLoaded() {
        boolean loaded = contactLoaded != null;
        if (loaded == false) {
            Toast message = Toast.makeText(this, R.string.no_contact_selected, Toast.LENGTH_SHORT);
            message.setGravity(Gravity.CENTER, message.getXOffset(), message.getYOffset());
            message.show();
        }
        return loaded;
    }

}