Skip to content

Commit

Permalink
Add Lab6
Browse files Browse the repository at this point in the history
  • Loading branch information
jackshendrikov committed Feb 17, 2021
1 parent fe28791 commit db2b1e0
Show file tree
Hide file tree
Showing 38 changed files with 2,125 additions and 475 deletions.
3 changes: 3 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ dependencies {
implementation 'com.jackandphantom.android:customtogglebutton:1.0.1'
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
implementation 'com.jjoe64:graphview:4.2.2'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'org.lucasr.twowayview:twowayview:0.1.4'
implementation 'com.baoyz.swipemenulistview:library:1.3.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,11 @@
</intent-filter>
</activity>

<activity android:name=".GalleryActivity"
<activity android:name=".PictureActivity"
android:theme="@style/Theme.AppCompat.NoActionBar"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.GalleryActivity" />
<action android:name="android.intent.action.PictureActivity" />

<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ protected void onCreate(Bundle savedInstanceState) {
Book fullBook = (Book) getIntent().getSerializableExtra("book_full");

ImageView cover = findViewById(R.id.image_full);
assert fullBook != null;
if (fullBook.getImageUrl().equals("")) {
cover.setImageResource(R.drawable.noimage);
} else {
Expand Down
243 changes: 134 additions & 109 deletions app/src/main/java/ua/kpi/comsys/io8227/jackshen/BookActivity.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
package ua.kpi.comsys.io8227.jackshen;

import android.app.LoaderManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Outline;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
Expand All @@ -29,25 +30,45 @@
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.android.material.textfield.TextInputEditText;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class BookActivity extends AppCompatActivity {
public class BookActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>> {

/** URL for book data */
public static final String REQUEST_URL = "";

/**
* Constant value for the book loader ID.
* We can choose any int, it`s really needed for multiple loaders
*/
private static final int BOOK_LOADER_ID = 1;

/** Adapter for the list of books */
private BookAdapter mAdapter;

/** Handler for the list of books */
List<Book> books;
List<Book> books = new ArrayList<>();

/** InputText for the book search */
private TextInputEditText mSearchText;

/** ImageButton for the book search */
private ImageView mSearchButton;

/** TextView that is displayed when the list is empty */
private TextView mEmptyTextView;

/** Loading indicator */
private View mLoadingIndicator;

private LoaderManager mLoaderManager;

private String mQueryText;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -61,14 +82,18 @@ protected void onCreate(Bundle savedInstanceState) {
// Setup UI to hide soft keyboard when clicked outside the {@link EditText}
setupUI(findViewById(R.id.main_parent));

// Load Data from JSON files
books = BookJSONParser.extractDataFromJson(this);

// Find a reference to the {@link bookListView} in the layout
SwipeMenuListView bookListView = findViewById(R.id.list);

mLoadingIndicator = findViewById(R.id.progress_bar);
mLoadingIndicator.setVisibility(View.GONE);

if (savedInstanceState != null) {
mQueryText = savedInstanceState.getString(REQUEST_URL);
}

// Set empty view when there is no data
View mEmptyTextView = findViewById(R.id.empty_view);
mEmptyTextView = findViewById(R.id.empty_view);
bookListView.setEmptyView(mEmptyTextView);

// Create a new adapter that takes an empty list of books as input
Expand Down Expand Up @@ -106,7 +131,7 @@ public void create(SwipeMenu menu) {
mSearchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickSearch();
onClickSearch(Objects.requireNonNull(mSearchText.getText()).toString());
}
});

Expand All @@ -119,7 +144,8 @@ public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// User has finished entering text
// Perform the search button click programmatically
onClickSearch();
onClickSearch(Objects.requireNonNull(mSearchText.getText()).toString());

// Return true on successfully handling the action
return true;
}
Expand Down Expand Up @@ -157,112 +183,74 @@ public void onItemClick(AdapterView<?> adapterView, View view, int position, lon
}
});

// Check if the book list has been updated, if so, add new values ​​to the activity
updateListView();

Button mAddButton = findViewById(R.id.buttonAdd);

//Stylization button for adding books
ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
int shapeSize = getResources().getDimensionPixelSize(R.dimen.shape_size);
outline.setRoundRect(0, 0, shapeSize, shapeSize, shapeSize / 2);
}
};
mAddButton.setOutlineProvider(viewOutlineProvider);
mAddButton.setClipToOutline(true);
/*
* Initialize the loader
*/
if (mQueryText != null) {
getLoaderManager().initLoader(BOOK_LOADER_ID, null, this);
}

}


/** This method is called when the user hits the search button */
public void onClickSearch() {
// Get a handle for the editable text view holding the user's search text and convert it
// to lowercase string value
String text = mSearchText.getText().toString().toLowerCase();

// Create empty list of Books
List<Book> booksSearch = new ArrayList<>();

if (text.length() == 0) {
// User has not entered any search text
// Notify user to enter text via toast
Toast toast = Toast.makeText(getApplicationContext(), "Please, enter text", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
// Go through all books in the current list and search if any title contains the text
// we are looking for
for (int i = 0; i < mAdapter.getCount(); i++) {
if (mAdapter.getItem(i).getTitle() != null) {
// Get lowercase value of current book title
String temp = mAdapter.getItem(i).getTitle().toLowerCase();
// If title contains our text -> create new Book item and add it to {@link booksSearch}
if (temp.contains(text)) {
Book findBook = new Book(mAdapter.getItem(i).getTitle(),
mAdapter.getItem(i).getSubtitle(), mAdapter.getItem(i).getAuthor(),
mAdapter.getItem(i).getPublisher(), mAdapter.getItem(i).getISBN(),
mAdapter.getItem(i).getPages(), mAdapter.getItem(i).getYear(),
mAdapter.getItem(i).getRate(), mAdapter.getItem(i).getDescription(),
mAdapter.getItem(i).getPrice(), mAdapter.getItem(i).getImageUrl());
booksSearch.add(findBook);
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onClickSearch(String searchText) {
mSearchText.clearFocus();
mAdapter.clear();
mEmptyTextView.setVisibility(View.GONE);

// Get a reference to the ConnectivityManager to check state of network connectivity
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

// Get details on the currently active default data network
NetworkInfo networkInfo = Objects.requireNonNull(connMgr).getActiveNetworkInfo();

try {
// If there is a network connection -> get data
if (networkInfo != null && networkInfo.isConnected()) {
if (!searchText.isEmpty() && searchText.length() >= 3 && searchText != null) {
String bookName = URLEncoder.encode(searchText.trim().replaceAll(" ", "%20"), "UTF-8");

// Set the URL with the suitable bookName
mQueryText = "https://api.itbook.store/1.0/search/" + bookName;

// Show the loading indicator.
mLoadingIndicator.setVisibility(View.VISIBLE);

// Create a bundle called queryBundle
Bundle queryBundle = new Bundle();

// Use putString with REQUEST_URL as the key and the String value of the URL as the value
queryBundle.putString(REQUEST_URL, mQueryText);

// Get a reference to the LoaderManager, in order to interact with loaders.
mLoaderManager = getLoaderManager();

// Get the loader initialized. Go through the above specified int ID constant
// and pass the bundle to null.
Loader<String> BooksSearchLoader = mLoaderManager.getLoader(BOOK_LOADER_ID);
if (BooksSearchLoader == null) {
mLoaderManager.initLoader(BOOK_LOADER_ID, queryBundle, BookActivity.this);
} else {
mLoaderManager.restartLoader(BOOK_LOADER_ID, queryBundle, BookActivity.this);
}
} else {
Toast.makeText(this, "You need to introduce some text to search (>=3 symbols)", Toast.LENGTH_LONG).show();
}
}
if (mAdapter.isEmpty()) {
// No results available
Toast toast = Toast.makeText(getApplicationContext(), "There are no results", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
SwipeMenuListView bookListView = findViewById(R.id.list);

// Sort all books by title
Collections.sort(booksSearch, new Comparator<Book>() {
@Override public int compare(Book u1, Book u2) {
return u1.getTitle().compareTo(u2.getTitle());
}
});

// Create a new adapter that takes an empty list of books as input
mAdapter = new BookAdapter(this, booksSearch);

// Set the adapter on the {@link bookListView} so the list can be populated in UI
bookListView.setAdapter(mAdapter);
// Otherwise, display error
// First, hide loading indicator so error message will be visible
mLoadingIndicator.setVisibility(View.INVISIBLE);

// Notify about changes
mAdapter.notifyDataSetChanged();
// Update empty state with no connection error message
Toast.makeText(BookActivity.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
mEmptyTextView.setText("No Internet Connection");
}
}
}


/** This method is called when the user hits the add button */
public void onClickAdd(View view) {
Intent intent = new Intent(this, AddBookActivity.class);
startActivity(intent);
}

/**
* This method is called when the user create new Book item and we need to add it to our
* books List
*/
public void updateListView() {
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
books.add(new Book(getIntent().getStringExtra("title_new"),
getIntent().getStringExtra("subtitle_new"),
"Unknown",
"Unknown",
getIntent().getStringExtra("isbn_new"),
"undefined",
"undefined",
getIntent().getStringExtra("rate_new"),
"",
"$" + getIntent().getStringExtra("price_new"),
""
));
mAdapter.notifyDataSetChanged();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

Expand Down Expand Up @@ -317,5 +305,42 @@ public static void hideSoftKeyboard(Activity activity) {
}
}

@Override
public Loader<List<Book>> onCreateLoader(int i, Bundle args) {
return new BookLoader(this, args);
}

@Override
public void onLoadFinished(Loader<List<Book>> loader, List<Book> data) {
// Set empty text to display "No books found."
mEmptyTextView.setText("No books found");
mEmptyTextView.setVisibility(View.VISIBLE);

// Hide the indicator after the data is appeared
mLoadingIndicator.setVisibility(View.GONE);

// Clear the adapter pf previous book data
mAdapter.clear();

// If there is a valid list of {@link Book}s, then add them to the adapter's
// data set. This will trigger the ListView to update
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}

}

@Override
public void onLoaderReset(Loader<List<Book>> loader) {
// Clear existing data on adapter as loader is reset
mAdapter.clear();
}

/** Save the data about url */
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(REQUEST_URL, mQueryText);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public View getView(int position, View convertView, @NonNull ViewGroup parent) {
// Set the color on the rating circle
ratingCircle.setColor(ratingColor);


// Find the TextView with view ID titleBook
TextView titleView = listItemView.findViewById(R.id.titleBook);

Expand Down Expand Up @@ -155,6 +156,8 @@ private String formatRating(double rating) {
return ratingFormat.format(rating);
}



/** Class to download an image from URL */
public static class DownloadImage extends AsyncTask<String, Void, Bitmap> {
final ImageView bmImage;
Expand Down
Loading

0 comments on commit db2b1e0

Please sign in to comment.