mp.paschalis.RequestActivity.java Source code

Java tutorial

Introduction

Here is the source code for mp.paschalis.RequestActivity.java

Source

/*
 This file is part of SmartLib Project.
    
SmartLib is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
SmartLib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with SmartLib.  If not, see <http://www.gnu.org/licenses/>.
    
   Author: Paschalis Mpeis
    
   Affiliation:
   Data Management Systems Laboratory 
   Dept. of Computer Science 
   University of Cyprus 
   P.O. Box 20537 
   1678 Nicosia, CYPRUS 
   Web: http://dmsl.cs.ucy.ac.cy/
   Email: dmsl@cs.ucy.ac.cy
   Tel: +357-22-892755
   Fax: +357-22-892701
       
    
 */

package mp.paschalis;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

// import mp.paschalis.R;
import mp.paschalis.Cache.ImageLoader;
import com.google.zxing.client.android.PreferencesActivity;

public class RequestActivity extends SherlockActivity {

    private static final String TAG = RequestActivity.class.getSimpleName();

    MainActivity.DataClassActivities dataClassActivities;

    App app;

    Button buttonHybrid;

    Button buttonContact;

    ProgressBar progressBarHybrid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        app = (App) getApplication();

        // Get arguments, to determine who opened this activity
        final Bundle extras = getIntent().getExtras();

        try {
            dataClassActivities = (MainActivity.DataClassActivities) extras
                    .get(App.ExtrasForRequestBookActivityFromActivitiesActivity);
        } catch (Exception e) {
            Toast.makeText(RequestActivity.this, R.string.msgErrorApplicationReport, Toast.LENGTH_LONG).show();
            finish();
        }

        // Get layout's Data
        TextView username = (TextView) findViewById(R.id.textViewActivityItemUsername);

        TextView date = (TextView) findViewById(R.id.textViewActivityItemDate);

        TextView acknowledgeTitle = (TextView) findViewById(R.id.textViewActivityItemAnswerTitle);
        TextView acknowledge = (TextView) findViewById(R.id.textViewActivityItemAnswer);
        TextView isbn = (TextView) findViewById(R.id.textViewActivityItemISBN);
        TextView title = (TextView) findViewById(R.id.textViewActivityItemTitle);
        TextView authors = (TextView) findViewById(R.id.textViewActivityItemAuthors);

        ImageView cover = (ImageView) findViewById(R.id.imageViewActivityBookCover);

        username.setText(dataClassActivities.username);

        date.setText(App.makeTimeStampHumanReadble(getApplicationContext(), dataClassActivities.book.dateOfInsert));

        // Set Ack Status strings
        ExpandableAdapterActivityInfo.setStatusString(dataClassActivities.acknowledge, acknowledge,
                acknowledgeTitle);

        TextView tvnc = (TextView) findViewById(R.id.textViewNoCover);
        isbn.setText(dataClassActivities.book.isbn);
        title.setText(dataClassActivities.book.title);
        authors.setText(dataClassActivities.book.authors);

        // show The Image and save it to Library
        ImageLoader.DataClassDisplayBookCover bk = new ImageLoader.DataClassDisplayBookCover();
        bk.iv = cover;
        bk.isCover = true;
        bk.tv = tvnc;
        bk.pb = (ProgressBar) findViewById(R.id.progressBarLoadCover);
        bk.book = dataClassActivities.book;

        App.imageLoader.DisplayCover(bk);

        buttonHybrid = (Button) findViewById(R.id.buttonRequestHybrid);
        buttonContact = (Button) findViewById(R.id.buttonRequestContact);

        buttonContact.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RequestActivity.this, SendMessageActivity.class);

                intent.putExtra(App.ExtrasForSendMessage_DestinationUser, dataClassActivities.username);

                startActivity(intent);

            }
        });

        progressBarHybrid = (ProgressBar) findViewById(R.id.progressBarRequestHybridButton);

        switch (dataClassActivities.type) {
        case IncomingRequest:
            // Other user wants my books

            if (dataClassActivities.acknowledge == App.REQUESTS_ANSWER_DINT_ANSWER_YET) {
                hButtonReplyRequest();
                buttonHybrid.setText(R.string.reply);
            } else if (dataClassActivities.acknowledge == App.REQUESTS_ANSWER_POSITIVE) {
                hButtonLentABook();
            } else {
                hButtonDeleteRequest();
            }

            break;
        case OutgoingRequest:
            // I want a book that belongs to other user

            if (dataClassActivities.acknowledge == App.REQUESTS_ANSWER_DINT_ANSWER_YET) {
                hButtonDeleteRequest();

            } else if (dataClassActivities.acknowledge == App.REQUESTS_ANSWER_POSITIVE) {
                hButtonHide();
            } else {
                hButtonDeleteRequest();
            }

            buttonHybrid.setText(R.string.deleteRequest);
            break;
        case BooksITook:
            // Book i lented from another user(took)
            hButtonHide();

            break;
        case BooksIGave:
            // Book i lent to other user(gave)
            hButtonReturnBook();
            break;

        default:
            break;
        }

    }

    /**
     * Hides hybrid button
     */
    private void hButtonHide() {
        buttonHybrid.setVisibility(View.INVISIBLE);
    }

    /**
     * Returns a book to user
     */
    private void hButtonReturnBook() {
        buttonHybrid.setText(R.string.isItReturned_);

        buttonHybrid.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                {
                    AlertDialog.Builder alert = new AlertDialog.Builder(RequestActivity.this);
                    alert.setTitle(R.string.msgIsItReturnedToYou_);

                    alert.setIcon(R.drawable.ic_menu_forward);

                    alert.setNegativeButton(R.string.no, new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });

                    alert.setPositiveButton(R.string.yes, new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Return the book
                            new AsyncTaskReturnABook().execute(dataClassActivities.book.isbn);
                        }
                    });

                    alert.show();

                }

                // DataClassLentABook data = new DataClassLentABook();
                //
                // data.destinationUser = dataClassActivities.username;
                // data.isbn = dataClassActivities.isbn;
                //
                // new AsyncTaskLentABook_Activities().execute(data);

            }
        });

    }

    /**
     * Lents a book to user
     */
    private void hButtonLentABook() {
        buttonHybrid.setText(R.string.lent);

        buttonHybrid.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                {
                    AlertDialog.Builder alert = new AlertDialog.Builder(RequestActivity.this);
                    alert.setTitle(R.string.msg_sure);

                    alert.setIcon(R.drawable.ic_menu_back);

                    alert.setNegativeButton(R.string.no, new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });

                    alert.setPositiveButton(R.string.yes, new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Lent a book
                            LentBookActivity.DataClassLentABook data = new LentBookActivity.DataClassLentABook();

                            data.destinationUser = dataClassActivities.username;
                            data.isbn = dataClassActivities.book.isbn;

                            new AsyncTaskLentABook_Activities().execute(data);
                        }
                    });

                    alert.show();

                }

            }
        });

    }

    /**
     * Replies to request of user
     */
    private void hButtonReplyRequest() {
        buttonHybrid.setText(R.string.reply);

        buttonHybrid.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                AlertDialog.Builder builder = new AlertDialog.Builder(RequestActivity.this);

                builder.setIcon(R.drawable.ic_menu_info_details);
                builder.setTitle(R.string.replyToRequest);
                builder.setItems(R.array.ArrayRequestReply, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int item) {

                        LentBookActivity.DataClassLentABook d = new LentBookActivity.DataClassLentABook();
                        d.destinationUser = dataClassActivities.username;
                        d.isbn = dataClassActivities.book.isbn;
                        d.answer = "0";
                        if (item == 0)
                            d.answer = "1";

                        new AsyncTaskReplyToRequest().execute(d);

                    }
                });
                AlertDialog alert = builder.create();
                alert.show();

            }
        });

    }

    /**
     * Replies to request of user
     */
    private void hButtonDeleteRequest() {
        buttonHybrid.setText(R.string.deleteRequest);

        buttonHybrid.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                {
                    AlertDialog.Builder alert = new AlertDialog.Builder(RequestActivity.this);
                    alert.setTitle(R.string.msg_sure);

                    alert.setIcon(R.drawable.ic_dialog_alert_holo_light);

                    alert.setNegativeButton(R.string.no, new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });

                    alert.setPositiveButton(R.string.yes, new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Delete a request
                            LentBookActivity.DataClassLentABook d = new LentBookActivity.DataClassLentABook();
                            d.destinationUser = dataClassActivities.username;
                            d.isbn = dataClassActivities.book.isbn;

                            new AsyncTaskDeleteABookRequest().execute(d);
                        }
                    });

                    alert.show();

                }

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, App.MENU_GLOBAL_SETTINGS, Menu.NONE, R.string.menu_settings)
                .setIcon(R.drawable.ic_menu_settings_holo_light).setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);

        menu.add(Menu.NONE, App.MENU_LIBRARY_SETTINGS, Menu.NONE, app.library.name)
                .setIcon(R.drawable.ic_menu_account_list).setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        case App.MENU_LIBRARY_SETTINGS: {
            Intent myIntent = new Intent(RequestActivity.this, LibPreferences.class);
            RequestActivity.this.startActivity(myIntent);

        }
            return true;
        case App.MENU_GLOBAL_SETTINGS: {
            Intent myIntent = new Intent(RequestActivity.this, PreferencesActivity.class);

            RequestActivity.this.startActivity(myIntent);
        }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Lents a book to user, in Activities
     *
     * @author paschalis
     */
    private class AsyncTaskLentABook_Activities
            extends AsyncTask<LentBookActivity.DataClassLentABook, Integer, Integer> {

        LentBookActivity.DataClassLentABook mData;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            buttonHybrid.setEnabled(false);
            buttonHybrid.setVisibility(View.INVISIBLE);
            progressBarHybrid.setVisibility(View.VISIBLE);

        }

        @Override
        protected Integer doInBackground(LentBookActivity.DataClassLentABook... data) {

            mData = data[0];

            int returnResult = App.GENERAL_NO_INTERNET;

            ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
            // Say that we are mobile (Android Device)
            parameters.add(new BasicNameValuePair("device", App.DEVICE_ANDROID));

            // Save Username , ISBN, and Destination User
            parameters.add(new BasicNameValuePair("owner", app.getUsername()));
            parameters.add(new BasicNameValuePair("destination", data[0].destinationUser));
            parameters.add(new BasicNameValuePair("isbn", data[0].isbn));

            // Execute PHP Script
            String resultStr = App.executePHPScript(app.getLibrary_lentABook_URL(), parameters);

            // Parse Result (JSON Obj)
            if (resultStr != null) {
                try {
                    // Create JSON Obj based on the result!
                    JSONObject userData = new JSONObject(resultStr);

                    returnResult = userData.getInt("result");

                } catch (JSONException e) {
                    Log.e(TAG, "Error parsing data " + e.toString());

                }

            }

            return returnResult;

        }

        protected void onPostExecute(Integer result) {

            buttonHybrid.setVisibility(View.VISIBLE);
            progressBarHybrid.setVisibility(View.INVISIBLE);

            if (result == App.BORROW_SUCCESSFULL) {

                Toast.makeText(RequestActivity.this, R.string.msgBookSuccessfullyLented, Toast.LENGTH_SHORT).show();

                RequestActivity.this.finish();
            } else if (result == App.BORROW_CANT_LEND_YOURSELF) {
                Toast.makeText(RequestActivity.this, R.string.msgErrorApplicationReport, Toast.LENGTH_SHORT).show();
            } else if (result == App.BORROW_NOT_FOUND_USER_DESTINATION) {
                Toast.makeText(RequestActivity.this, R.string.msgErrorApplicationReport, Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(RequestActivity.this, R.string.msgBookFailedToLent, Toast.LENGTH_SHORT).show();

                // textViewLentResult.setText(R.string.msgBookFailedToLent);
                // App.setStyleErrorDirection(textViewLentResult);
                //
                buttonHybrid.setEnabled(true);

            }

        }
    }

    /**
     * Lents a book to user, in Activities
     *
     * @author paschalis
     */
    private class AsyncTaskDeleteABookRequest
            extends AsyncTask<LentBookActivity.DataClassLentABook, Integer, Integer> {

        LentBookActivity.DataClassLentABook mData;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            buttonHybrid.setEnabled(false);
            buttonHybrid.setVisibility(View.INVISIBLE);
            progressBarHybrid.setVisibility(View.VISIBLE);
        }

        @Override
        protected Integer doInBackground(LentBookActivity.DataClassLentABook... data) {

            mData = data[0];

            int returnResult = App.GENERAL_NO_INTERNET;

            ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
            // Say that we are mobile (Android Device)
            parameters.add(new BasicNameValuePair("device", App.DEVICE_ANDROID));

            // Destination User is now owner
            parameters.add(new BasicNameValuePair("owner", data[0].destinationUser));
            parameters.add(new BasicNameValuePair("username", app.user.username));
            parameters.add(new BasicNameValuePair("isbn", data[0].isbn));

            // Execute PHP Script
            String resultStr = App.executePHPScript(app.getLibrary_getdeleteABookRequest_URL(), parameters);

            // Parse Result (JSON Obj)
            if (resultStr != null) {
                try {
                    // Create JSON Obj based on the result!
                    JSONObject userData = new JSONObject(resultStr);

                    returnResult = userData.getInt("result");

                } catch (JSONException e) {
                    Log.e(TAG, "Error parsing data " + e.toString());

                }

            }

            return returnResult;

        }

        protected void onPostExecute(Integer result) {

            buttonHybrid.setVisibility(View.VISIBLE);
            progressBarHybrid.setVisibility(View.INVISIBLE);

            if (result == App.GENERAL_SUCCESSFULL) {

                Toast.makeText(RequestActivity.this, R.string.succesfullyDeletedRequest, Toast.LENGTH_SHORT).show();

                hButtonHide();

                RequestActivity.this.finish();
            } else if (result == App.GENERAL_DATABASE_ERROR) {
                Toast.makeText(RequestActivity.this, R.string.msgDatabaseError, Toast.LENGTH_SHORT).show();
                buttonHybrid.setEnabled(true);
            } else {
                Toast.makeText(RequestActivity.this, R.string.msgErrorApplicationReport, Toast.LENGTH_SHORT).show();

                buttonHybrid.setEnabled(true);

            }

        }
    }

    /**
     * Lents a book to user, in Activities
     *
     * @author paschalis
     */
    private class AsyncTaskReplyToRequest extends AsyncTask<LentBookActivity.DataClassLentABook, Integer, Integer> {

        LentBookActivity.DataClassLentABook mData;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            buttonHybrid.setEnabled(false);
            buttonHybrid.setVisibility(View.INVISIBLE);
            progressBarHybrid.setVisibility(View.VISIBLE);
        }

        @Override
        protected Integer doInBackground(LentBookActivity.DataClassLentABook... data) {

            mData = data[0];

            int returnResult = App.GENERAL_NO_INTERNET;

            ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
            // Say that we are mobile (Android Device)
            parameters.add(new BasicNameValuePair("device", App.DEVICE_ANDROID));

            // Save Username , ISBN, and Destination User
            parameters.add(new BasicNameValuePair("owner", app.getUsername()));
            parameters.add(new BasicNameValuePair("destination", data[0].destinationUser));
            parameters.add(new BasicNameValuePair("isbn", data[0].isbn));

            parameters.add(new BasicNameValuePair("answer", data[0].answer));

            // Execute PHP Script
            String resultStr = App.executePHPScript(app.getLibrary_getReplyToBookRequest_URL(), parameters);

            // Parse Result (JSON Obj)
            if (resultStr != null) {
                try {
                    // Create JSON Obj based on the result!
                    JSONObject userData = new JSONObject(resultStr);

                    returnResult = userData.getInt("result");

                } catch (JSONException e) {
                    Log.e(TAG, "Error parsing data " + e.toString());

                }

            }

            return returnResult;

        }

        protected void onPostExecute(Integer result) {

            buttonHybrid.setVisibility(View.VISIBLE);
            progressBarHybrid.setVisibility(View.INVISIBLE);

            if (result == App.GENERAL_SUCCESSFULL) {

                Toast.makeText(RequestActivity.this, R.string.succesfullyReplied, Toast.LENGTH_SHORT).show();

                hButtonHide();

                // RequestActivity.this.finish();
            } else if (result == App.GENERAL_DATABASE_ERROR) {
                Toast.makeText(RequestActivity.this, R.string.msgDatabaseError, Toast.LENGTH_SHORT).show();
                buttonHybrid.setEnabled(true);
            } else {
                Toast.makeText(RequestActivity.this, R.string.msgErrorApplicationReport, Toast.LENGTH_SHORT).show();

                buttonHybrid.setEnabled(true);

            }

        }
    }

    /**
     * Return a book to user
     *
     * @author paschalis
     */
    public class AsyncTaskReturnABook extends AsyncTask<String, Integer, Integer> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            buttonHybrid.setEnabled(false);
            buttonHybrid.setVisibility(View.INVISIBLE);
            progressBarHybrid.setVisibility(View.VISIBLE);

        }

        @Override
        protected Integer doInBackground(String... isbn) {

            int returnResult = App.GENERAL_NO_INTERNET;

            ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
            // Say that we are mobile (Android Device)
            parameters.add(new BasicNameValuePair("device", App.DEVICE_ANDROID));

            // Save Username , ISBN, and Destination User
            parameters.add(new BasicNameValuePair("owner", app.getUsername()));
            parameters.add(new BasicNameValuePair("isbn", isbn[0]));

            // Execute PHP Script
            String resultStr = App.executePHPScript(app.getLibrary_returnABook_URL(), parameters);

            // Parse Result (JSON Obj)
            if (resultStr != null) {
                try {
                    // Create JSON Obj based on the result!
                    JSONObject userData = new JSONObject(resultStr);

                    returnResult = userData.getInt("result");

                } catch (JSONException e) {
                    Log.e(TAG, "Error parsing data " + e.toString());

                }

            }

            return returnResult;

        }

        protected void onPostExecute(Integer result) {

            buttonHybrid.setEnabled(false);
            buttonHybrid.setVisibility(View.VISIBLE);
            progressBarHybrid.setVisibility(View.INVISIBLE);
            // buttonDeleteBook.setEnabled(false);

            if (result == App.GENERAL_SUCCESSFULL) {

                Toast.makeText(RequestActivity.this, R.string.msgBookSuccesfullyReturned, Toast.LENGTH_LONG).show();
                // Workaround
                RequestActivity.this.finish();

            } else {

                Toast.makeText(
                        RequestActivity.this, getString(R.string.msgBookFailedToReturn) + ". "
                                + getString(R.string.msgPleaseContact) + ": " + app.getLibraryEmail(),
                        Toast.LENGTH_LONG).show();

            }

        }

    }

    @Override
    protected void onResume() {
        // Set library's logo as ActionBar Icon
        App.imageLoader.DisplayActionBarIcon(app.library.getImageURL(), getApplicationContext(),
                getSupportActionBar());

        if (App.refreshLang) {
            refresh();
        }
        super.onResume();
    }

    /**
     * Refresh activity's language
     */
    private void refresh() {
        App.refreshLang = false;
        finish();
        Intent myIntent = new Intent(RequestActivity.this, RequestActivity.class);
        startActivity(myIntent);
    }

}