android action bar menu button event handling issue - android

I have action button in my fragment, i follow some tutorial in internet and i have managed to show my action button in my fragment. but for unknown reason when i tap the action button nothing happened.
This is my xml menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<item android:id="#+id/send_card"
android:icon="#drawable/btn_add"
android:title="send card"
yourapp:showAsAction="always"
/>
</menu>
package com.dycode.durexlovers.fragment;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.dycode.durexlovers.R;
import com.dycode.durexlovers.adapter.HorizontalListViewCardAdapter;
import com.dycode.durexlovers.adapter.MomentAdapter;
import com.dycode.durexlovers.adapter.SpiceItUpAdapter;
import com.dycode.durexlovers.adapter.ViewPagerAdapter;
import com.dycode.durexlovers.api.CardApi;
import com.dycode.durexlovers.api.MomentApi;
import com.dycode.durexlovers.card.PreviewCard;
import com.dycode.durexlovers.card.SendCard;
import com.dycode.durexlovers.dao.CardDao;
import com.dycode.durexlovers.dao.MomentDao;
import com.dycode.durexlovers.utils.Constant;
import com.dycode.durexlovers.utils.SessionManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import it.sephiroth.android.library.widget.AdapterView;
import it.sephiroth.android.library.widget.HListView;
/**
* Created by Minecraft on 06/01/2015.
*/
public class SpiceItUpFragment extends Fragment {
LinearLayout stripRomantic, stripRomanticAct, stripTease, stripTeaseAct, stripIntimate, stripIntimateAct;
Button btnRomantic, btnTease, btnIntimate, btnNext, btnBack, btnSendCard;
HListView hListView;
private CardApi cardApi;
private List<CardDao> listCard = new ArrayList<CardDao>();
HorizontalListViewCardAdapter adapter;
ProgressDialog dialog;
SessionManager sessionManager;
String email;
TextView tvNameCard, tvDescCard;
ImageView ivCard;
AQuery aQuery;
int pos;
String categoryCard;
public SpiceItUpFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_spice_it_up, container, false);
stripRomantic = (LinearLayout) rootView.findViewById(R.id.strip_tab_romantic);
stripRomanticAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_romantic_active);
stripTease = (LinearLayout) rootView.findViewById(R.id.strip_tab_tease);
stripTeaseAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_tease_active);
stripIntimate = (LinearLayout) rootView.findViewById(R.id.strip_tab_intimate);
stripIntimateAct = (LinearLayout) rootView.findViewById(R.id.strip_tab_intimate_active);
btnRomantic = (Button) rootView.findViewById(R.id.btnRomantic);
btnTease = (Button) rootView.findViewById(R.id.btnTease);
btnIntimate = (Button) rootView.findViewById(R.id.btnIntimate);
btnNext = (Button) rootView.findViewById(R.id.btnNext);
btnBack = (Button) rootView.findViewById(R.id.btnBack);
btnSendCard = (Button) rootView.findViewById(R.id.btnSendCard);
hListView = (HListView) rootView.findViewById(R.id.hListView);
tvNameCard = (TextView) rootView.findViewById(R.id.tvNameCard);
tvDescCard = (TextView) rootView.findViewById(R.id.tvDescCard);
ivCard = (ImageView) rootView.findViewById(R.id.ivCard);
aQuery = new AQuery(getActivity());
cardApi = new CardApi(getActivity(), cardListener);
adapter = new HorizontalListViewCardAdapter(getActivity(), listCard);
hListView.setAdapter(adapter);
sessionManager = new SessionManager(getActivity());
// get user data from session
HashMap<String, String> user = sessionManager.getUserDetails();
email = user.get(sessionManager.KEY_EMAIL);
categoryCard = "romantic";
cardApi.callApiCard(email, categoryCard);
//hListView.setAdapter( new ArrayAdapter<String>( getActivity(), R.layout.card_horizontal_list_item, activities ) );
btnRomantic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("romantic")){
categoryCard = "romantic";
stripRomantic.setVisibility(View.INVISIBLE);
stripRomanticAct.setVisibility(View.VISIBLE);
stripTease.setVisibility(View.VISIBLE);
stripTeaseAct.setVisibility(View.INVISIBLE);
stripIntimate.setVisibility(View.VISIBLE);
stripIntimateAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email, categoryCard);
}
}
});
btnTease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("tease")){
categoryCard = "tease";
stripTease.setVisibility(View.INVISIBLE);
stripTeaseAct.setVisibility(View.VISIBLE);
stripRomantic.setVisibility(View.VISIBLE);
stripRomanticAct.setVisibility(View.INVISIBLE);
stripIntimate.setVisibility(View.VISIBLE);
stripIntimateAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email,categoryCard);
}
}
});
btnIntimate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!categoryCard.equalsIgnoreCase("intimate")){
categoryCard = "intimate";
stripIntimate.setVisibility(View.INVISIBLE);
stripIntimateAct.setVisibility(View.VISIBLE);
stripTease.setVisibility(View.VISIBLE);
stripTeaseAct.setVisibility(View.INVISIBLE);
stripRomantic.setVisibility(View.VISIBLE);
stripRomanticAct.setVisibility(View.INVISIBLE);
cardApi.callApiCard(email,categoryCard);
}
}
});
hListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
pos = position;
tvNameCard.setText(listCard.get(position).getNameCard());
tvDescCard.setText(listCard.get(position).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(position).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pos < listCard.size()-1) {
pos = pos + 1;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pos > 0) {
pos = pos - 1;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
}
});
btnSendCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), PreviewCard.class);
i.putExtra("id",listCard.get(pos).getIdCard());
i.putExtra("name",listCard.get(pos).getNameCard());
i.putExtra("desc",listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
i.putExtra("url",urlCard);
startActivity(i);
}
});
setHasOptionsMenu(true);
return rootView;
}
CardApi.ApiResultListener cardListener = new CardApi.ApiResultListener() {
#Override
public void onApiResultOk(List<CardDao> listData) {
if (dialog != null)
dialog.dismiss();
listCard.clear();
listCard.addAll(listData);
adapter.notifyDataSetChanged();
pos = listCard.size() / 2;
tvNameCard.setText(listCard.get(pos).getNameCard());
tvDescCard.setText(listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
aQuery.id(ivCard).image(urlCard);
}
#Override
public void onApiPreCall() {
dialog = ProgressDialog.show(getActivity(), "", "loading...");
}
#Override
public void onApiResultError(String errorMessage) {
showDialogNotification(errorMessage);
if (dialog != null)
dialog.dismiss();
}
};
private void showDialogNotification(String message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder.setTitle("Notification");
alertDialogBuilder.setMessage(message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_send_card, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.send_card:
Intent i = new Intent(getActivity(), PreviewCard.class);
i.putExtra("id",listCard.get(pos).getIdCard());
i.putExtra("name",listCard.get(pos).getNameCard());
i.putExtra("desc",listCard.get(pos).getDescriptionCard());
String urlCard = Constant.URLImage.CARD + listCard.get(pos).getImageCard();
i.putExtra("url",urlCard);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Thank for your help

change your method like below.you need to call super.onCreateOptionsMenu like below
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_send_card, menu);
}
and set setHasOptionsMenu(true); in your oncreateview befor return v;

Related

ListView displays data twice

I am working on a small application to save the data of the book (such as the name of the book, the type of the book, the author of the book and the year of publication) in a database, but when the data is returned from the databases using CursorLoader It's shown twice in ListView
This is a code of AddBook activity.
package training.android.com.librarycard;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
public class AddBook extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_BOOK_LOADER = 0;
Spinner mBookType;
EditText mBookTitle, mBookAuthor, mBookPublishYear;
String bookType;
int position;
private boolean bookHasChanged = false;
private Uri currentBookUri;
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
bookHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
Intent intent = getIntent();
if (intent != null) {
currentBookUri = intent.getData();
if (currentBookUri == null) {
setTitle("Add a book");
invalidateOptionsMenu();
} else {
setTitle("Edit a book");
getLoaderManager().initLoader(EXISTING_BOOK_LOADER, null, this);
}
}
mBookType = findViewById(R.id.spinner);
mBookTitle = findViewById(R.id.book_title);
mBookAuthor = findViewById(R.id.book_author);
mBookPublishYear = findViewById(R.id.publish_year);
mBookType.setOnTouchListener(touchListener);
mBookAuthor.setOnTouchListener(touchListener);
mBookTitle.setOnTouchListener(touchListener);
mBookPublishYear.setOnTouchListener(touchListener);
setupBookTypeSpinner();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (currentBookUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_save:
setBook();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!bookHasChanged) {
NavUtils.navigateUpFromSameTask(AddBook.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener
= new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
NavUtils.navigateUpFromSameTask(AddBook.this);
}
};
showUnsavedChangeDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
private void showUnsavedChangeDialog(DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Discard your changes and quit editing?");
builder.setPositiveButton("Discard", discardButtonClickListener);
builder.setNegativeButton("Keep editing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this book ?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteBook();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteBook() {
if (currentBookUri != null) {
int rowDeleted = getContentResolver().delete(currentBookUri, null, null);
if (rowDeleted == 0)
Toast.makeText(this, "Delete book failed", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Delete book successful", Toast.LENGTH_SHORT).show();
}
finish();
}
public void setupBookTypeSpinner() {
final ArrayAdapter<CharSequence> bookTypeAdapter = ArrayAdapter.createFromResource(
this, R.array.books_type, R.layout.support_simple_spinner_dropdown_item);
bookTypeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mBookType.setAdapter(bookTypeAdapter);
mBookType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
bookType = parent.getSelectedItem().toString();
position = parent.getSelectedItemPosition();
Log.i("BookTypeSelection", bookType+"");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void setBook() {
String bookTitle = mBookTitle.getText().toString().trim();
String bookAuthor = mBookAuthor.getText().toString().trim();
String publishYear = mBookPublishYear.getText().toString().trim();
if (currentBookUri == null && TextUtils.isEmpty(bookTitle) && TextUtils.isEmpty(bookAuthor)
&& TextUtils.isEmpty(publishYear))
return;
Database database = new Database(this);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE, bookTitle);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR, bookAuthor);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR, publishYear);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE, bookType);
if (currentBookUri == null) {
Uri uri = getContentResolver().insert(LibraryCardContract.LibraryCard.CONTENT_URI, values);
if (uri == null) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
} else {
int rowAffected = getContentResolver().update(currentBookUri, values, null, null);
if (rowAffected == 0) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
}
db.insert(LibraryCardContract.LibraryCard.TABLE_NAME, null, values);
Toast.makeText(this, "Insert new book", Toast.LENGTH_SHORT).show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String [] projection = {
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR };
return new CursorLoader(this,currentBookUri,projection,
null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(data.moveToFirst()){
String title = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String publishYear = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
mBookTitle.setText(title);
mBookAuthor.setText(author);
mBookType.setSelection(position);
mBookPublishYear.setText(publishYear);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mBookTitle.setText("");
mBookType.setSelection(position);
mBookAuthor.setText("");
mBookPublishYear.setText("");
}
#Override
public void onBackPressed() {
if(!bookHasChanged){
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
};
showUnsavedChangeDialog(discardButtonClickListener);
}
}
And this is a code of Home activity that contains a listView to
display the data.
package training.android.com.librarycard;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.Models.BookCursorAdapter;
import training.android.com.librarycard.Models.BookDetail;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final int BOOK_LOADER = 0;
private ListView mBookList;
private BookCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mBookList = findViewById(R.id.books_rv);
cursorAdapter = new BookCursorAdapter(this, null);
mBookList.setAdapter(cursorAdapter);
mBookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Home.this, AddBook.class);
Uri currentPetUri = ContentUris.withAppendedId(LibraryCardContract.LibraryCard.CONTENT_URI, id);
intent.setData(currentPetUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(BOOK_LOADER, null, this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddBook.class);
startActivity(intent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.delete_all_books:
deleteAllBooks();
return true;
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
private void deleteAllBooks() {
int rowDeleted = getContentResolver().delete(LibraryCardContract.LibraryCard.CONTENT_URI,
null, null);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
LibraryCardContract.LibraryCard._ID,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR};
return new CursorLoader(this, LibraryCardContract.LibraryCard.CONTENT_URI,
projection,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
> This is a code of **BookCursorAdapter** class.
package training.android.com.librarycard.Models;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.R;
/**
* Created by Hassan on 4/9/2018.
*/
public class BookCursorAdapter extends CursorAdapter {
public BookCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context)
.inflate(R.layout.book_list,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView bookTitle = view.findViewById(R.id.book_name_tv);
TextView bookAuthor = view.findViewById(R.id.author_tv);
TextView bookType = view.findViewById(R.id.book_type_tv);
TextView publishYear = view.findViewById(R.id.publish_year_tv);
String title = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String year = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
bookAuthor.setText(author);
bookTitle.setText(title);
bookType.setText(type);
publishYear.setText(year);
}
#Override
public int getCount() {
return super.getCount();
}
}
Screenshot of the application
enter image description here

onSupportNavigateUp() function not working?

All my pages use onSupportNavigateUp() function with the same method and it's working. However when I tried to implement in my LessonActivity.java it's not working. Any ideas? It's it because of WebView?
My current working codes for LessonActivity.java:
package com.activity.lesson;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatRatingBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.material.components.R;
import com.material.components.activity.pastyears.PastYears;
import com.material.components.activity.practice.Practice;
import com.material.components.adapter.AdapterQuestionToTeacher;
import com.material.components.model.Lessons;
import com.material.components.model.QuestionsToTeacher;
import com.material.components.model.SubChapter;
import com.material.components.utils.Tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LessonActivity extends AppCompatActivity{
public WebView contentWebView;
public ProgressBar progressBar;
public String chapterTitle;
private SharedPreferences analysisSharedPreferences;
private SharedPreferences.Editor editorAnalysisPreferences;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private BottomNavigationView navigation;
public ArrayList<QuestionsToTeacher> questionsToTeacherList = new ArrayList<>();
private AdapterQuestionToTeacher adapterQuestionToTeacher;
private RecyclerView questionListRecyclerView;
private String subjectId;
private String chapterId;
private String subchapterId;
private TextView question_content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
contentWebView = findViewById(R.id.contentWebView);
progressBar = findViewById(R.id.progressBarContent);
question_content = findViewById(R.id.question_content);
Tools.setSystemBarColor(this,R.color.black);
String qContent = question_content.getText().toString().trim();
if(qContent.isEmpty())
{
question_content.setVisibility(View.GONE);
}else
{
question_content.setVisibility(View.VISIBLE);
}
initToolbar();
String subChapterId = getIntent().getStringExtra("subchapter_id");
getLessonData(subChapterId);
analysisSharedPreferences = getApplicationContext().getSharedPreferences("AnalysisSharedPreferences",MODE_PRIVATE);
editorAnalysisPreferences = analysisSharedPreferences.edit();
subjectId = analysisSharedPreferences.getString("subjectId","");
chapterId = analysisSharedPreferences.getString("chapterId","");
subchapterId = analysisSharedPreferences.getString("subchapterId","");
bottom_sheet = findViewById(R.id.bottom_sheet);
mBehavior = BottomSheetBehavior.from(bottom_sheet);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_question_list:
showQuestionList();
return true;
}
return false;
}
});
}
private void getQuestionList() {
GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
questionsToTeacherList.clear();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
databaseReference.child("ask_teachers/students/"+firebaseAuth.getUid()+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
String dataReceived = gson.toJson(snapshot.getValue());
System.out.println(snapshot.getValue());
QuestionsToTeacher questionsToTeacher = gson.fromJson(dataReceived,QuestionsToTeacher.class);
questionsToTeacherList.add(questionsToTeacher);
}
adapterQuestionToTeacher.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showQuestionList() {
if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
final View view = getLayoutInflater().inflate(R.layout.sheet_question_list, null);
adapterQuestionToTeacher = new AdapterQuestionToTeacher(questionsToTeacherList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(LessonActivity.this);
questionListRecyclerView = view.findViewById(R.id.questionListRecyclerView);
questionListRecyclerView.setItemAnimator(new DefaultItemAnimator());
questionListRecyclerView.setNestedScrollingEnabled(false);
questionListRecyclerView.setHasFixedSize(true);
questionListRecyclerView.setLayoutManager(layoutManager);
questionListRecyclerView.setAdapter(adapterQuestionToTeacher);
adapterQuestionToTeacher.setOnClickListener(new AdapterQuestionToTeacher.OnClickListener() {
#Override
public void onItemClick(View view, QuestionsToTeacher obj, int pos) {
question_content.setVisibility(View.VISIBLE);
question_content.setText(obj.messages);
mBottomSheetDialog.dismiss();
}
});
(view.findViewById(R.id.bt_close)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBottomSheetDialog.dismiss();
}
});
mBottomSheetDialog = new BottomSheetDialog(this);
mBottomSheetDialog.setContentView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
mBottomSheetDialog.show();
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mBottomSheetDialog = null;
}
});
getQuestionList();
}
private void getLessonData(String subChapterId)
{
FirebaseDatabase.getInstance().getReference().child("lessons/"+subChapterId+"/lessons_data")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lessonDisplay = "";
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
System.out.println("lesson_inner_content");
System.out.println(snapshot.getValue());
lessonDisplay += snapshot.getValue();
}
contentWebView.getSettings().setJavaScriptEnabled(true);
contentWebView.setWebViewClient(new AppWebViewClients(progressBar));
contentWebView.loadData(String.valueOf(lessonDisplay),"text/html", "UTF-8");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class AppWebViewClients extends WebViewClient {
private ProgressBar progressBar;
public AppWebViewClients(ProgressBar progressBar) {
this.progressBar=progressBar;
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
private void initToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
chapterTitle = getIntent().getStringExtra("subChapterTitle");
setTitle(chapterTitle);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
public void openSubMenu(View v)
{
PopupMenu popup = new PopupMenu(v.getContext(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_lesson_more, popup.getMenu());
popup.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_lesson,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.askTeacher)
{
showQuestionEntryDialog();
}
if(id == R.id.practice)
{
Intent gotoPractice = new Intent(LessonActivity.this, Practice.class);
startActivity(gotoPractice);
}
if(id == R.id.pastYears)
{
Intent gotoPastYears = new Intent(LessonActivity.this, PastYears.class);
startActivity(gotoPastYears);
}
return true;
}
private void showQuestionEntryDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.dialog_ask_teacher_question_entry);
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
final EditText et_post = dialog.findViewById(R.id.et_post);
dialog.findViewById(R.id.bt_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.bt_submit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String review = et_post.getText().toString().trim();
if (review.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please fill review text", Toast.LENGTH_SHORT).show();
}else
{
submitQuestion(review, dialog);
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
}
private void submitQuestion(String message, final Dialog dialog)
{
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uuid = currentFirebaseUser.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference();
HashMap<Object,Object> messagesData = new HashMap<>();
messagesData.put("subject_id",subjectId);
messagesData.put("chapter_id",chapterId);
messagesData.put("subchapter_id",subchapterId);
messagesData.put("messages",message);
messagesData.put("status","pending");
messagesData.put("dt_added", ServerValue.TIMESTAMP);
databaseReference.child("ask_teachers/students/"+uuid+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions/").push().setValue(messagesData, new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(LessonActivity.this, "Successfully added to Ask Teacher list", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
}
onSupportNavigateUp() is not working because you're also overriding onOptionsItemSelected(). Since you return true; from onOptionsItemSelected(), you basically tell Android that you handle all item clicks by yourself and it doesn't need to do something.
You have two options now. Either call super.onOptionsItemSelected() like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.askTeacher) {
showQuestionEntryDialog();
return true; // don't forget to return true after your action
}
// ... handle all your other items
return super.onOptionsItemSelected(item);
}
Or you handle the back button click by yourself:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// navigate up on back button click
if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
return true;
}
// ... handle all your other items
return true;
}
By the way, I think overriding onSupportNavigateUp() is not needed at all. Up navigation works "out of the box" (at least for me), as long as I don't override onOptionsItemSelected() or call super.onOptionsItemSelected(item); from within it.

Get single JSON value from response Retrofit

Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." .
what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; and i fill it with a specific value from the json file from the server. here is what i tried.
Json format
"axe1": {"test1"}
The ApiInterface
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}
The MainActivity
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
String bnr;
String intt;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourdomain.com/s/ ")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject json = new JsonObject(body().toString());
Gson gson = new Gson();
Myads ad = gson.fromJson(jsonString, Myads.class);
Log.i(LOG_TAG, String.valueOf(ad.bnr));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "allQuotes");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFavorite");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "qteday");
startActivity(qteDay);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
}
So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string
You are using wrong import:
import com.android.volley.Response;
Replace it with
import retrofit2.Response;
Firstly, your JSON format is invalid, it should be {"axe1": "test1"}.
To store it you could do :
JSONObject json = new JSONObject(response.body().toString());
Log.i(LOG_TAG, json.getString("axe1"));

Passing Boolean value from fragments to activity

I am new to android development and I am trying to pass a Boolean value from dialog fragment to the activity.
the boolean value is supposed to be decided by the user(depends on which button user clicked). However, the boolean immediately turned to false without clicking any button.
I have tried various method recommended I found on internet but none of them works for me(I guess I have some part screwed up...), these method include:
-broadcasting
-implementing interface
-intent.putExtra
and below is the code that I have came up with, could anyone help me take a look? Any help is appreciated.
Stage:
package com.example.fuj.valorsafeworldbytrade;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;
public class Stage extends AppCompatActivity {
String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public void setText(){
TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
TextView pGoldText = (TextView) findViewById(R.id.player_gold);
TextView pRepText = (TextView) findViewById(R.id.player_reputation);
cpuReputation.setText(String.valueOf(basicInfo.cRep));
cpuGold.setText(String.valueOf(basicInfo.cGold));
pGoldText.setText(String.valueOf(basicInfo.pGold));
pRepText.setText(String.valueOf(basicInfo.pRep));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage);
setText();
}
protected void onStart() {
super.onStart();
stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}
public void playerChoice(View view) {
boolean deceiveEnabled;
switch (view.getId()) {
case R.id.cooperate_button:
deceiveEnabled = false;
break;
case R.id.deceive_button:
deceiveEnabled = true;
break;
default:
throw new RuntimeException("Unknown Button ID");
}
switch (stage){
case "xumo":
xuMo(deceiveEnabled);
break;
}
}
public void xuMo(boolean playerDeceiveEnabled){
boolean cpuDeceiveEnabled;
cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);
if (cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuD();
// faith changes to be amend w/ proper value, need record on the change of status
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuD();
}
}
if (!cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuC();
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuC();
}
}
if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
//to be changed
setText();
losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
//trying to show a alert dialog fragment
Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));
if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
//This is the part that I wanted to retrieve data from the user(if they want to try again or not)
basicInfo.reset();
losingDialogFragment.dismiss();
}else{
losingDialogFragment.dismiss();
}
}
setText();
// to be changed
}
}
LosingDialogFragment:
package com.example.fuj.valorsafeworldbytrade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by fuj on 20/1/2017.
*/
public class LosingDialogFragment extends DialogFragment{
public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;
Intent intent = new Intent();
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
//the following code is used to set the boolean value after the user click the button
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgainEnabled = true;
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgainEnabled = false;
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
}
I am also sorry that I am not the best with English, if any things is not clear or not polite because of my poor English, please kindly let me know. I apologize in advance for any mistakes I have made.
It's because you check the value of tryAgainEnabled exactly right after showing the Dialog. Dialog starts Asynchronously, It means that it starts in diffrent Thread and your current thread doesn't wait for dismissing Dialog, So this line of your code if(losingDialogFragment.tryAgainEnabled){ runs exactly after you show dialog, befor you set value to tryAgainEnabled. Because the default value of boolean is always false, you will get false everytime.
I suggest that use listener for this:
Dialog:
public class LosingDialogFragment extends DialogFragment {
public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;
Intent intent = new Intent();
private View.OnClickListener onTryAgainButtonClickLisnter;
private View.OnClickListener onGiveUpButtonClickLisnter;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onTryAgainButtonClickLisnter!=null)
onTryAgainButtonClickLisnter.onClick(v);
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onGiveUpButtonClickLisnter!=null)
onGiveUpButtonClickLisnter.onClick(v);
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
public void setOnTryAgainButtonClickLisnter(View.OnClickListener onTryAgainButtonClickLisnter) {
this.onTryAgainButtonClickLisnter = onTryAgainButtonClickLisnter;
}
public void setOnGiveUpButtonClickLisnter(View.OnClickListener onGiveUpButtonClickLisnter) {
this.onGiveUpButtonClickLisnter = onGiveUpButtonClickLisnter;
}
}
In your activity call dialog like this:
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
losingDialogFragment.setOnTryAgainButtonClickLisnter(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgain();
losingDialogFragment.dismiss();
}
});
losingDialogFragment.setOnGiveUpButtonClickLisnter(new View.OnClickListener() {
#Override
public void onClick(View v) {
giveUp();
losingDialogFragment.dismiss();
}
});
losingDialogFragment.show(fragmentManager, "");
Declare public boolean tryAgainEnabled; in your Stage Activity and youd can update that variable using ((Stage)context).tryAgainEnabled.
package com.example.fuj.valorsafeworldbytrade;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;
public class Stage extends AppCompatActivity {
String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public boolean tryAgainEnabled;
public void setText(){
TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
TextView pGoldText = (TextView) findViewById(R.id.player_gold);
TextView pRepText = (TextView) findViewById(R.id.player_reputation);
cpuReputation.setText(String.valueOf(basicInfo.cRep));
cpuGold.setText(String.valueOf(basicInfo.cGold));
pGoldText.setText(String.valueOf(basicInfo.pGold));
pRepText.setText(String.valueOf(basicInfo.pRep));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage);
setText();
}
protected void onStart() {
super.onStart();
stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}
public void playerChoice(View view) {
boolean deceiveEnabled;
switch (view.getId()) {
case R.id.cooperate_button:
deceiveEnabled = false;
break;
case R.id.deceive_button:
deceiveEnabled = true;
break;
default:
throw new RuntimeException("Unknown Button ID");
}
switch (stage){
case "xumo":
xuMo(deceiveEnabled);
break;
}
}
public void xuMo(boolean playerDeceiveEnabled){
boolean cpuDeceiveEnabled;
cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);
if (cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuD();
// faith changes to be amend w/ proper value, need record on the change of status
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuD();
}
}
if (!cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuC();
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuC();
}
}
if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
//to be changed
setText();
losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));
if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
basicInfo.reset();
losingDialogFragment.dismiss();
}else{
losingDialogFragment.dismiss();
}
}
setText();
// to be changed
}
}
And in Fragment
package com.example.fuj.valorsafeworldbytrade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by fuj on 20/1/2017.
*/
public class LosingDialogFragment extends DialogFragment{
public static final String LOSING_FRAGMENT = "LOSING";
Context context;
Intent intent = new Intent();
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Stage)context).tryAgainEnabled = true;
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Stage)context).tryAgainEnabled = false;
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
}

Eclipse says onClickListener variable in Android cannot be resolved, but has been created?

In my project i several onClick listeners, and all of them are fine, but one, i can not find and error in the code, if i delete the code and retype it and save it, it is fine without errors, if i close and eclipse and comeback later, variable cant be resolved again.
This is where it cant be resolved in the code:
Button webButton = (Button) newStockRow.findViewById(R.id.webButton);
webButton.setOnClickListener(getStockFromWebClickListener);
and this is how i create it:
public OnClickListener getStockFromWebClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
TableRow tableR = (TableRow) arg0.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
Intent getStockWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(stockURL));
startActivity(getStockWebPage);
}
};
Code for full File:
package com.gscore.quotestock;
import java.util.Arrays;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class StockQ extends Activity {
public final static String STOCK_SYMBOL = "com.gscore.quotestock.STOCK";
private SharedPreferences stockSymbolsEntered;
private TableLayout stockTableScrollView;
private EditText stockSymbolET;
Button enterStockSymbolButton;
Button deleteStocksButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stock_q);
// Get user stock list
stockSymbolsEntered = getSharedPreferences("stockList", MODE_PRIVATE);
// Initialize UI components
stockTableScrollView = (TableLayout) findViewById(R.id.stockTableLayout);
stockSymbolET = (EditText) findViewById(R.id.stockSymbolEditText);
enterStockSymbolButton= (Button) findViewById(R.id.enterButton);
deleteStocksButton= (Button) findViewById(R.id.deleteAllButton);
// Set ClickListeners
enterStockSymbolButton.setOnClickListener(enterButtonClickListener);
deleteStocksButton.setOnClickListener(deleteButtonClickListener);
updateSavedStockList(null);
}
private void updateSavedStockList(String newStockSymbol){
String[] stocks = stockSymbolsEntered.getAll().keySet().toArray(new String[0]);
Arrays.sort(stocks, String.CASE_INSENSITIVE_ORDER);
if (newStockSymbol != null){
insertStockInStockTable(newStockSymbol, Arrays.binarySearch(stocks, newStockSymbol));
} else {
for(int i = 0; i < stocks.length; i++){
insertStockInStockTable(stocks[i], i);
}
}
}
private void saveStockSymbol(String newStock){
String isTheStockNew = stockSymbolsEntered.getString(newStock, null);
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.putString(newStock, newStock);
preferencesEditor.commit();
if(isTheStockNew == null){
updateSavedStockList(newStock);
}
}
private void insertStockInStockTable(String stock, int arrayIndex){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newStockRow = inflater.inflate(R.layout.stock_quote_row, null);
TextView newStockTextView = (TextView) newStockRow.findViewById(R.id.stockSymbolTextView);
newStockTextView.setText(stock);
Button stockQuoteButton = (Button) newStockRow.findViewById(R.id.stockQuoteButton);
stockQuoteButton.setOnClickListener(getStockActivityListener);
Button webButton = (Button) newStockRow.findViewById(R.id.webButton);
webButton.setOnClickListener(getStockFromWebClickListener);
stockTableScrollView.addView(newStockRow, arrayIndex);
}
public OnClickListener enterButtonClickListener= new OnClickListener(){
#Override
public void onClick(View v) {
if(stockSymbolET.getText().length() > 0){
saveStockSymbol(stockSymbolET.getText().toString());
stockSymbolET.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(stockSymbolET.getWindowToken(), 0);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(StockQ.this);
builder.setTitle(R.string.invalid_stock_symbol);
builder.setPositiveButton(R.string.ok, null);
builder.setMessage(R.string.missing_stock_symbol);
AlertDialog theAlertDialog = builder.create();
theAlertDialog.show();
}
}
};
private void deleteAllStocks(){
stockTableScrollView.removeAllViews();
}
public OnClickListener deleteButtonClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
deleteAllStocks();
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.clear();
preferencesEditor.commit();
}
};
public OnClickListener getStockActivityListener = new OnClickListener(){
#Override
public void onClick(View v) {
TableRow tableR = (TableRow) v.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
Intent intent = new Intent(StockQ.this, StockInfoActivity.class);
intent.putExtra(STOCK_SYMBOL, stockSymbol);
startActivity(intent);
}
};
public OnClickListener getStockFromWebClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
TableRow tableR = (TableRow) arg0.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
Intent getStockWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(stockURL));
startActivity(getStockWebPage);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.stock_q, menu);
return true;
}
}
That's indeed an annoying problem with importing an inner class (or interface) on Eclipse.
What you have to do is instead of:
new OnClickListener()
Write:
new View.OnClickListener()
And make sure that android.view.View is imported.

Categories

Resources