com.kku.apps.pricesearch.util.Utils.java Source code

Java tutorial

Introduction

Here is the source code for com.kku.apps.pricesearch.util.Utils.java

Source

/*
 * Copyright (C) 2012 kkurahar
 *
 * 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 com.kku.apps.pricesearch.util;

import java.io.ByteArrayOutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.util.Log;

import com.kku.apps.pricesearch.provider.SearchContract;
import com.kku.apps.pricesearch.provider.SearchContract.FavoritesColumns;
import com.kku.apps.pricesearch.provider.SearchContract.HistoryColumns;
import com.kku.apps.pricesearch.ui.HomeActivity;
import com.kku.apps.pricesearch.R;

public class Utils {

    private static final String TAG = "Utils";

    // ??z?[{^??
    public static void goHome(Context context) {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(R.anim.fade, R.anim.hold);
    }

    // ???A?ui?v?L?[Xg\?[g?s?A?ui?v?ACe
    public static List<ListItem> addListItem(List<ListItem> list, ListItem item) {
        if (!("").equals(item.getPrice())) {
            list.add(item);
        }
        return list;
    }

    // ?i?
    public static Bitmap setupImageBitmap(String imageUrl) {

        // ?i
        final Bitmap bitmap = HttpConnection.getBitmapFromUrl(imageUrl);

        return bitmap;
    }

    // 7netpJSONp?[X?@Y?p?A?null?s
    public static ListItem setItemJson(ListItem item, JSONObject json) throws JSONException {
        if (!json.isNull("SalesPrice")) {
            item.setPrice(json.getString("SalesPrice"));
        }
        if (!json.isNull("ImageUrl")) {
            item.setImageUrl(json.getString("ImageUrl"));
        }
        if (!json.isNull("Manufacturer")) {
            item.setManufacturer(json.getString("Manufacturer"));
        }
        if (!json.isNull("JanCode")) {
            item.setKeywords(json.getString("JanCode"));
        }
        return item;
    }

    // ?
    public static String getDate() {
        final Calendar cal = Calendar.getInstance();
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy'N'MM''dd'' HH''mm''ss'b'");
        return sdf.format(cal.getTime());
    }

    // ???@bitmap ? byte[]
    public static byte[] getByteImage(Bitmap image) {

        final ByteArrayOutputStream stream = new ByteArrayOutputStream();
        image.compress(CompressFormat.PNG, 100, stream);

        return stream.toByteArray();
    }

    // ???@byte[] ? bitmap
    public static Bitmap getBitmapImage(byte[] image) {

        final BitmapFactory.Options options = new BitmapFactory.Options();

        return BitmapFactory.decodeByteArray(image, 0, image.length, options);
    }

    // Ce?[u???
    public static Cursor readFavorites(Context context, ListItem item) {

        final ContentResolver cr = context.getContentResolver();
        final Cursor c = cr.query(SearchContract.URI_FAVORITES, null, FavoritesColumns.ITEMURL + " = ?",
                new String[] { item.getItemUrl() }, null);
        return c;
    }

    // Ce?[u????
    public static void deleteFavorites(Context context, ListItem item) {
        final AsyncQueryHandler dbHandler = new AsyncQueryHandler(context.getContentResolver()) {
        };
        dbHandler.startDelete(0, null, SearchContract.URI_FAVORITES, FavoritesColumns.ITEMURL + " = ?",
                new String[] { item.getItemUrl() });
    }

    // Ce?[uo^??
    public static void entryFavorites(Context context, ListItem item) {
        final ContentValues cv = new ContentValues();
        cv.put(FavoritesColumns.KEYWORDS, item.getKeywords());
        cv.put(FavoritesColumns.NAME, item.getName());
        if (item.getImage() != null) {
            cv.put(FavoritesColumns.IMAGE, getByteImage(item.getImage()));
        }
        cv.put(FavoritesColumns.ITEMURL, item.getItemUrl());
        cv.put(FavoritesColumns.PRICE, item.getPrice());
        cv.put(FavoritesColumns.SHOP, item.getShop());
        cv.put(FavoritesColumns.LOGO, item.getLogo());
        cv.put(FavoritesColumns.DATE, Utils.getDate());
        final AsyncQueryHandler dbHandler = new AsyncQueryHandler(context.getContentResolver()) {

            @Override
            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
                super.onQueryComplete(token, cookie, cursor);
            }
        };
        dbHandler.startInsert(0, null, SearchContract.URI_FAVORITES, cv);
    }

    // e?[uo^??
    public static void entryHistory(Context context, ListItem item) {

        final ContentValues cv = new ContentValues();
        cv.put(HistoryColumns.KEYWORDS, item.getKeywords());
        cv.put(HistoryColumns.NAME, item.getName());
        if (item.getImage() != null) {
            cv.put(HistoryColumns.IMAGE, getByteImage(item.getImage()));
        }
        cv.put(HistoryColumns.DATE, Utils.getDate());
        final AsyncQueryHandler dbHandler = new AsyncQueryHandler(context.getContentResolver()) {

            @Override
            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
                super.onQueryComplete(token, cookie, cursor);
            }
        };
        dbHandler.startInsert(0, null, SearchContract.URI_HISTORY, cv);
    }

    // L?[??[h??iAPI?i?JANR?[h?iEAN?j?j
    public static String setupKeywords(List<ListItem> listItem) {

        String keywords = "";
        ListItem li;
        for (int i = 0, length = listItem.size(); i < length; i++) {
            li = listItem.get(i);
            if (!("").equals(li.getKeywords())) {
                keywords = li.getKeywords();
                break;
            }
        }
        return keywords;
    }

    // e?[uo^f?[^?
    public static ListItem setupHistroyItem(List<ListItem> listItem, String param) {
        ListItem item = new ListItem();

        if (isNumericAndJAN(param)) {
            item.setKeywords(param);
        } else {

            String keywords = setupKeywords(listItem);

            if (("").equals(keywords)) {
                item.setKeywords(param);
            } else {
                item.setKeywords(keywords);
            }
        }

        item.setName(listItem.get(0).getName());
        item.setImage(listItem.get(0).getImage());
        item.setImageUrl(listItem.get(0).getImageUrl());

        return item;
    }

    // NbNXgACe??
    public static ListItem setupClickItem(List<ListItem> listItem, int position) {

        ListItem item = new ListItem();

        item.setName(listItem.get(position).getName());
        item.setItemUrl(listItem.get(position).getItemUrl());
        item.setPrice(listItem.get(position).getPrice());
        item.setShop(listItem.get(position).getShop());
        item.setImageUrl(listItem.get(position).getImageUrl());
        item.setLogo(listItem.get(position).getLogo());
        item.setFavorites(listItem.get(position).getFavorites());

        return item;
    }

    // ?lJAN(EAN)R?[h
    public static Boolean isNumericAndJAN(String keywords) {

        int length = keywords.length();

        if (length != 13 || length != 8) {
            return false;
        } else {
            for (int i = 0; i < length; i++) {

                char c = keywords.charAt(i);
                char c1 = '0';
                char c2 = '9';

                if (c < c1 || c > c2) {
                    return false;
                }
            }
        }
        return true;
    }

    // litH?[}bg?
    public static String getPriceFromat(String price) {
        long num = Long.parseLong(price);
        final DecimalFormat df = new DecimalFormat("??###,###");
        String value = df.format(num);

        return value;
    }

    // Z?kURL
    public static String getShortUrl(Context context, String longUrl) {
        String url = longUrl;
        // Z?kURLAPIpp??[^??
        final Uri.Builder builder = new Uri.Builder();
        builder.scheme("http");
        builder.encodedAuthority("api.bit.ly");
        builder.path("/shorten");
        builder.appendQueryParameter("version", "2.0.1");
        builder.appendQueryParameter("login", "kkurahar");
        builder.appendQueryParameter("apiKey", context.getResources().getString(R.string.api_key_bitly));
        builder.appendQueryParameter("longUrl", longUrl);

        // Z?kURLIuWFNg
        final HttpConnection con = new HttpConnection();
        String jsonObj = con.doGet(builder.build().toString());
        try {
            final JSONObject json = new JSONObject(jsonObj);
            JSONObject resultJson = json.getJSONObject("results");
            JSONObject paramJson = resultJson.getJSONObject(longUrl);
            String shortUrl = paramJson.getString("shortUrl");

            if (shortUrl != null || ("").equals(shortUrl)) {
                url = shortUrl;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return url;
    }
}