ListView displays data twice - android

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

Related

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.

First message is duplicated

I've been working on a messaging app and within the group and private chat, the first message duplicates and then when another message is sent, it's hidden behind the duplicated text until another one is sent and then so on. Can anybody help me with this problem? I'm using Quickblox as a database
ChatMessage Class
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.liftersheaven.messaging.Adapter.ChatMessageAdapter;
import com.liftersheaven.messaging.Common.Common;
import com.liftersheaven.messaging.Holder.QBChatMessagesHolder;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBIncomingMessagesManager;
import com.quickblox.chat.QBRestChatService;
import com.quickblox.chat.exception.QBChatException;
import com.quickblox.chat.listeners.QBChatDialogMessageListener;
import com.quickblox.chat.model.QBChatDialog;
import com.quickblox.chat.model.QBChatMessage;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.chat.request.QBDialogRequestBuilder;
import com.quickblox.chat.request.QBMessageGetBuilder;
import com.quickblox.chat.request.QBMessageUpdateBuilder;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import java.util.ArrayList;
public class ChatMessage extends AppCompatActivity implements
QBChatDialogMessageListener{
QBChatDialog qbChatDialog;
ListView lstChatMessages;
ImageButton submitButton;
EditText edtContent;
ChatMessageAdapter adapter;
int contextMenuIndexClicked = -1;
boolean isEditMode = false;
QBChatMessage editMessage;
Toolbar toolbar;
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()){
case R.id.chat_group_edit_name:
editNameGroup();
break;
case R.id.chat_group_add_user:
addUser();
break;
case R.id.chat_group_remove_user:
removeUser();
break;
}
return true;
}
private void removeUser() {
Intent intent = new Intent(this,ListUsers.class);
intent.putExtra(Common.UPDATE_DIALOG_EXTRA, qbChatDialog);
intent.putExtra(Common.UPDATE_MODE, Common.UPDATE_REMOVE_MODE);
startActivity(intent);
}
private void addUser() {
Intent intent = new Intent(this,ListUsers.class);
intent.putExtra(Common.UPDATE_DIALOG_EXTRA, qbChatDialog);
intent.putExtra(Common.UPDATE_MODE,Common.UPDATE_ADD_MODE);
startActivity(intent);
}
private void editNameGroup() {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.dialog_edit_group_layout, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(view);
final EditText newName = (EditText) view.findViewById(R.id.edt_group_name);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
qbChatDialog.setName(newName.getText().toString());
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(ChatMessage.this, "Group name edited", Toast.LENGTH_SHORT);
toolbar.setTitle(qbChatDialog.getName());
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(getBaseContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (qbChatDialog.getType() == QBDialogType.GROUP || qbChatDialog.getType() == QBDialogType.PUBLIC_GROUP)
getMenuInflater().inflate(R.menu.chat_message_group_menu, menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
contextMenuIndexClicked = info.position;
switch (item.getItemId()){
case R.id.chat_message_update:
updateMessage();
break;
case R.id.chat_message_delete:
deleteMessage();
break;
}
return true;
}
private void deleteMessage() {
final ProgressDialog deleteDialog = new ProgressDialog(ChatMessage.this);
deleteDialog.setMessage("Please wait...");
deleteDialog.show();
editMessage = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatDialog.getDialogId())
.get(contextMenuIndexClicked);
QBRestChatService.deleteMessage(editMessage.getId(),false).performAsync(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
retrieveAllMessage();
deleteDialog.dismiss();
}
#Override
public void onError(QBResponseException e) {
}
});
}
private void updateMessage() {
editMessage = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatDialog.getDialogId())
.get(contextMenuIndexClicked);
edtContent.setText(editMessage.getBody());
isEditMode = true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
getMenuInflater().inflate(R.menu.chat_message_content_menu, menu);
}
#Override
protected void onDestroy(){
super.onDestroy();
qbChatDialog.removeMessageListrener(this);
}
#Override
protected void onStop(){
super.onStop();
qbChatDialog.removeMessageListrener(this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_message);
initViews();
initChatDialogs();
retrieveAllMessage();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!edtContent.getText().toString().isEmpty()){
if (!isEditMode) {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(edtContent.getText().toString());
chatMessage.setSenderId(QBChatService.getInstance().getUser().getId());
chatMessage.setSaveToHistory(true);
try {
qbChatDialog.sendMessage(chatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
if (qbChatDialog.getType() == QBDialogType.PRIVATE){
QBChatMessagesHolder.getInstance().putMessage(qbChatDialog.getDialogId(),chatMessage);
ArrayList<QBChatMessage> messages = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(chatMessage.getDialogId());
adapter = new ChatMessageAdapter(getBaseContext(),messages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
edtContent.setText("");
edtContent.setFocusable(true);
}else
{
final ProgressDialog updateDialog = new ProgressDialog(ChatMessage.this);
updateDialog.setMessage("Please wait...");
updateDialog.show();
QBMessageUpdateBuilder messageUpdateBuilder = new QBMessageUpdateBuilder();
messageUpdateBuilder.updateText(edtContent.getText().toString()).markDelivered().markRead();
QBRestChatService.updateMessage(editMessage.getId(),qbChatDialog.getDialogId(),messageUpdateBuilder)
.performAsync(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
retrieveAllMessage();
isEditMode = false;
updateDialog.dismiss();
edtContent.setText("");
edtContent.setFocusable(true);
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(getBaseContext(),""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
}
private void retrieveAllMessage() {
QBMessageGetBuilder messageGetBuilder = new QBMessageGetBuilder();
messageGetBuilder.setLimit(500);
if(qbChatDialog != null){
QBRestChatService.getDialogMessages(qbChatDialog,messageGetBuilder).performAsync(new QBEntityCallback<ArrayList<QBChatMessage>>() {
#Override
public void onSuccess(ArrayList<QBChatMessage> qbChatMessages, Bundle bundle) {
QBChatMessagesHolder.getInstance().putMessages(qbChatDialog.getDialogId(),qbChatMessages);
adapter = new ChatMessageAdapter(getBaseContext(),qbChatMessages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
}
});
}
}
private void initChatDialogs() {
qbChatDialog = (QBChatDialog)getIntent().getSerializableExtra(Common.DIALOG_EXTRA);
qbChatDialog.initForChat(QBChatService.getInstance());
QBIncomingMessagesManager incomingMessage = QBChatService.getInstance().getIncomingMessagesManager();
incomingMessage.addDialogMessageListener(new QBChatDialogMessageListener() {
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
}
#Override
public void processError(String s, QBChatException e, QBChatMessage qbChatMessage, Integer integer) {
}
});
if (qbChatDialog.getType() == QBDialogType.PUBLIC_GROUP || qbChatDialog.getType() == QBDialogType.GROUP){
DiscussionHistory discussionHistory = new DiscussionHistory();
discussionHistory.setMaxStanzas(0);
qbChatDialog.join(discussionHistory, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
}
#Override
public void onError(QBResponseException e) {
Log.d("ERROR", ""+e.getMessage());
}
});
}
qbChatDialog.addMessageListener(this);
toolbar.setTitle(qbChatDialog.getName());
setSupportActionBar(toolbar);
}
private void initViews() {
lstChatMessages = (ListView)findViewById(R.id.messages_list);
submitButton = (ImageButton)findViewById(R.id.send);
edtContent = (EditText)findViewById(R.id.edt_content);
registerForContextMenu(lstChatMessages);
toolbar = (Toolbar)findViewById(R.id.chatmessage_toolbar);
}
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
QBChatMessagesHolder.getInstance().putMessage(qbChatMessage.getDialogId(),qbChatMessage);
ArrayList<QBChatMessage> messages = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatMessage.getDialogId());
adapter = new ChatMessageAdapter(getBaseContext(),messages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void processError(String s, QBChatException e, QBChatMessage qbChatMessage, Integer integer) {
Log.e("ERROR",""+e.getMessage());
}
}
ChatMessageAdapter Class
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.github.library.bubbleview.BubbleTextView;
import com.liftersheaven.messaging.Holder.QBUsersHolder;
import com.liftersheaven.messaging.R;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.model.QBChatMessage;
import java.util.ArrayList;
public class ChatMessageAdapter extends BaseAdapter {
private Context context;
private ArrayList<QBChatMessage> qbChatMessages;
public ChatMessageAdapter(Context context, ArrayList<QBChatMessage> qbChatMessages){
this.context = context;
this.qbChatMessages = qbChatMessages;
}
#Override
public int getCount() {
return qbChatMessages.size();
}
#Override
public Object getItem(int position) {
return qbChatMessages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (qbChatMessages.get(position).getSenderId().equals(QBChatService.getInstance().getUser().getId())){
view = inflater.inflate(R.layout.list_message_send, null);
BubbleTextView bubbleTextView = (BubbleTextView)view.findViewById(R.id.message_content);
bubbleTextView.setText(qbChatMessages.get(position).getBody());
}
else{
view = inflater.inflate(R.layout.list_recieve_message, null);
BubbleTextView bubbleTextView = (BubbleTextView)view.findViewById(R.id.message_recieve);
bubbleTextView.setText(qbChatMessages.get(position).getBody());
TextView txtName = (TextView)view.findViewById(R.id.message_user);
txtName.setText(QBUsersHolder.getInstance().getUserById(qbChatMessages.get(position).getSenderId()).getFullName());
}
}
return view;
}
}
QBChatMessagesHolder Class
import com.quickblox.chat.model.QBChatMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class QBChatMessagesHolder {
private static QBChatMessagesHolder instance;
private HashMap<String,ArrayList<QBChatMessage>> qbChatMessageArray;
public static synchronized QBChatMessagesHolder getInstance(){
QBChatMessagesHolder qbChatMessagesHolder;
synchronized (QBChatMessagesHolder.class){
if (instance == null)
instance = new QBChatMessagesHolder();
qbChatMessagesHolder = instance;
}
return qbChatMessagesHolder;
}
private QBChatMessagesHolder(){
this.qbChatMessageArray = new HashMap<>();
}
public void putMessages(String dialogId,ArrayList<QBChatMessage> qbChatMessages){
this.qbChatMessageArray.put(dialogId,qbChatMessages);
}
public void putMessage(String dialogId,QBChatMessage qbChatMessage){
List<QBChatMessage> lstResult = (List)this.qbChatMessageArray.get(dialogId);
lstResult.add(qbChatMessage);
ArrayList<QBChatMessage> lstAdded = new ArrayList(lstResult.size());
lstAdded.addAll(lstResult);
putMessages(dialogId, lstAdded);
}
public ArrayList<QBChatMessage> getChatMessagesByDialogId(String dialogId){
return (ArrayList<QBChatMessage>)this.qbChatMessageArray.get(dialogId);
}
}

First item displayed two times in the Listview Android

Hi I already posted the question before but again same question with details ,
I created a a NavigationDrawer in the app , Its working fine but the problem is that in FolderActivity the first Item as a title displayed two time in navigation drawer, I posted the code below please suggest me solution if any...!
navigation_drawer_class.java
package com.abc;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.*;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.BaseBundle;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class navigation_drawer_class extends Activity
{
private static final int Copy = 0;
int a =0;
public static FrameLayout frameLayout;
TextView mytextview;
public static ListView mDrawerList;
public DrawerLayout mDrawerLayout;
String Fullname;
protected String[] listArray = {"Home","Queue","Inbox","Create Ticket","Search","Clients","App settings"};
protected static int position;
private static boolean isLaunch = true;
JSONObject post_details_obj,post_obj;
public static String FIRST_NAME="first_name",LAST_NAME="last_name",PROFILE_IMAGE="image_name";
JSONArray staff_data_array;
private ActionBarDrawerToggle actionBarDrawerToggle;
Operation op=new Operation();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setHomeAsUpIndicator(R.drawable.crop3);//THIS ONE FOR THE DRAWER LOGO
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listArray));
View header = (View)getLayoutInflater().inflate(R.layout.headerview_nav_drawer,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText("");
new getname().execute();
mDrawerList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
position -= mDrawerList.getHeaderViewsCount();//THIS ONE FOR THE FIRST ITEM AS TITLE
openActivity(position);
}
});
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, // host Activity
mDrawerLayout, // DrawerLayout object
R.drawable.ic_launcher, // nav drawer image to replace 'Up' caret
R.string.open_drawer, // "open drawer" description for accessibility
R.string.close_drawer) // "close drawer" description for accessibility
{
#Override
public void onDrawerClosed(View drawerView)
{
getActionBar().setTitle(listArray[position]);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState)
{
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
if(isLaunch){
isLaunch = false;
openActivity(0);
}
}
protected void openActivity(int position) {
//mDrawerList.setItemChecked(position, true);
//setTitle(listArray[position]);
mDrawerLayout.closeDrawer(mDrawerList);
navigation_drawer_class.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
startActivity(new Intent(this, Folders.class));
break;
case 1:
Intent i=new Intent(navigation_drawer_class.this,G.class);
startActivity(i);
break;
case 2:
Intent inbox=new Intent(navigation_drawer_class.this,E.class);
startActivity(inbox);
break;
case 3:
startActivity(new Intent(this, S.class));
break;
case 4:
startActivity(new Intent(this, A.class));
break;
case 5:
startActivity(new Intent(this, P.class));
break;
case 6:
startActivity(new Intent(this, V.class));
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
switch (item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/* We can override onBackPressed method to toggle navigation drawer*/
#Override
public void onBackPressed()
{
if(mDrawerLayout.isDrawerOpen(mDrawerList))
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
mDrawerLayout.openDrawer(mDrawerList);
}
}
private class getname extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(navigation_drawer_class.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
String STAFF_URL=op.getUrl(getApplicationContext(),"staff","get_staff_details","");
staff_data_array = JSONfunctions.getJSONfromURL(STAFF_URL+"&vis_encode=json",navigation_drawer_class.this);
return staff_data_array;
}
#Override
public void onPostExecute(JSONArray staff_data_array)
{
super.onPostExecute(staff_data_array);
String staff_data_result =staff_data_array.toString();
try {
post_obj = staff_data_array.getJSONObject(0);
String fname=post_obj.getString(FIRST_NAME);
String lname=post_obj.getString(LAST_NAME);
String image=post_obj.getString(PROFILE_IMAGE);
String fullname =fname;
if(fullname=="")
{
fullname="Admin";
}
Fullname="Welcome "+fullname;
View header = (View)getLayoutInflater().inflate(R.layout.headerview_nav_drawer,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText(Fullname);
headerValue.setCompoundDrawablesWithIntrinsicBounds(R.drawable.default_img,0,0,0);
mDrawerList.addHeaderView(headerValue, null, false);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}
}
Folders.java
package com.abc;
import java.util.ArrayList;
import android.R.*;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Folders extends navigation_drawer_class {
static final String NEW="A", OVERDUE ="B", ASSIGNED="C", TRASH="D", SPAM="E",NAME="name",COUNT="count";
ListView folders_list;
String[] folders;
String[] filter_id ={"2","3","4","5","6"};
List<String> folder_count;
JSONArray quick_view_array;
JSONObject quick_view_obj,count_obj;
String new_count, overdue_count,assigned_count,trash_count,spam_count;
List<HashMap<String, String>> menuItems;
Dialog dialog;
String URL;
Operation op=new Operation();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new getbrand().execute();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
getLayoutInflater().inflate(R.layout.folders, frameLayout);
mDrawerList.setItemChecked(position, true);
setTitle(listArray[position]);
folders_list = (ListView)findViewById(R.id.folder_display_list);
folders_list.setAdapter(null);
View header = (View)getLayoutInflater().inflate(R.layout.headerview,null);
folders_list.addHeaderView(header, null, false);
if (Operation.isNetworkAvailable(this))
{
new folders().execute();
folders_list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
{
position -= folders_list.getHeaderViewsCount();
String fid = filter_id[position];
String title=folders[position];
Intent i=new Intent(Folders.this,Tickets.class);
i.putExtra("filter_id","&vis_filter_id="+fid);
i.putExtra("title",title);
i.putExtra("set_queue","no");
startActivity(i);
}});
}
else
{
Operation.showToast(getApplicationContext(),R.string.no_network);
}
}
private class folders extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(Folders.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params) {
// TODO Auto-generated method stub
URL=op.getUrl(getApplicationContext(),"ticket","quick_view","");
quick_view_array = JSONfunctions.getJSONfromURL(URL+"&vis_encode=json",Folders.this);
return quick_view_array;
}
#Override
public void onPostExecute(JSONArray quick_view_array)
{
super.onPostExecute(quick_view_array);
try
{
quick_view_obj=quick_view_array.getJSONObject(0);
count_obj=quick_view_obj.getJSONObject("count");
folder_count= new ArrayList<String>();
//folder_count.add("");
folder_count.add(count_obj.getString(NEW));
folder_count.add(count_obj.getString(OVERDUE));
folder_count.add(count_obj.getString(ASSIGNED));
folder_count.add(count_obj.getString(TRASH));
folder_count.add(count_obj.getString(SPAM));
folders = getResources().getStringArray(R.array.folders);
menuItems=new ArrayList<HashMap<String, String>>();
for (int i = 0; i <filter_id.length; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(NAME,folders[i]);
map.put(COUNT,folder_count.get(i));
menuItems.add(map);
}
SimpleAdapter list =new SimpleAdapter
(Folders.this,
menuItems,
R.layout.folders,
new String[] {NAME,COUNT},
new int[] {R.id.folder_name,R.id.folder_count}
)
{ };
folders_list.setAdapter(list);
dialog.dismiss();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.home, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String filter_id = null,Tickets_title = null;
int start_limit=0,page_no=1;
// TODO Auto-generated method stub
switch (item.getItemId())
{
case R.id.menu_inbox:
Intent inbox = new Intent(Folders.this,Test.class);
startActivity(inbox);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed()
{
moveTaskToBack(true);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}
private class getbrand extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(Folders.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
// TODO Auto-generated method stub
String access=op.getUrl(getApplicationContext(),"ticket","get_branding","");
JSONArray access_denied = JSONfunctions.getJSONfromURL(access+"&vis_encode=json",Folders.this);
return access_denied;
}
#Override
public void onPostExecute(JSONArray access_denied)
{
super.onPostExecute(access_denied);
String access_result =access_denied.toString();
ActionBar ab = getActionBar();
if(access_result.equals("[\"1\"]"))
{ ab.setTitle(R.string.app_name);
ab.setIcon(R.drawable.application_icon);
}
else
{
ab.setTitle(R.string.nobrand_app_name);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
ab.setHomeAsUpIndicator(R.drawable.crop1);
ab.setIcon(R.drawable.white3);
}
dialog.dismiss();
}
}
private class getname extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(Folders.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
String STAFF_URL=op.getUrl(getApplicationContext(),"staff","get_staff_details","");
staff_data_array = JSONfunctions.getJSONfromURL(STAFF_URL+"&vis_encode=json",Folders.this);
return staff_data_array;
}
#Override
public void onPostExecute(JSONArray staff_data_array)
{
super.onPostExecute(staff_data_array);
String staff_data_result =staff_data_array.toString();
try {
post_obj = staff_data_array.getJSONObject(0);
String fname=post_obj.getString(FIRST_NAME);
String lname=post_obj.getString(LAST_NAME);
String image=post_obj.getString(PROFILE_IMAGE);
String fullname =fname;
if(fullname=="")
{
fullname="Admin";
}
Fullname="Welcome "+fullname;
TextView tv = new TextView(getApplicationContext());
tv.setText(Fullname);
tv.setBackgroundColor(Color.GREEN);
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.default_img,0,0,0);
mDrawerList.addHeaderView(tv, null, false);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}
}

android action bar menu button event handling issue

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;

can't override onContextItemSelected in Fragment

I'm trying to convert Activity to a fragment and can't override this methods : onCreateOptionsMenu,onOptionsItemSelected,onContextItemSelected.
,maybe some import statements are missing ? don't know what to do.Her is my Class file :
package com.wts.ui;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MainFragment extends Fragment {
protected final static int REQUEST_CODE = 1;
public static WordsDBAdapter dbAdapter;
private CustomAdapter cDataAdapter;
private Button button;
private EditText editWord;
private EditText editTranslate;
private ListView listView;
private String selectedWord;
private Cursor cursor;
// context menu
private final static int IDM_EDIT = 101;
private final static int IDM_DELETE = 102;
private final static int IDM_INFO = 103;
// options menu
private static final int IDM_ABOUT = 201;
private static final int IDM_EXIT = 202;
private static final int IDM_SETTINGS = 203;
private static final int IDM_QUESTION = 204;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbAdapter = new WordsDBAdapter(getActivity());
dbAdapter.open();
displayListView();
registerForContextMenu(listView);
// ================ListView onLongClick========================
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
cursor = (Cursor) listView.getItemAtPosition(arg2);
selectedWord = cursor.getString(WordsDBAdapter.ID_COL);
return false;
}
});
// ================Button onClick========================
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = editWord.getText().toString();
String translate = editTranslate.getText().toString();
if (word.length() > 0 && translate.length() >= 0) {
Cursor cursor = dbAdapter.fetchWordsByName(word);// chek is
// word
// repeat
if (cursor.moveToFirst()) {
Toast.makeText(getActivity().getApplicationContext(),
getResources().getString(R.string.word_exist),
Toast.LENGTH_SHORT).show();
} else if (!CheckWordInput(word)
|| !CheckTranslateInput(translate)) {
Toast.makeText(
getActivity().getApplicationContext(),
getResources().getString(
R.string.incorrect_input),
Toast.LENGTH_SHORT).show();
} else {
dbAdapter.insertWord(word, translate, " ",
String.valueOf(false), 0, 0, new Date());
displayListView();
editWord.setText("");
editTranslate.setText("");
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
button = (Button) view.findViewById(R.id.buttonAddWord);
listView = (ListView) view.findViewById(R.id.listWords);
editWord = (EditText) view.findViewById(R.id.editWord);
editTranslate = (EditText) view.findViewById(R.id.editTranslate);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// setContentView(R.layout.activity_main);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listWords) {
String[] menuItems = getResources().getStringArray(
R.array.contextMenuItems);
menu.add(Menu.NONE, IDM_EDIT, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_EDIT]);
menu.add(Menu.NONE, IDM_INFO, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_INFO]);
menu.add(Menu.NONE, IDM_DELETE, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_DELETE]);
}
}
//
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_EDIT: {
Intent intent = new Intent(getActivity(), EditActivity.class);
intent.putExtra(getResources().getString(R.string.fstRow),
cursor.getString(WordsDBAdapter.WORD_COL));
intent.putExtra(getResources().getString(R.string.scndRow),
cursor.getString(WordsDBAdapter.TRANS_COL));
intent.putExtra(getResources().getString(R.string.thrdRow),
cursor.getString(WordsDBAdapter.DESC_COL));
startActivityForResult(intent, REQUEST_CODE);
}
break;
case IDM_DELETE:
dbAdapter.deleteWord(selectedWord);
displayListView();
break;
case IDM_INFO: {
Intent intent = new Intent(getActivity(), InformationActivity.class);
for (int i = 1; i <= InformationActivity.nListItems; i++)
intent.putExtra(String.valueOf(i), cursor.getString(i));
startActivity(intent);
}
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
private void displayListView() {
// Cursor cursor = dbAdapter.fetchAllTranslated();
Cursor cursor = dbAdapter.fetchAllTranslated();
String[] columns = new String[] { WordsDBAdapter.KEY_WORD,
WordsDBAdapter.KEY_TRANSLATION, WordsDBAdapter.KEY_SUCCEEDED, };
int[] to = new int[] { R.id.textViewTranslate, R.id.textViewWord,
R.id.textViewSuccessPoints };
cDataAdapter = new CustomAdapter(getActivity(), R.layout.word_info,
cursor, columns, to);
listView.setAdapter(cDataAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_ABOUT: {
Intent intent = new Intent(getActivity(), AboutActivity.class);
startActivity(intent);
break;
}
case IDM_EXIT: {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
break;
}
case IDM_SETTINGS: {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
break;
}
case IDM_QUESTION: {
if (!StartActivity.isMainActivitySart)
getActivity().onBackPressed();
else {
Intent intent = new Intent(getActivity(),
QuestionActivity.class);
startActivity(intent);
}
}
break;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
if (intent.hasExtra(getResources().getString(R.string.fstRow))) {
dbAdapter.changeValue(
selectedWord,
intent.getExtras().getString(
getResources().getString(R.string.fstRow)),
intent.getExtras().getString(
getResources().getString(R.string.scndRow)),
intent.getExtras().getString(
getResources().getString(R.string.thrdRow)),
null, null, null, null);
displayListView();
}
}
}
#Override
public void onResume() {
super.onResume();
SettingsManager.setPreferedLanguage(getActivity());// set language
displayListView();
}
public static boolean CheckTranslateInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{0,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
public static boolean CheckWordInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{1,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
#Override
public void onDetach() {
super.onDetach();
dbAdapter.close();
}
}
You have to think about what you want your Fragment to be - Fragment or SherlockFragment?
You import this:
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
And so, your overrides aren't overrides because Menu & friends are different classes right now than what Fragment needs - they are ActionBarSherlock's classes.
If you extend SherlockFragment instead, your overrides should work, and it is recommended to extend SherlockFragment if you are using ActionBarSherlock (which based on your tags, you are).
If you want to keep this as a regular fragment, then import:
android.view.Menu
android.view.MenuItem
android.view.MenuInflater

Categories

Resources