org.androidpn.demoapp.MessageListActivity.java Source code

Java tutorial

Introduction

Here is the source code for org.androidpn.demoapp.MessageListActivity.java

Source

/*
 * Copyright (C) 2010 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 org.androidpn.demoapp;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v4.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sohu.focus.framework.loader.JsonLoaderJeallyBean;
import com.sohu.focus.framework.loader.LoadContext;
import com.sohu.focus.framework.loader.cache.Configuration;

import org.androidpn.demoapp.util.CommonUtil;
import org.androidpn.demoapp.constant.Constants;
import org.androidpn.demoapp.model.MessageListResponse;
import org.androidpn.demoapp.model.SingleMessage;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * Demonstration of the use of a CursorLoader to load and display contacts
 * data in a fragment.
 */
public class MessageListActivity extends ActionBarActivity
        implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener,
        PullToRefreshBase.OnRefreshListener<ListView>, AdapterView.OnItemLongClickListener {
    private PullToRefreshListView mListView;
    private MessageListAdapter mAdapter;
    private static final int LOADER_ID = 101;
    private static final int LOADER_ONLINE_ID = 102;
    private String latestId;
    private boolean downLoadOnline = false;
    private boolean manualRefresh = false;
    private ProgressDialog progressDialog;
    static final String[] MESSAGE_SUMMARY_PROJECTION = new String[] { MessageProvider.DemoMessage.ID,
            MessageProvider.DemoMessage.MESSAGE_ID, MessageProvider.DemoMessage.API_KEY,
            MessageProvider.DemoMessage.TITLE, MessageProvider.DemoMessage.CONTENT,
            MessageProvider.DemoMessage.IS_REPLY, MessageProvider.DemoMessage.STATUS,
            MessageProvider.DemoMessage.RECEIVE_DATE, MessageProvider.DemoMessage.OPTIONS };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_message_list);
        initUi();
        loadDataInDatabase();
    }

    private void initUi() {
        mAdapter = new MessageListAdapter(this, null);
        mListView = (PullToRefreshListView) findViewById(R.id.message_list);
        mListView.setAdapter(mAdapter);
        mListView.setMode(PullToRefreshBase.Mode.BOTH);
        mListView.getLoadingLayoutProxy(false, true).setPullLabel("...");
        mListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("...");
        mListView.getLoadingLayoutProxy(false, true).setReleaseLabel("...");
        mListView.setOnItemClickListener(this);
        mListView.setOnRefreshListener(this);
        mListView.getRefreshableView().setDivider(null);
        mListView.setBackgroundColor(getResources().getColor(R.color.default_background));
        mListView.getRefreshableView().setBackgroundColor(getResources().getColor(R.color.default_background));
        mListView.getRefreshableView().setSelector(android.R.color.transparent);
        mListView.getRefreshableView().setOnItemLongClickListener(this);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("downLoad info.....");
        progressDialog.setCancelable(false);
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri baseUri = ServerMessage.CONTENT_URI;

        return new CursorLoader(this, baseUri, MESSAGE_SUMMARY_PROJECTION, null, null,
                MessageProvider.DemoMessage.RECEIVE_DATE + " DESC");
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        downLoadOnline = true;
        if (data != null && data.getCount() > 0) {
            ArrayList<SingleMessage> list = new ArrayList<SingleMessage>();
            if (data.moveToFirst()) {
                do {
                    list.add(ServerMessage.createFromCursor(data).toSingleMessage());
                } while (data.moveToNext());
            }

            mAdapter.addData(list);
            mAdapter.notifyDataSetChanged();
            latestId = ((SingleMessage) (mAdapter.getItem(mAdapter.getCount() - 1))).getId();
            data.close();
            mListView.onRefreshComplete();
            checkIfAnyNewData();
        } else {
            if (data != null)
                data.close();
            loadOnline();
        }

    }

    private void checkIfAnyNewData() {
        final ProgressDialog checkDialog = new ProgressDialog(this);
        checkDialog.setMessage(getString(R.string.check_new_data));
        checkDialog.show();
        getSupportLoaderManager().restartLoader(LOADER_ONLINE_ID, null,
                new LoaderManager.LoaderCallbacks<MessageListResponse>() {
                    @Override
                    public Loader<MessageListResponse> onCreateLoader(int id, Bundle args) {
                        String identity = MobilePushApp.getInstance().getUserIdentity();
                        String url = Constants.getMessageList(identity, "");
                        LoadContext<MessageListResponse> loadContext = new LoadContext<MessageListResponse>();
                        loadContext.setFlag(LoadContext.FLAG_HTTP_ONLY);
                        loadContext.setClazz(MessageListResponse.class);
                        loadContext.setParam(url);

                        return new JsonLoaderJeallyBean<MessageListResponse>(MessageListActivity.this, loadContext,
                                new Configuration.CREATOR().setExpiration(Constants.EXPIRATION_TIME)
                                        .setCacheDir(getCacheDir().toString()).create());
                    }

                    @Override
                    public void onLoadFinished(Loader<MessageListResponse> loader, MessageListResponse data) {
                        if (data != null && data.getResultCode().equals("1") && data.getList().size() > 0) {
                            if (!((SingleMessage) mAdapter.getItem(0)).getId().equals(data.getList().get(0).getId())
                                    || manualRefresh) {
                                getContentResolver().delete(ServerMessage.CONTENT_URI, null, null);
                                saveData(data.getList());
                                mAdapter = new MessageListAdapter(MessageListActivity.this, data.getList());
                                mListView.setAdapter(mAdapter);
                                mAdapter.notifyDataSetChanged();
                                latestId = ((SingleMessage) (mAdapter.getItem(mAdapter.getCount() - 1))).getId();
                            }
                        }
                        if (checkDialog.isShowing())
                            checkDialog.dismiss();
                        manualRefresh = false;
                        mListView.onRefreshComplete();
                    }

                    @Override
                    public void onLoaderReset(Loader<MessageListResponse> loader) {

                    }
                });
    }

    public void onLoaderReset(Loader<Cursor> loader) {

    }

    private void loadOnline() {
        progressDialog.show();
        getSupportLoaderManager().restartLoader(LOADER_ONLINE_ID, null,
                new LoaderManager.LoaderCallbacks<MessageListResponse>() {
                    @Override
                    public Loader<MessageListResponse> onCreateLoader(int id, Bundle args) {
                        String identity = MobilePushApp.getInstance().getUserIdentity();
                        String url = Constants.getMessageList(identity, String.valueOf(latestId));
                        LoadContext<MessageListResponse> loadContext = new LoadContext<MessageListResponse>();
                        loadContext.setFlag(LoadContext.FLAG_HTTP_ONLY);
                        loadContext.setClazz(MessageListResponse.class);
                        loadContext.setParam(url);

                        return new JsonLoaderJeallyBean<MessageListResponse>(MessageListActivity.this, loadContext,
                                new Configuration.CREATOR().setExpiration(Constants.EXPIRATION_TIME)
                                        .setCacheDir(getCacheDir().toString()).create());
                    }

                    @Override
                    public void onLoadFinished(Loader<MessageListResponse> loader, MessageListResponse data) {
                        if (progressDialog != null && progressDialog.isShowing())
                            progressDialog.dismiss();
                        if (data != null && data.getResultCode().equals("1") && data.getList().size() > 0) {
                            mAdapter.addData(data.getList());
                            mAdapter.notifyDataSetChanged();
                            saveData(data.getList());
                            latestId = ((SingleMessage) (mAdapter.getItem(mAdapter.getCount() - 1))).getId();
                        } else if (data != null && data.getResultCode().equals("0") && data.getList().size() == 0) {
                            Toast.makeText(MessageListActivity.this, "", Toast.LENGTH_LONG).show();
                        } else if (data != null && data.getResultCode().equals("0")) {
                            CommonUtil.ToastNetWorkError(MessageListActivity.this);
                        } else {
                            CommonUtil.ToastNetWorkError(MessageListActivity.this);
                        }
                        mListView.onRefreshComplete();
                    }

                    @Override
                    public void onLoaderReset(Loader<MessageListResponse> loader) {

                    }
                });
    }

    private void saveData(ArrayList<SingleMessage> list) {
        for (SingleMessage message : list) {
            String Id = message.getId();
            String apiKey = "1234567890";
            String title = message.getTitle();
            String messageBody = message.getMessage();
            String time = message.getTimes();
            String isReply = message.getIsReply();
            String options = message.getOptions();
            // save
            ContentResolver contentResolver = getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MESSAGE_SUMMARY_PROJECTION[1], Id);
            contentValues.put(MESSAGE_SUMMARY_PROJECTION[2], apiKey);
            contentValues.put(MESSAGE_SUMMARY_PROJECTION[3], title);
            contentValues.put(MESSAGE_SUMMARY_PROJECTION[4], messageBody);
            contentValues.put(MESSAGE_SUMMARY_PROJECTION[5], isReply);
            contentValues.put(MESSAGE_SUMMARY_PROJECTION[6], 0);
            contentValues.put(MESSAGE_SUMMARY_PROJECTION[7], time);
            contentValues.put(MESSAGE_SUMMARY_PROJECTION[8], options);
            contentResolver.insert(ServerMessage.CONTENT_URI, contentValues);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, MessageDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("message", (Serializable) parent.getAdapter().getItem(position));
        intent.putExtras(bundle);
        ((SingleMessage) parent.getAdapter().getItem(position)).setStatus(1);
        ContentResolver contentResolver = getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[6], 1);
        contentResolver.update(ServerMessage.CONTENT_URI, contentValues, "message_id = ?",
                new String[] { ((SingleMessage) parent.getAdapter().getItem(position)).getId() });
        mAdapter.notifyDataSetChanged();
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.profile_about, menu);
        menu.add(0, UIUtil.MENU_ID_REMOVE_ALL, 0, R.string.remove_all);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == UIUtil.MENU_ID_REMOVE_ALL) {
            removeAllMessage();
        }
        return UIUtil.selectMenu(item, this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        getSupportLoaderManager().destroyLoader(LOADER_ID);
        getSupportLoaderManager().destroyLoader(LOADER_ONLINE_ID);
    }

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (refreshView.isHeaderShown()) {
            manualRefresh = true;
            checkIfAnyNewData();
        } else if (refreshView.isFooterShown()) {
            loadOnline();
        }

    }

    private void loadDataInDatabase() {
        getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long id) {
        new AlertDialog.Builder(this).setTitle("").setMessage("")
                .setPositiveButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        deleteMessage(position - 1);
                    }
                }).setNegativeButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();

        return true;
    }

    private void deleteMessage(int position) {
        if (position >= 0 && position < mAdapter.getCount()) {
            getContentResolver().delete(ServerMessage.CONTENT_URI, "message_id = ?",
                    new String[] { ((SingleMessage) mAdapter.getItem(position)).getId() });
            mAdapter.remove(position);
        }
    }

    private void removeAllMessage() {
        getContentResolver().delete(ServerMessage.CONTENT_URI, null, null);
        mAdapter.removeAll();
    }
}