com.barcamppenang2014.tabfragment.ProfileFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.barcamppenang2014.tabfragment.ProfileFragment.java

Source

/*
 * Copyright (C) 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 com.barcamppenang2014.tabfragment;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.barcamppenang2014.MainActivity;
import com.barcamppenang2014.MyDatabase;
import com.barcamppenang2014.R;
import com.barcamppenang2014.helper.GalleryImageResize;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

public class ProfileFragment extends SherlockFragment implements TabInterface {
    private Button bt_save;
    private ImageButton bt_connect;
    private ImageButton bt_namecard;
    private EditText et_name;
    private EditText et_email;
    private EditText et_phone;
    private EditText et_profession;
    private EditText et_fbId;
    private TextView tv_imgtext;
    private TextView tv_remove;
    private String isProfileCreated;
    private String uriStr = "none";
    public static final String TITLE = "  Profile";
    private static final int GALLERY_REQUEST_CODE = 100;
    private Fragment profilefrg;
    // Google Analytics
    private Tracker GaTracker;
    private GoogleAnalytics GaInstance;

    // Connecting to facebook
    private Session.StatusCallback statusCallback = new SessionStatusCallback();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GaInstance = GoogleAnalytics.getInstance(getActivity());
        GaTracker = GaInstance.getTracker("UA-35359053-9");
        GaTracker.sendView("TITLE");
    }

    @Override
    public void onResume() {
        super.onResume();
        ActionBar actionBar = ((MainActivity) getActivity()).getSupportActionBar();
        actionBar.setTitle(TITLE);
        actionBar.setDisplayHomeAsUpEnabled(false);

    }

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

        View v = inflater.inflate(R.layout.update_profile_page, container, false);
        profilefrg = this;
        bt_save = (Button) v.findViewById(R.id.btnSave);
        bt_connect = (ImageButton) v.findViewById(R.id.btnfbconnect);
        bt_namecard = (ImageButton) v.findViewById(R.id.bt_namecard);
        et_name = (EditText) v.findViewById(R.id.editTextName);
        et_email = (EditText) v.findViewById(R.id.editTextEmail);
        et_phone = (EditText) v.findViewById(R.id.editTextPhone);
        et_profession = (EditText) v.findViewById(R.id.editTextProfession);
        et_fbId = (EditText) v.findViewById(R.id.editTextFbId);
        tv_imgtext = (TextView) v.findViewById(R.id.tx_namecard);
        tv_remove = (TextView) v.findViewById(R.id.tx_remove);

        final Bitmap defaultNamecard = BitmapFactory.decodeResource(getActivity().getResources(),
                R.drawable.default_namecard);
        //set default image for namecard
        bt_namecard.setImageBitmap(defaultNamecard);
        // Retrive the data from sqlite if profile is created.
        isProfileCreated = check();

        if (isProfileCreated.equalsIgnoreCase("true")) {

            String[] myInfo = fillTextField();
            et_name.setText(myInfo[0]);
            et_email.setText(myInfo[1]);
            et_phone.setText(myInfo[2]);
            et_profession.setText(myInfo[3]);
            if (!myInfo[4].equals("none")) {
                et_fbId.setText(myInfo[4]);
            }
            String picUri = getSharePreferenceKey("picuri");
            // myInfo[5] retrieved from sharedpreference
            if (!picUri.equals("none")) {
                Uri imageUri = Uri.parse(picUri);
                try {
                    URIToBitmap(imageUri);
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

        }

        bt_connect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                fbLogin();
            }

        });

        tv_remove.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                SharedPreferences sharedpreferences = getActivity().getSharedPreferences("MyPREFERENCES",
                        Context.MODE_PRIVATE);
                Editor editor = sharedpreferences.edit();
                editor.putString("picuri", "none");
                editor.commit();

                //set default image for namecard
                bt_namecard.setImageBitmap(defaultNamecard);

            }

        });

        bt_namecard.setOnClickListener(galleryOnClickListener);
        tv_imgtext.setOnClickListener(galleryOnClickListener);

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        Session session = Session.getActiveSession();
        if (session == null) {

            if (savedInstanceState != null) {

                session = Session.restoreSession(getActivity(), null, statusCallback, savedInstanceState);
            }
            if (session == null) {
                Activity temp = getActivity();
                session = new Session(temp);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {

                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }

        bt_save.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                String name = et_name.getText().toString();
                String email = et_email.getText().toString();
                String phone = et_phone.getText().toString();
                String profession = et_profession.getText().toString();
                // fbId and picUri can be null
                String fbId = et_fbId.getText().toString().equals("") ? "none" : et_fbId.getText().toString();
                // String picUri = getSharePreferenceKey("picuri");

                if (name.equals("") || email.equals("") || phone.equals("") || profession.equals("")) {
                    Toast.makeText(getActivity(), "Please fill in all the details.", Toast.LENGTH_LONG).show();
                }

                else {
                    // URLNamecard =
                    // "http://chimou.com/barcamppg/namecard.php?get&email=yinsee@wsatp.com";

                    // If bitmap is not null, POST to php               

                    String picUri = getSharePreferenceKey("picuri");
                    if (!picUri.equals("none")) {

                        // new POSTNamecard().execute(email);
                        //new POSTNamecard().execute("baa@gmail.com");
                    }

                    MyDatabase database = new MyDatabase(getActivity());
                    SQLiteDatabase sqliteDatabase = database.getWritableDatabase();
                    String sql = "INSERT OR REPLACE INTO USERPROFILE (ISPFOFILECREATED,MYKEYID, MYNAME, MYEMAIL, MYPHONE,MYPROFESSION, MYFBID )"
                            + " VALUES ('true','" + "1','" + name + "', '" + email + "', '" + phone + "', '"
                            + profession + "', '" + fbId + "'); ";

                    sqliteDatabase.execSQL(sql);

                    database.close();
                    sqliteDatabase.close();

                    MainActivity main = (MainActivity) getActivity();
                    // main.switchContentWithinTab(new ProfileQrFragment(),
                    // TITLE);
                    main.switchContent(new ProfileQrFragment());

                }

            }

        });

        return v;

    }

    // return value in sharedpreferences
    private String getSharePreferenceKey(String key) {
        String storedPreference = "none";
        try {
            SharedPreferences sharedpreferences = getActivity().getSharedPreferences("MyPREFERENCES",
                    Context.MODE_PRIVATE);
            storedPreference = sharedpreferences.getString(key, "none");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return storedPreference;
        }
        return storedPreference;
    }

    // POST namecard in PHP
    private class POSTNamecard extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... param) {
            Log.v("yc", "call doInBackground");
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Bitmap bitmap = ((BitmapDrawable) bt_namecard.getDrawable()).getBitmap();
            bitmap.compress(CompressFormat.JPEG, 75, bos);
            Log.v("yc-bos", Integer.toString(bos.size()));
            Log.v("yc-bos", bos.toString());

            byte[] data = bos.toByteArray();
            Log.v("yc-byte data", Integer.toString(data.length));
            Log.v("yc-byte data ", data.toString());

            ByteArrayBody bab = new ByteArrayBody(data, "me");
            Log.v("yc-bab ", bab.toString());
            Log.v("yc-bab length ", Long.toString(bab.getContentLength()));
            entity.addPart("namecard", bab);

            HttpClient httpClient = new DefaultHttpClient();
            Log.v("yc url", "http://chimou.com/barcamppg/namecard.php?email=" + param[0]);
            HttpPost post = new HttpPost("http://chimou.com/barcamppg/namecard.php?email=" + param[0]);
            // http://chimou.com/barcamppg/namecard.php?get&email=baa@gmail.com
            post.setEntity(entity);

            try {
                HttpResponse response = httpClient.execute(post);

            } catch (ClientProtocolException e) {
                Log.e("asdf", e.getMessage(), e);
            } catch (IOException e) {
                Log.e("asdf", e.getMessage(), e);
            }
            return null;
        }
    }

    private OnClickListener galleryOnClickListener = new OnClickListener() {
        @Override
        public void onClick(final View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            MainActivity._tempFragment = profilefrg;
            startActivityForResult(intent, GALLERY_REQUEST_CODE);
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        // Log.d("fb", "onStart");
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        // Log.d("fb", "onStop");
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
        Log.d("yc", "call onActivityResult in profilefragment ");
        if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            // Recyle unused bitmaps
            /*
             * if (bitmap != null) { bitmap.recycle(); }
             */
            Uri uri = data.getData();
            uriStr = uri.toString();
            // save picUri to sharedpreference
            SharedPreferences sharedpreferences = getActivity().getSharedPreferences("MyPREFERENCES",
                    Context.MODE_PRIVATE);
            Editor editor = sharedpreferences.edit();
            // picUri could be 'none' or a valid picUri
            editor.putString("picuri", uriStr);
            editor.commit();

            try {
                URIToBitmap(uri);
            } catch (Exception e) {
                e.printStackTrace();
            }
            MainActivity._tempFragment = null;
        }
    }

    private void URIToBitmap(Uri uri) throws FileNotFoundException, IOException {
        // bitmap = Media.getBitmap(getActivity().getContentResolver(), uri);
        GalleryImageResize resizer = new GalleryImageResize();
        // Uri uri, Context context, Boolean inApp, Boolean frmCamera
        Bitmap bit = resizer.loadPrescaledBitmap(uri, getActivity().getApplicationContext(), true, false);
        bt_namecard.setImageBitmap(bit);
        // bitmap = Bitmap.createScaledBitmap(bitmap, 500, 400, false);
        // resizer.scaleAndSetImage(bt_namecard,600,bitmap);
        // return bitmap;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Log.d("fb", "onSaveInstanceState at profileFragment is called");
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    private void updateView() {
        Session session = Session.getActiveSession();
        Log.d("fb", "Is session open? " + Boolean.toString(session.isOpened()) + "session state: "
                + session.getState().toString());
        if (session.isOpened()) {
            // Log.d("fb", "at updateView, session is open");
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    // Log.d("fb", "onCompleted");
                    if (user != null) {

                        et_fbId.setText(user.getId());

                    }
                }
            });

        }
    }

    private void fbLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            // Log.d("fb", "there is session");
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        } else {
            // Log.d("fb", "there is NO session");
            Session.openActiveSession(getActivity(), this, true, statusCallback);
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            // Log.d("at SessionStatusCallback", "calling updateView");
            updateView();
        }
    }

    public String check() {
        // Log.d("yc", "at check()");
        String isCreated = "false";

        MyDatabase database = new MyDatabase(getActivity());
        SQLiteDatabase sqliteDatabase = database.getReadableDatabase();
        Log.d("debug", "database.getReadableDatabase()");
        String sql = "SELECT ISPFOFILECREATED FROM USERPROFILE;";
        Cursor retrieved = sqliteDatabase.rawQuery(sql, null);
        Log.d("debug", "rawQuery");

        if (retrieved.moveToFirst()) {
            isCreated = retrieved.getString(retrieved.getColumnIndex("ISPFOFILECREATED"));
        }

        Log.d("debug", "checking isProfileCreated " + isCreated);
        retrieved.close();
        database.close();
        sqliteDatabase.close();
        return isCreated;
    }

    // User data is already stored in sqlite.
    public String[] fillTextField() {
        String[] myInfo = new String[5];

        MyDatabase database = new MyDatabase(getActivity());
        SQLiteDatabase sqliteDatabase = database.getReadableDatabase();
        String sql = "SELECT * FROM USERPROFILE;";
        Cursor retrieved = sqliteDatabase.rawQuery(sql, null);

        // Log.d("yc","row of cursor in database is "+
        // Integer.toString(retrieved.getCount()));

        // If cursor is not null
        while (retrieved.moveToNext()) {

            myInfo[0] = retrieved.getString(retrieved.getColumnIndex("MYNAME"));
            myInfo[1] = retrieved.getString(retrieved.getColumnIndex("MYEMAIL"));
            myInfo[2] = retrieved.getString(retrieved.getColumnIndex("MYPHONE"));
            myInfo[3] = retrieved.getString(retrieved.getColumnIndex("MYPROFESSION"));
            myInfo[4] = retrieved.getString(retrieved.getColumnIndex("MYFBID"));
            // myInfo[5] =
            // retrieved.getString(retrieved.getColumnIndex("MYURI"));

        }

        retrieved.close();
        database.close();
        sqliteDatabase.close();

        return myInfo;

    }

    @Override
    public String printTitle() {

        return ProfileFragment.TITLE;
    }
}