I have an app with several activities. The up button created by
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
works on all the activities except for one. I've checked the manifest and I can see the parent is set correctly.
Code from activity where the up button doesn't work:
package com.icenibees.apiarymanager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.icenibees.apiarymanager.sample.SampleDataProvider;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.UUID;
public class ApiaryDetails extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
public static final String LOGTAG="APIARYMANAGER";
public String apiaryIDDelete = "";
AMDBDataSource mDataSource;
EditText updateApiaryNameInput;
EditText updateApiaryLocationInput;
EditText updateApiaryDescriptionInput;
EditText updateApiarySetupDateInput;
EditText updateApiaryNotesInput;
String updateApiaryidInput;
private TextView tvName, tvDescription, tvLocation, tvSetupDate, tvNotes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apiary_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDataSource = new AMDBDataSource(this);
mDataSource.open();
final AMClasses.Apiary updateApiary = new AMClasses.Apiary();
// String apiaryId = getIntent().getExtras().getString(ApiaryItemAdapter.APIARY_ID_KEY);
// AMClasses.Apiary item = SampleDataProvider.apiaryItemMap.get(apiaryId);
final AMClasses.Apiary item = getIntent().getExtras().getParcelable(ApiaryItemAdapter.APIARY_RECORD);
if (item == null) {
throw new AssertionError("No data record received!?!");
}
tvName = (TextView) findViewById(R.id.tvApiaryName);
tvLocation = (TextView) findViewById(R.id.tvApiaryLocation);
tvSetupDate = (TextView) findViewById(R.id.tvApiarySetupDate);
tvDescription = (TextView) findViewById(R.id.tvApiaryDescription);
tvNotes = (TextView) findViewById(R.id.tvApiaryNotes);
tvName.setText(item.getApiaryname());
tvLocation.setText(item.getApiarylocation());
tvSetupDate.setText(item.getApiarysetupdate());
tvDescription.setText(item.getApiarydescription());
tvNotes.setText(item.getApiarynotes());
apiaryIDDelete = item.getApiaryid();
Button updateApiaryButton = (Button) findViewById(R.id.btnUpdateApiary);
updateApiaryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
updateApiaryidInput = item.getApiaryid();
updateApiaryNameInput = (EditText) findViewById(R.id.tvApiaryName);
updateApiaryLocationInput = (EditText) findViewById(R.id.tvApiaryLocation);
updateApiaryDescriptionInput = (EditText) findViewById(R.id.tvApiaryDescription);
updateApiarySetupDateInput = (EditText) findViewById(R.id.tvApiarySetupDate);
updateApiaryNotesInput = (EditText) findViewById(R.id.tvApiaryNotes);
//updateApiary.setApiaryid(UUID.randomUUID().toString());
updateApiary.setApiaryid(updateApiaryidInput);
updateApiary.setApiaryname(updateApiaryNameInput.getText().toString());
updateApiary.setApiarylocation(updateApiaryLocationInput.getText().toString());
updateApiary.setApiarydescription(updateApiaryDescriptionInput.getText().toString());
updateApiary.setApiarysetupdate(updateApiarySetupDateInput.getText().toString());
updateApiary.setApiarynotes(updateApiaryNotesInput.getText().toString());
Log.i(LOGTAG, "Apiary ID to be updated: " + updateApiary.getApiaryid());
Log.i(LOGTAG, "Update Apiary Name: " + updateApiary.getApiaryname());
Log.i(LOGTAG, "Update Apiary Location: " + updateApiary.getApiarylocation());
Log.i(LOGTAG, "Update Apiary Description: " + updateApiary.getApiarydescription());
Log.i(LOGTAG, "Update Apiary Setup Date: " + updateApiary.getApiarysetupdate());
Log.i(LOGTAG, "Update Apiary Notes: " + updateApiary.getApiarynotes());
mDataSource.updateApiary2DB(updateApiary);
Snackbar.make(findViewById(android.R.id.content),
"Apiary updated", Snackbar.LENGTH_LONG)
.setAction("Action",null).show();
thread.start();
}
}
);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
//ACTIVITY TIMER CLOSER
Thread thread = new Thread(){
#Override
public void run() {
try {
Thread.sleep(2500); // As I am using LENGTH_LONG in Toast
ApiaryDetails.this.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//DELETE MENU
#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_edit_apiary, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// SETTINGS MENU CASE STATEMENTS
int id = item.getItemId();
switch (id) {
case R.id.action_apiary_delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.app_name);
builder.setMessage("Please confirm you want to delete the apiary?");
builder.setIcon(R.drawable.ic_action_delete);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
mDataSource.deleteApiary(apiaryIDDelete); // Delete Apiary Row
Snackbar.make(findViewById(android.R.id.content),
"Apiary deleted", Snackbar.LENGTH_LONG)
.setAction("Action",null).show();
thread.start();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
}
return true;
}
//DATE PICKER CODE
public void datePickerEditApiary(View view){
NewApiary.DatePickerFragment fragment = new NewApiary.DatePickerFragment();
fragment.show(getSupportFragmentManager(), "date");
}
public void setDate(final Calendar calendar){
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
((TextView) findViewById(R.id.tvApiarySetupDate)).setText(dateFormat.format(calendar.getTime()));
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar cal = new GregorianCalendar(year, month, dayOfMonth);
setDate(cal);
}
public static class DatePickerFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(),
(DatePickerDialog.OnDateSetListener) getActivity(),year, month, day);
}
}
}
Manifest:
<activity
android:name=".EditApiary"
android:label="#string/title_activity_edit__apiary"
android:parentActivityName=".ApiarySetup"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.ApiarySetup" />
</activity>
<activity
android:name=".ApiaryDetails"
android:label="#string/title_activity_apiary_details"
android:parentActivityName=".EditApiary"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.EditApiary" />
</activity>
<activity
android:name=".EditHive"
android:label="#string/title_activity_edit_hive"
android:parentActivityName=".ApiarySetup"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.ApiarySetup" />
</activity>
I see
getSupportActionBar()
So, you are using AppCompatActivity instance
Probably, you should override onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
finish();
return true;
//Or another code here
}
return false;
}
Also, you can add parent activity inside AndroidManifest.xml like this:
API 16+
<activity
....
android:parentActivityName="activity_class_name" />
Related
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
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"));
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have 1 problem and Who can help me?.
I have 1 Activity run when start App
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
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.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.Serializable;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
Button btnLogin, btnRegister, btnFindPassword;
EditText editUsername, editPassword;
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
btnLogin = (Button) findViewById(R.id.button_login);
btnRegister = (Button) findViewById(R.id.button_register);
btnFindPassword = (Button) findViewById(R.id.button_findPassword);
editUsername = (EditText) findViewById(R.id.editText_username);
editPassword = (EditText) findViewById(R.id.editText_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarActivity);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Đăng nhập");
Login();
Register();
FindPassword();
}
public void Login(){
btnLogin.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = db.getDataTableUser();
int temp = 1;
if (res.getCount() == 0) {
showMessage("Error", "Tài khoản không tồn tại");
return;
}
while (res.moveToNext()) {
String username, password, idUser;
idUser = res.getString(0);
username = res.getString(1);
password = res.getString(2);
if (editUsername.getText().toString().equals(username) == true&&editPassword.getText().toString().equals(password) == true) {
doOpenManagePage(idUser);
temp = 0;
break;
}
}
if (temp==1){
showMessage("Error", "Account does not exist");
}
}
}
);
}
public void Register(){
btnRegister.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenRegister();
}
}
);
}
public void FindPassword(){
btnFindPassword.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenFindPasswordStep1();
}
}
);
}
public void doOpenRegister(){
Intent newIntent = new Intent(this, Register.class);
startActivity(newIntent);
}
public void doOpenFindPasswordStep1(){
Intent newIntent = new Intent(this, FindPasswordStep1.class);
startActivity(newIntent);
}
public void doOpenManagePage(String idUser){
Intent newIntent = new Intent(this, ManagePage.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.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_manage_page, 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.action_logout) {
return true;
}
else if (id==R.id.action_search){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then it send IdUser to this Activity
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class ManagePage extends AppCompatActivity{
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_page);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_note);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doOpenInsertNote(idUser);
}
});
}
public String getIdUser(){
Bundle extras = getIntent().getExtras();
String idUser = extras.getString("IdUser");
return idUser;
}
public void doOpenInsertNote(String idUser){
Intent newIntent = new Intent(this, InsertNote.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
}
When i run it 1st time, this app is ok, it can go to next Activity
package com.example.khuatduytan.doantotnghiep;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
public class InsertNote extends AppCompatActivity implements View.OnClickListener {
private ImageButton insertDate;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et, content_InsertNote, money_InsertNote;
private Button btnSubmitNote, btnCancelNote;
private Spinner SelectTypeNote;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
insertDate = (ImageButton) findViewById(R.id.dateInsert);
cal = Calendar.getInstance();
et = (EditText) findViewById(R.id.dateInsert_editText);
btnSubmitNote = (Button) findViewById(R.id.insertNote);
btnCancelNote = (Button) findViewById(R.id.cancelNote);
content_InsertNote = (EditText) findViewById(R.id.noiDung);
money_InsertNote = (EditText) findViewById(R.id.soTien);
SelectTypeNote = (Spinner) findViewById(R.id.loai);
db = new DatabaseHelper(this);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
insertDate.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
setBtnSubmitNote(idUser);
setBtnCancelNote();
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / " + selectedYear);
}
};
private void setBtnSubmitNote(final String idUser){
btnSubmitNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmDialog(idUser);
}
});
}
private void setBtnCancelNote(){
Intent newIntent = new Intent(this, ManagePage.class);
startActivity(newIntent);
}
private void confirmDialog(final String idUser) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String date = null, content = null, money = null, TypeNote_Selected;
int Type_Note = 0, id_User;
id_User = Integer.parseInt(idUser);
date = et.getText().toString();
content = content_InsertNote.getText().toString();
money = money_InsertNote.getText().toString();
TypeNote_Selected = SelectTypeNote.getSelectedItem().toString();
if(TypeNote_Selected.equals("Thu")){
Type_Note = 0;
} else{
Type_Note = 1;
}
if(date.equals("")||content.equals("")||money.equals("")){
Toast.makeText(InsertNote.this, "Bạn chưa nhập đủ dữ liệu", Toast.LENGTH_LONG).show();
}
else {
long isInserted = db.insertNoteTable(date, content, Type_Note, money, id_User);
if (isInserted == -1) {
Toast.makeText(InsertNote.this, "Thêm ghi chú không thành công", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(InsertNote.this, "Thêm ghi chú thành công", Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.show();
}
}
`
But when i run it second time, When i click button to open Activity
InsertNote, I receive a error
03-26 16:12:32.161 2614-2614/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khuatduytan.doantotnghiep/com.example.khuatduytan.doantotnghiep.ManagePage}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.khuatduytan.doantotnghiep.ManagePage.onCreate(ManagePage.java:21)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I tried to print what i send from Activity Main to Activity ManagePage by Toast, it display exactly what i want to send.
But i dont know why this error display.
Can you help me?
Sorry about my English
You call setBtnCancelNote() method in the onCreate() method of your InsertNote activity. so as soon as InsertNote starts it tries to launch the ManagePage activity.
The problem is your ManagePage activity expects the value IdUser in the bundle received from the intent. But you do not pass this value to ManagePage activity when you start it from InsertNote activity.
You probably want to add this line to your setBtncancelNote() method in InsertPage activity -
newIntent.putExtra("IdUser", //The Values here);
If you pass this value then ManageNote will not crash.
please add more info like line numbers, otherwise its difficult to debug it remotely ..
Anyway, my guess is you have to check for null pointers when you do stuff like getIntent().getExtras()
just put some breakpoints there, and step by step and you'll figure it out
The apk is a memo pad or something like that. First you can put the title and then the note and if you press the button "Save" the note is saved and it saves in database. And if you press the button "Notes", you can view a list with all notes saved in database and you can select all notes and in the top of screen, you can read how many notes are selected. Ok, it's fine but I need remove notes when the are selected and I press the button with bin icon in the top menu.
The code:
package com.example.u2tarea3;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AnotacionesOpenHelperSingleton extends SQLiteOpenHelper {
private static AnotacionesOpenHelperSingleton instancia = null;
private Context mCtx;
public static AnotacionesOpenHelperSingleton getInstance(Context ctx){
if(instancia == null){
instancia = new AnotacionesOpenHelperSingleton(ctx);
}
return instancia;
}
private AnotacionesOpenHelperSingleton(Context ctx) {
super(ctx,"anotaciones",null,2);
}
#Override
public void onCreate(SQLiteDatabase bd) {
StringBuilder sql = new StringBuilder();
sql.append("create table IF NOT EXISTS anotaciones (");
sql.append("_id integer primary key autoincrement,");
sql.append("texto text not null,");
sql.append("fecha text not null)");
bd.execSQL(sql.toString());
}
#Override
public void onUpgrade(SQLiteDatabase bd, int oldVersion, int newVersion) {
//bd.execSQL("drop table anotaciones");
bd.execSQL("ALTER TABLE anotaciones ADD titulo text");
bd.execSQL("UPDATE anotaciones SET titulo = 'sin titulo' WHERE titulo is NULL");
onCreate(bd);
}
}
package com.example.u2tarea3;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText editText;
EditText editTitulo;
Button btnGuardar;
Button btnAnotaciones;
SQLiteDatabase bd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton.getInstance(this);
bd = openHelperSingleton.getWritableDatabase();
editText = (EditText)findViewById(R.id.editText);
editTitulo = (EditText) findViewById(R.id.editTitulo);
btnGuardar = (Button) findViewById(R.id.btnGuardar);
btnGuardar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
ContentValues valores = new ContentValues();
valores.put("texto", editText.getText().toString());
valores.put("fecha", sdf.format(c.getTime()));
valores.put("titulo", editTitulo.getText().toString());
bd.insert("anotaciones", null, valores);
editText.setText("");
}
});
btnAnotaciones = (Button) findViewById(R.id.btnAnotaciones);
btnAnotaciones.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,ListAnotaciones.class);
startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
}
package com.example.u2tarea3;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class ListAnotaciones extends ListActivity {
SQLiteDatabase bd;
Cursor cursor;
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton
.getInstance(this);
int cont = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelperSingleton.getReadableDatabase();
cursor = bd.rawQuery("SELECT * FROM anotaciones", null);
try {
String[] from = { "fecha", "titulo" };
int[] to = { R.id.anotacionesFecha, R.id.anotacionesTitulo };
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.anotacion, cursor, from, to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
MenuInflater inflater = arg0.getMenuInflater();
inflater.inflate(R.menu.anotaciones, arg1);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch(arg1.getItemId()){
case R.id.delete_id:
//arg0.finish();
default:
break;
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
int seleccionados = getListView()
.getCheckedItemCount();
switch (seleccionados) {
case 1:
mode.setTitle("1 nota seleccionada");
break;
default:
mode.setTitle("" + seleccionados
+ " notas seleccionadas");
break;
}
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}
}
You'll need to remove the note from the database and the ListView, and then call ListViewAdapter.notifyDataSetChanged()
To delete from the datasource have a method in the class that deals with the datasource:
/**
* Delete a note given an id.
* #param id Key used to identify a note to delete.
*/
public void deleteNote(long id) {
System.out.println("Note deleted with id: " + id);
database.delete(ListOpenHelper.TABLE_MEMOS,
ListOpenHelper.ID + " = " + id,
null);
}
To refresh the ListView you could simply clear and re-add all the Views via the ListViewAdapter:
// Refresh adapter view with new data
ListAdapter.clear();
ListAdapter.addAll(dataSource.getAllNotes());
ListAdapter.notifyDataSetChanged();
Alternatively remove only a single element from the ListViewAdapter and call notifyDataSetChanged();.
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;