Regarding migrating searchview on appcompat - android

I am migrating search view Item provided in action bar using support library .Here I have done as mentioned in doc but still it is giving error while creating options menu.Please tell me where I have done wrong.Here is my code.
contacts_list_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.utteru.ui="http://schemas.android.com/apk/res-auto"
xmlns:yourapp="http://schemas.android.com/tools">
<!-- The search menu item. Honeycomb and above uses an ActionView or specifically a SearchView
which expands within the Action Bar directly. Note the initial collapsed state set using
collapseActionView in the showAsAction attribute. -->
<group
android:id="#+id/main_menu_group">
<item
android:id="#+id/menu_search"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/ic_action_search"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
<group
android:id="#+id/refresh_group">
<item
android:id="#+id/refresh"
android:icon="#android:drawable/ic_popup_sync"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
</menu>
ContactsListFragment.java
import android.accounts.Account;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Photo;
import android.support.v4.BuildConfig;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ContactsListFragment extends ListFragment {
private static final String TAG = "ContactsAccessFragment";
private static final String STATE_PREVIOUSLY_SELECTED_KEY =
"com.Utteru.ui.SELECTED_ITEM";
ArrayList<AccessContactDto> allcontacts;
ArrayList<AccessContactDto> databasecontacts;
TextView textempty;
public Context mContext;
private AccessContactAdapter mAdapter;
private ImageLoader mImageLoader; // Handles loading the contact image in a background thread
// Stores the previously selected search item so that on a configuration change the same item
// can be reselected again
private int mPreviouslySelectedSearchItem = 0;
// Whether or not the search query has changed since the last time the loader was refreshed
private boolean mSearchQueryChanged;
// Whether or not this fragment is showing in a two-pane layout
private boolean mIsTwoPaneLayout;
// Whether or not this is a search result view of this fragment, only used on pre-honeycomb
// OS versions as search results are shown in-line via Action Bar search from honeycomb onward
private boolean mIsSearchResultView = false;
/**
* Fragments require an empty constructor.
*/
public ContactsListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIsTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
getActivity().setTitle("");
if (savedInstanceState != null) {
// If we're restoring state after this fragment was recreated then
// retrieve previous search term and previously selected search
// result.
mPreviouslySelectedSearchItem =
savedInstanceState.getInt(STATE_PREVIOUSLY_SELECTED_KEY, 0);
}
mImageLoader = new ImageLoader(getActivity(), CommonUtility.getListPreferredItemHeight(getActivity())) {
#Override
protected Bitmap processBitmap(Object data) {
// This gets called in a background thread and passed the data from
// ImageLoader.loadImage().
return loadContactPhotoThumbnail((String) data, getImageSize());
}
};
// Set a placeholder loading image for the image loader
mImageLoader.setLoadingImage(R.drawable.ic_contact_picture_holo_light);
// Add a cache to the image loader
mImageLoader.addImageCache(getActivity().getSupportFragmentManager(), 0.1f);
mContext = getActivity().getBaseContext();
new loadData().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the list fragment layout
View all_contacts_view = inflater.inflate(R.layout.contact_list_fragment, container, false);
textempty = (TextView)all_contacts_view.findViewById(android.R.id.empty);
textempty.setText("No contacts found");
return all_contacts_view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
AccessContactDto cdto = (AccessContactDto) l.getItemAtPosition(position);
Log.e("number on click",""+cdto.getMobile_number());
cdto=UserService.getUserServiceInstance(mContext).getAccessConDataByNumber(cdto.getMobile_number());
if(cdto==null)
cdto = (AccessContactDto) l.getItemAtPosition(position);
else
Log.e("mumber not mull from db","number not null from db");
Intent detailsActivity = new Intent(mContext, ContactDetailActivity.class);
detailsActivity.putExtra("selected_con", cdto);
startActivity(detailsActivity);
getActivity().overridePendingTransition(R.anim.animation1, R.anim.animation2);
super.onListItemClick(l, v, position, id);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Let this fragment contribute menu items
setHasOptionsMenu(true);
// Set up ListView, assign adapter and set some listeners. The adapter was previously
// created in onCreate().
setListAdapter(mAdapter);
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
// Pause image loader to ensure smoother scrolling when flinging
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageLoader.setPauseWork(true);
} else {
mImageLoader.setPauseWork(false);
}
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
if (mIsTwoPaneLayout) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
if (mPreviouslySelectedSearchItem == 0) {
}
}
#Override
public void onPause() {
super.onPause();
mImageLoader.setPauseWork(false);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.contact_list_menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
menu.setGroupVisible(R.id.main_menu_group, true);
if (mIsSearchResultView) {
searchItem.setVisible(false);
}
if (Utils.hasHoneycomb()) {
final SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryText) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.e("on query text change ","on query text change");
if (newText != null && !newText.equals(""))
{
ArrayList<AccessContactDto> filterList = new ArrayList<AccessContactDto>();
for (AccessContactDto a : allcontacts) {
if (a.getDisplay_name().toLowerCase().startsWith(newText.toLowerCase())) {
filterList.add(a);
continue;
}
getListView().setAdapter(new AccessContactAdapter(filterList, getActivity(), mImageLoader));
}
return true;
}
else{
getListView().setAdapter(new AccessContactAdapter(allcontacts, getActivity(), mImageLoader));
return true;
}
}
});
}
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (!Utils.hasHoneycomb()) {
getActivity().onSearchRequested();
}
break;
case R.id.refresh:
if (CommonUtility.isNetworkAvailable(getActivity())) {
final Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE);
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(account, ContactsContract.AUTHORITY, bundle);
mAdapter.notifyDataSetChanged();
// new CountDownTimer(5000, 1000) {
// #Override
// public void onTick(long millisUntilFinished) {
// }
//
// #Override
// public void onFinish() {
//
// }
// }.start();
} else {
Toast.makeText(getActivity(), "Internet Connection Required!!", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {
if (!isAdded() || getActivity() == null) {
return null;
}
AssetFileDescriptor afd = null;
try {
Uri thumbUri;
if (Utils.hasHoneycomb()) {
thumbUri = Uri.parse(photoData);
} else {
final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
}
afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");
FileDescriptor fileDescriptor = afd.getFileDescriptor();
if (fileDescriptor != null) {
return ImageLoader.decodeSampledBitmapFromDescriptor(
fileDescriptor, imageSize, imageSize);
}
} catch (FileNotFoundException e) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
+ ": " + e.toString());
}
} finally {
if (afd != null) {
try {
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public ArrayList<AccessContactDto> readContactsNew() {
ArrayList<AccessContactDto> list = new ArrayList<AccessContactDto>();
AccessContactDto adto;
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String photouri= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
String contact_id= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
Uri con_uri= Contacts.getLookupUri(phones.getLong(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)), phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY)));
adto = new AccessContactDto(contact_id, name, null, phoneNumber, null, photouri, con_uri.toString(),null,null,null);
list.add(adto);
}
phones.close();
return list;
}
public class loadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void aVoid) {
mAdapter = new AccessContactAdapter(allcontacts, getActivity(), mImageLoader);
if(getActivity()!=null)
getListView().setAdapter(mAdapter);
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(Void... params) {
allcontacts = readContactsNew();
// databasecontacts = UserService.getUserServiceInstance(mContext).getAllAccessContacts();
// allcontacts.removeAll(databasecontacts);
// allcontacts.addAll(databasecontacts);
Collections.sort(allcontacts, new Comparator<AccessContactDto>() {
#Override
public int compare(AccessContactDto lhs, AccessContactDto rhs) {
return lhs.getDisplay_name().compareToIgnoreCase(rhs.getDisplay_name());
}
});
return null;
}
}
}
ContactsListActivity.java
import android.accounts.AccountManager;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import com.viewpagerindicator.IconPagerAdapter;
public class ContactsListActivity extends ActionBarActivity {
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
private ContactDetailFragment mContactDetailFragment;
private boolean isTwoPaneLayout;
AccountManager mAccountManager;
Boolean checkAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(R.color.purple));
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
isTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
pagerTabStrip.setTextSpacing(0);
pagerTabStrip.setPadding(0, 0, 0, 10);
pagerTabStrip.setTextSize(1, 20);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.remove("android:support:fragments");
}
#Override
public void onBackPressed() {
startActivity(new Intent(ContactsListActivity.this, MenuScreen.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK));
this.finish();
overridePendingTransition(R.anim.card_rotate_in, R.anim.card_rotate_out);
}
#Override
protected void onDestroy() {
if(CommonUtility.dialog!=null){
CommonUtility.dialog.dismiss();
}
super.onDestroy();
}
#Override
public boolean onSearchRequested() {
boolean isSearchResultView = false;
return !isSearchResultView && super.onSearchRequested();
}
public static class DemoCollectionPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[]{"All Contacts", "Access Contacts"};
protected final int[] ICONS = new int[]{
R.drawable.all_contact,
R.drawable.access_contacts
};
private int mCount = CONTENT.length;
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// All Contacts Fragment
return new ContactsListFragment();
case 1:
// Access Contacts Fragment
return new ContactsAccessFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return DemoCollectionPagerAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
}
Error Log:
java.lang.NullPointerException
at com.hello.ContactsListFragment.onPrepareOptionsMenu(ContactsListFragment.java:236)
at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1882)
at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:2020)
at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:459)
at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:280)
at android.support.v7.app.ActionBarActivityDelegate$1.onPreparePanel(ActionBarActivityDelegate.java:84)
at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:1006)
at android.support.v7.app.ActionBarActivityDelegateBase.doInvalidatePanelMenu(ActionBarActivityDelegateBase.java:1182)
at android.support.v7.app.ActionBarActivityDelegateBase.access$100(ActionBarActivityDelegateBase.java:79)
at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:115)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)

Related

ListView displays data twice

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

onBackPressed() unfortunately app has stopped in android phone

I am developing an eCommerce application where most of the java class file using Async Task for fetching data from server and I am using fragment in all java class . My problem is that when I click OnBackPressed it shows error in Async Task line because it takes some time interval again to fetch data from server..
MainActivity.java
package com.prashant;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.os.Handler;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements android.support.v7.app.ActionBar.OnNavigationListener {
TextView txtView;
private static MainActivity sMainActivity;
ProgressBar prgLoading;
RelativeLayout drawerPane;
DrawerLayout drawerLayout;
GridView lvNav;
TextView Customer_name;
TextView Customer_email;
TextView Customer_mob;
List<NavItem> listNavItems;
List<Fragment> listFragment;
private Boolean exit = false;
ActionBarDrawerToggle actionBarDrawerToggle;
public int hot_number = Constants.ProductCart_Id.size();
private TextView ui_hot = null;
private boolean mNaviFirstHit = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sMainActivity = this;
// Styling Action Bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.rgb(7,112,200)));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//Getting Session Information Of Customer
String MyPREFERENCES = "CustomerData";
SharedPreferences sharedpreferences =getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Constants.Customer_FirstName= sharedpreferences.getString("Customer_FirstName","");
Constants.Customer_LastName=sharedpreferences.getString("Customer_LastName", "");
Constants.Customer_MobileNo=sharedpreferences.getString("Customer_MobileNo", "");
Constants.Customer_Id=sharedpreferences.getInt("Customer_Id", 0);
Constants.Customer_Email=sharedpreferences.getString("Customer_Email", "");
Customer_email.setText(Constants.Customer_Email);
//Asigning FRagment names of sidebar
listNavItems = new ArrayList<NavItem>();
listNavItems.add(new NavItem("Home", null, R.drawable.pras));
for(int i=0;i<Constants.Category_name.size();i++){
listNavItems.add(new NavItem(Constants.Category_name.get(i),null,R.drawable.teju));
}
NavListAdapter navListAdapter = new NavListAdapter(getApplicationContext(), R.layout.item_nav_list, listNavItems);
lvNav.setAdapter(navListAdapter);
listFragment = new ArrayList<Fragment>();
listFragment.add(new MyHome());
for(int i=0;i<Constants.Category_name.size();i++){
listFragment.add(new ProductsListFragment());
}
listFragment.add(new MyHome());
listFragment.add(new ActivityCart());
listFragment.add(new LoginFragment());
listFragment.add(new MyAbout());
//Asigning FRagment names of sidebar
//Saving fragment data as constants for my home categories
Constants.listNavItems=listNavItems;
Constants.listFragment=listFragment;
//Saving fragment data as constants for my home categories
//Load first fragment as default:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, listFragment.get(0)).commit();
setTitle(listNavItems.get(0).getTitle());
lvNav.setItemChecked(0, true);
drawerLayout.closeDrawer(drawerPane);
// create listener for drawer layout
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open , R.string.drawer_close)
{
#Override
public void onDrawerOpened(View drawerView)
{
invalidateOptionsMenu();
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView)
{
invalidateOptionsMenu();
super.onDrawerClosed(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
final Menu mMenu = menu;
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.actionbar_icon_menu, menu);
// Cart Icon in Action Bar
final View menu_hotlist = menu.findItem(R.id.cart_icon).getActionView();
ui_hot = (TextView) menu_hotlist.findViewById(R.id.hotlist_Cart_hot);
updateHotCount(hot_number);
menu_hotlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.lastDetails = false;
FragmentManager fragmentManager = getSupportFragmentManager();
ActivityCart cart = new ActivityCart();
fragmentManager.beginTransaction().replace(R.id.main_content, cart).commit();
setTitle("Cart");
drawerLayout.closeDrawer(drawerPane);
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.cart_icon:
// search action
FragmentManager fragmentManager = getSupportFragmentManager();
ActivityCart cart = new ActivityCart();
fragmentManager.beginTransaction().replace(R.id.main_content, cart).commit();
setTitle("Cart");
drawerLayout.closeDrawer(drawerPane);
return true;
case R.id.action_search:
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() >0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (mNaviFirstHit) {
mNaviFirstHit = false;
return true;
}
else {
if(itemPosition == 0)
Constants.isCallParent = true;
else
Constants.isCallParent = false;
Constants.SubCatposition = itemPosition;
ProductsListFragment productsListFragment = new ProductsListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, productsListFragment).commit();
//lvNav.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerPane);
//Toast.makeText(this, "Clicked at: " + itemPosition, Toast.LENGTH_LONG).show();
//mNaviFirstHit = true;
return true;
}
}
public void setLoginDetails(){
Customer_email.setText(Constants.Customer_Email);
Customer_name.setText("Welcome, " + Constants.Customer_FirstName);
Customer_name.setText(Constants.Customer_LastName);
}
}
ProductListFragment.java
package com.prashant;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by prashant.
*/
public class ProductsListFragment extends Fragment {
ProgressDialog pdialog;
View v;
Button sort,filter;
//ListView list;
GridView list;
LazyImageLoadAdapter adapter;
private static ProductsListFragment sProductsListFragment;
// Title navigation Spinner data
private ArrayList<SpinnerNavItem> navSpinner;
// Navigation adapter
private TitleNavigationAdapter titleNavigationAdapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
//((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
// Action Bar
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_LIST);
}
#Override
public View onCreateView(LayoutInflater inflater,#Nullable ViewGroup container,#Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.productlistfragment, container, false);
sProductsListFragment = this;
list=(GridView)v.findViewById(R.id.list);
sort = (Button) v.findViewById(R.id.btn_sort);
sort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),Pop.class));
}
});
//clearData();
return v;
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
#Override
public void onPause() {
super.onPause();
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Constants.cartEntry=0;
//check Product Description fragment is called or not
if (!Constants.lastDetails) {
clearData();
new getDataTask().execute();
}
else{
String[] images=new String[Constants.Product_image.size()];
images=Constants.Product_image.toArray(images);
adapter = new LazyImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list.setAdapter(adapter);
Constants.lastDetails = false;
}
}
// clear arraylist variables before used
void clearData(){
Constants.Product_ID.clear();
Constants.Product_name.clear();
Constants.Product_price.clear();
Constants.Product_image.clear();
Constants.Product_qty.clear();
Constants.Product_specialPrice.clear();
Constants.Product_desc.clear();
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
//list.setAdapter(null);
//Refresh cache directory downloaded images
//adapter.imageLoader.clearCache();
//adapter.notifyDataSetChanged();
super.onDestroy();
}
public View.OnClickListener listener=new View.OnClickListener(){
#Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
/*
Intent intent = new Intent(getActivity(), ProductDescription.class);
intent.putExtra("descposition", mPosition);
startActivity(intent);*/
Constants.product_position = mPosition;
ProductDescription productDescription=new ProductDescription();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content, productDescription, null).addToBackStack("productDescription").commit();
//((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(Constants.Product_name.get(mPosition));
getActivity().setTitle("Product Details");
}
// Image urls used in LazyImageLoadAdapter.java file
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage("Loading...");
pdialog.setCanceledOnTouchOutside(getRetainInstance());
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Create custom adapter for listview
String[] images=new String[Constants.Product_image.size()];
images=Constants.Product_image.toArray(images);
adapter = new LazyImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list.setAdapter(adapter);
if (!Constants.isSubCategory) {
Constants.isSubCategory = true;
// Spinner title navigation data
navSpinner = new ArrayList<SpinnerNavItem>();
navSpinner.add(new SpinnerNavItem(Constants.Category_name.get(Constants.position - 1), R.drawable.icon));
for (int i = 0; i < Constants.SubCategory_ID.size(); i++) {
navSpinner.add(new SpinnerNavItem(Constants.SubCategory_name.get(i), R.drawable.icon));
}
// title drop down adapter
titleNavigationAdapter = new TitleNavigationAdapter(getActivity(), navSpinner);
// assigning the spinner navigation
((MainActivity) getActivity()).getSupportActionBar().setListNavigationCallbacks(titleNavigationAdapter, ((MainActivity) getActivity()));
}
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
if (Constants.Product_ID.isEmpty()){
// Toast.makeText(getActivity(), "No products found!!Check your internet connection!!", Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("No Product Found!!").setMessage("Slow Internet/Check Your Internet Settings").create().show();
}
/*for (int i = 0; i < Constants.Product_ID.size(); i++) {
Toast.makeText(getActivity(), "__" + Constants.Product_ID.get(i) + "__" + i, Toast.LENGTH_SHORT).show();
}*/
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
// method to parse json data from server
public void parseJSONData(){
SoapObject request = new SoapObject(Constants.NAMESPACE, "catalogCategoryAssignedProducts");
String Catid;
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
if ((!Constants.isSubCategory) || Constants.isCallParent) {
Constants.isCallParent = false;
request.addProperty("categoryId", String.valueOf(Constants.Category_ID.get(Constants.position - 1)));
Catid=String.valueOf(Constants.Category_ID.get(Constants.position - 1));
}
else {
request.addProperty("categoryId", String.valueOf(Constants.SubCategory_ID.get(Constants.SubCatposition - 1)));
Catid=String.valueOf(Constants.SubCategory_ID.get(Constants.SubCatposition - 1));
}
api_calls call=new api_calls();
call.getCategoryProducts(Catid);
if (!Constants.isSubCategory) {
Constants.SubCategory_ID.clear();
Constants.SubCategory_name.clear();
parseJSONDataSubCategory();
}
}
// method to parse json data from server
public void parseJSONDataSubCategory(){
try {
SoapObject request = new SoapObject(Constants.NAMESPACE, "catalogCategoryTree");
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
request.addProperty("parentId", Constants.Category_ID.get(Constants.position-1));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
//Web method call
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.URL);
androidHttpTransport.debug = true;
androidHttpTransport.call("", envelope);
//get the response
SoapObject result2 = (SoapObject) envelope.getResponse();
SoapObject pii2 = (SoapObject) result2.getProperty(5);
for (int i = 0; i < pii2.getPropertyCount(); i++) {
//JSONObject object = data.getJSONObject(i);
SoapObject pii = (SoapObject)pii2.getProperty(i);
//JSONObject category = object.getJSONObject("Category");
Constants.SubCategory_ID.add(Long.parseLong(pii.getProperty(0).toString()));
Constants.SubCategory_name.add(pii.getProperty(2).toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
// Making Sub Drawer for Sub Category
public static ProductsListFragment getInstance() {
return sProductsListFragment;
}
public void onBackPressed()
{
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.popBackStack();
}
}
Logcat
02-11 12:39:57.838 12954-14579/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
Process: com.softonetech.www.takenick, PID: 12954
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at com.prashant.ProductsListFragment.parseJSONData(ProductsListFragment.java:250)
at com.prashant.ProductsListFragment$getDataTask.doInBackground(ProductsListFragment.java:185)
at com.prashant.ProductsListFragment$getDataTask.doInBackground(ProductsListFragment.java:167)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
try cancelling your Async task execution during onBackPressed()
Declare:
Public getDataTask asyncFetchData;
asyncFetchData = new getDataTask();
asyncFetchData.execute();
Now in your Fragment:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (asyncFetchData!= null)
asyncFetchData.cancel(true);
Toast.makeText(getActivity(), "Back pressed...", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});
}
Also in doInBackground notify the AsyncTask to cancel execution
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
if (isCancelled()) break;
return null;
}

How to use ViewPager + Fragment +ListView

here is my Code,the Activityis to show 7 tabs from Mon. to Sun.each tabs use the same fragment,I wanna add a ListView to load the imformation,but I don't how to do
Activity:
package space.levan.myclass.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;
import space.levan.myclass.R;
import space.levan.myclass.fragment.LessonFragment;
import space.levan.myclass.utils.InfoUtil;
import space.levan.myclass.utils.NetUtil;
/**
* Created by 339 on 2016/5/3.
*/
public class ScheduleActivity extends AppCompatActivity implements MaterialTabListener{
#Bind(R.id.materialTabHost)
MaterialTabHost mTabHost;
#Bind(R.id.pager)
ViewPager mViewPager;
ViewPagerAdapter adapter;
private List<HashMap<String, Object>> ClassInfos;
private HashMap<String, Object> ClassInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
ButterKnife.bind(this);
setTitle("课程表");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Fragment lessonFragment;
adapter = new ViewPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// when user do a swipe the selected tab change
mTabHost.setSelectedNavigationItem(position);
}
});
// insert all tabs from pagerAdapter data
for (int i = 0; i < adapter.getCount(); i++) {
mTabHost.addTab(
mTabHost.newTab()
.setText(adapter.getPageTitle(i))
.setTabListener(this)
);
}
Calendar calendar = Calendar.getInstance();
int temp = calendar.get(Calendar.DAY_OF_WEEK) - 2;
mViewPager.setCurrentItem(temp);
Map<String, String> loginInfo = InfoUtil.getLoginInfo(ScheduleActivity.this);
getLesson(loginInfo.get("StuToken"));
}
public String getLesson(final String mToken) {
new Thread() {
public void run() {
String result = NetUtil.getSchedule(mToken);
if (result != null) {
try {
JSONObject jsonObject = new JSONObject(result);
int error = jsonObject.getInt("error");
String message = jsonObject.getString("message");
switch (error) {
case 0:
getDes(jsonObject);
break;
case 1:
showToast(message);
break;
case 2:
reLogin();
break;
default:
break;
}
}catch (Exception e) {
e.printStackTrace();
}
} else {
showToast("数据异常");
}
}
}.start();
return null;
}
private void getDes(JSONObject jsonObject) {
try {
JSONObject Object = jsonObject.getJSONObject("data");
JSONObject data = Object.getJSONObject("data");
for (int i = 1; i < 7; i++) {
JSONObject day = data.getJSONObject(""+i);
for (int n = 1; n < 5; n++) {
JSONArray lesson = day.getJSONArray(""+n);
ClassInfos = new ArrayList<>();
for(int m = 0; m < lesson.length();m++) {
JSONObject des = (JSONObject) lesson.get(m);
String name = des.getString("course");
String teacher = des.getString("teacher");
String time = des.getString("time");
String room = des.getString("classroom");
/*showToast("星期:" + i + "\n节次:" + n + "\n课程名字:"
+ name + "\n任课老师:" + teacher + "\n上课周数:" + time
+ "\n教室:" + room);*/
ClassInfo = new HashMap<>();
ClassInfo.put("Name","课程名字:" + name);
ClassInfo.put("Teacher","上课老师:" + teacher);
ClassInfo.put("Time","上课周次:" + time);
ClassInfo.put("Room","上课教室:" + room);
ClassInfos.add(ClassInfo);
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
private void showToast(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScheduleActivity.this,message, Toast.LENGTH_SHORT).show();
}
});
}
private void reLogin() {
InfoUtil.deleteUserInfo(ScheduleActivity.this);
runOnUiThread(new Runnable() {
#Override
public void run() {
final Intent intent = getPackageManager().
getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Toast.makeText(ScheduleActivity.this,
"数据异常,请重新登录帐号",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onTabSelected(MaterialTab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(MaterialTab tab) {
}
#Override
public void onTabUnselected(MaterialTab tab) {
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int num) {
return new LessonFragment();
}
#Override
public int getCount() {
return 7;
}
#Override
public CharSequence getPageTitle(int position) {
int temp = position+1;
return "星期" + temp;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
menu.add(0, 1, 0, R.string.home_about);
return true;
}
/**
* 用于界面返回按钮
* #param item
* #return
*/
#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.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
case 1:
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
Here is fragment :
package space.levan.myclass.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by 339 on 2016/5/5.
*/
public class LessonFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
TextView text = new TextView(container.getContext());
text.setText("(╯°Д°)╯︵┴┴");
text.setGravity(Gravity.CENTER);
return text;
}
}
You just need to add a ListView in the LessonFragment.
Follow these steps:
Create a layout file with a listview.
Inflate this layout in onCreateView method of LessonFragment and find this listview.
now, set an adapter for this listview, with the data you want.(hoping you know how to set an adapter)
And now you have a listview in each tab.
public class LessonFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_lesson, container, false);
mListView = (ListView) rootView.findViewById(R.id.listview);
//create an adapter
//set the above adapter to the listview
return rootView;
}
}

Loading data from sqlite and displaying on ViewPager

Been trying to load data from sqlite and display it on viewpager without much success.
I have a viewpager with two tabs which should hold data based on the tag_id passed as a parameter of newInstance. There is also an action bar navigation spinner with a list of counties that is used for filter data displayed based on the county_id.
Am able to fetch data from server and save it in the sqlite db but displaying it is the problem. Data is not dispalyed on the first page of the viewpager but it exists in the sqlite. Data for the second is the only one laoded.
Below is my implementation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.app.adapter.CustomCountySpinnerAdapter;
import com.app.adapter.TendersAdapter;
import com.app.database.DBFunctions;
import com.app.externallib.AppController;
import com.app.model.CountyModel;
import com.app.model.PostsModel;
import com.app.utils.AppConstants;
import com.app.utils.PostsListLoader;
import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter;
import com.viewpagerindicator.TabPageIndicator;
public class PublicTendersFragment extends Fragment{
private static List<PubliTenders> public_tenders;
public PublicTendersFragment newInstance(String text) {
PublicTendersFragment mFragment = new PublicTendersFragment();
Bundle mBundle = new Bundle();
mBundle.putString(AppConstants.TEXT_FRAGMENT, text);
mFragment.setArguments(mBundle);
return mFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public_tenders = new ArrayList<PubliTenders>();
public_tenders.add(new PubliTenders(14, "County"));
public_tenders.add(new PubliTenders(15, "National"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context contextThemeWrapper = new ContextThemeWrapper(
getActivity(), R.style.StyledIndicators);
LayoutInflater localInflater = inflater
.cloneInContext(contextThemeWrapper);
View v = localInflater.inflate(R.layout.fragment_tenders, container,
false);
FragmentPagerAdapter adapter = new TendersVPAdapter(
getFragmentManager());
ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) v
.findViewById(R.id.indicator);
indicator.setViewPager(pager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
class TendersVPAdapter extends FragmentPagerAdapter{
public TendersVPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Tenders.newInstance(public_tenders.get(position).tag_id);
case 1:
return Tenders.newInstance(public_tenders.get(position).tag_id);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return public_tenders.get(position).tender_type.toUpperCase(Locale
.getDefault());
}
#Override
public int getCount() {
return public_tenders.size();
}
}
public class PubliTenders {
public int tag_id;
public String tender_type;
public PubliTenders(int tag_id, String tender_type) {
this.tag_id = tag_id;
this.tender_type = tender_type;
}
}
public static class Tenders extends ListFragment implements
OnNavigationListener, LoaderCallbacks<ArrayList<PostsModel>> {
boolean mDualPane;
int mCurCheckPosition = 0;
// private static View rootView;
private SwipeRefreshLayout swipeContainer;
private ListView lv;
private View rootView;
private DBFunctions mapper;
private CustomCountySpinnerAdapter spinadapter;
private TendersAdapter mTendersAdapter;
private static final String ARG_TAG_ID = "tag_id";
private int tag_id;
private int mycounty;
private static final int INITIAL_DELAY_MILLIS = 500;
private static final String DEBUG_TAG = "BlogsFragment";
private final String TAG_REQUEST = "BLOG_TAG";
private JsonArrayRequest jsonArrTendersRequest;
// private OnItemSelectedListener listener;
public static Tenders newInstance(int tag_id) {
Tenders fragment = new Tenders();
Bundle b = new Bundle();
b.putInt(ARG_TAG_ID, tag_id);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tag_id = getArguments().getInt(ARG_TAG_ID);
}
#Override
public void onStart() {
super.onStart();
getLoaderManager().initLoader(0, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_headlines_blog,
container, false);
swipeContainer = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipeProjectsContainer);
lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (lv == null || lv
.getChildCount() == 0) ? 0 : lv.getChildAt(0)
.getTop();
swipeContainer.setEnabled(topRowVerticalPosition >= 0);
}
});
swipeContainer.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
fetchPublicTenders(mycounty);
}
});
swipeContainer.setColorSchemeResources(R.color.blue_dark,
R.color.irdac_green, R.color.red_light,
R.color.holo_red_light);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mapper = new DBFunctions(getActivity());
mapper.open();
// initialize AB Spinner
populateSpinner();
fetchPublicTenders(mycounty);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
private void populateSpinner() {
try {
List<CountyModel> counties = new ArrayList<CountyModel>();
counties = mapper.getAllCounties();
ActionBar actBar = ((ActionBarActivity) getActivity())
.getSupportActionBar();
actBar.setDisplayShowTitleEnabled(true);
actBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
spinadapter = new CustomCountySpinnerAdapter(getActivity(),
android.R.layout.simple_spinner_dropdown_item, counties);
actBar.setListNavigationCallbacks(spinadapter, this);
} catch (NullPointerException exp) {
}
}
#Override
public Loader<ArrayList<PostsModel>> onCreateLoader(int arg0,
Bundle arg1) {
Log.v(DEBUG_TAG, "On Create Loader");
return new PostsListLoader(getActivity(), mycounty, tag_id);
}
#Override
public void onLoadFinished(Loader<ArrayList<PostsModel>> arg0,
ArrayList<PostsModel> data) {
// System.out.println("results " + data.size());
addToAdapter(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<PostsModel>> arg0) {
lv.setAdapter(null);
}
#Override
public boolean onNavigationItemSelected(int pos, long arg1) {
CountyModel mo = spinadapter.getItem(pos);
this.mycounty = mo.getId();
refresh(mo.getId());
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextView txtTitle = (TextView) v.findViewById(R.id.tender_title);
TextView txtRefNo = (TextView) v.findViewById(R.id.ref_no);
TextView txtExpiryDate = (TextView) v
.findViewById(R.id.expiry_date);
TextView txtOrg = (TextView) v.findViewById(R.id.dept_or_org);
Intent intTenderFullDetails = new Intent(getActivity(),
TenderDetailsActivity.class);
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_TITLE,
txtTitle.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_REF_NO,
txtRefNo.getText().toString().trim());
intTenderFullDetails.putExtra(
TenderDetailsActivity.TENDER_EXPIRY_DATE, txtExpiryDate
.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_ORG,
txtOrg.getText().toString().trim());
// intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_DESC,
// Lorem);
startActivity(intTenderFullDetails);
}
private void fetchPublicTenders(final int county_id) {
swipeContainer.setRefreshing(true);
Uri.Builder builder = Uri.parse(AppConstants.postsUrl).buildUpon();
builder.appendQueryParameter("tag_id", Integer.toString(tag_id));
System.out.println("fetchPublicTenders with tag_id " + tag_id
+ " and county_id " + county_id);
jsonArrTendersRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject tender_item = response
.getJSONObject(i);
mapper.createPost(
tender_item.getInt("id"),
tender_item.getInt("tag_id"),
tender_item.getInt("county_id"),
tender_item.getInt("sector_id"),
tender_item.getString("title"),
tender_item.getString("slug"),
tender_item.getString("content"),
tender_item
.getString("reference_no"),
tender_item
.getString("expiry_date"),
tender_item
.getString("organization"),
tender_item
.getString("image_url"),
tender_item
.getString("created_at"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
refresh(county_id);
}
} else {
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
try {
Toast.makeText(getActivity(),
"Sorry! No results found",
Toast.LENGTH_LONG).show();
} catch (NullPointerException npe) {
System.out.println(npe);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
try {
Toast.makeText(
getActivity(),
"Network Error. Cannot refresh list",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
refresh(county_id);
} else if (error instanceof ServerError) {
try {
Toast.makeText(
getActivity(),
"Problem Connecting to Server. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
try {
Toast.makeText(getActivity(),
"No Connection", Toast.LENGTH_SHORT)
.show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
} else if (error instanceof TimeoutError) {
try {
Toast.makeText(
getActivity()
.getApplicationContext(),
"Timeout Error. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
// Set a retry policy in case of SocketTimeout & ConnectionTimeout
// Exceptions. Volley does retry for you if you have specified the
// policy.
jsonArrTendersRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(20),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonArrTendersRequest.setTag(TAG_REQUEST);
AppController.getInstance().addToRequestQueue(jsonArrTendersRequest);
}
public void refresh(int county_id) {
Bundle b = new Bundle();
b.putInt("myconty", county_id);
if (isAdded()) {
getLoaderManager().restartLoader(0, b, this);
}
}
private void addToAdapter(ArrayList<PostsModel> plist) {
mTendersAdapter = new TendersAdapter(rootView.getContext(), plist);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
mTendersAdapter);
swingBottomInAnimationAdapter.setAbsListView(lv);
assert swingBottomInAnimationAdapter.getViewAnimator() != null;
swingBottomInAnimationAdapter.getViewAnimator()
.setInitialDelayMillis(INITIAL_DELAY_MILLIS);
setListAdapter(swingBottomInAnimationAdapter);
mTendersAdapter.notifyDataSetChanged();
}
}
}
And this is the PostsListLoader class
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.app.database.DBFunctions;
import com.app.model.PostsModel;
public class PostsListLoader extends AsyncTaskLoader<ArrayList<PostsModel>> {
private DBFunctions mapper;
private ArrayList<PostsModel> myPostsModel;
private int county_id;
private int tag_id;
public PostsListLoader(Context context, int county_id, int tag_id) {
super(context);
mapper = new DBFunctions(getContext());
mapper.open();
this.county_id = county_id;
this.tag_id = tag_id;
}
#Override
public ArrayList<PostsModel> loadInBackground() {
String query_string = AppConstants.KEY_COUNTY_ID + " = " + county_id
+ " AND " + AppConstants.KEY_TAG_ID + " = " + tag_id;
myPostsModel = mapper.getPosts(query_string);
return myPostsModel;
}
#Override
public void deliverResult(ArrayList<PostsModel> data) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (data != null) {
onReleaseResources(data);
}
}
List<PostsModel> oldNews = data;
myPostsModel = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(data);
}
// At this point we can release the resources associated with
// 'oldNews' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldNews != null) {
onReleaseResources(oldNews);
}
}
/**
* Handles a request to start the Loader.
*/
#Override
protected void onStartLoading() {
if (myPostsModel != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(myPostsModel);
}
if (takeContentChanged() || myPostsModel == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Handles a request to cancel a load.
*/
#Override
public void onCanceled(ArrayList<PostsModel> news) {
super.onCanceled(news);
// At this point we can release the resources associated with 'news'
// if needed.
onReleaseResources(news);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (myPostsModel != null) {
onReleaseResources(myPostsModel);
myPostsModel = null;
}
}
/**
* Helper function to take care of releasing resources associated with an
* actively loaded data set.
*/
protected void onReleaseResources(List<PostsModel> news) {
}
}
What could I be doing wrong?
Any help will be appreciated.
Thanks

ListActivity onScroll never fired

I have a ListActivity that implements OnScrollListener. Unfortunality the methods onScroll and onScrollStateChanged are never fired.
I have absolutly no idear why. The data is shown correctly. I am able to scroll inside my view... Do you see the problem?
package bc.qz.client.android.activity;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import bc.qz.client.android.R;
import bc.qz.client.android.adapter.ScoreListAdapter;
import bc.qz.client.android.proxy.RemoteServletCaller;
import de.bc.qz.business.Score;
public class ScoreActivity extends ListActivity implements OnScrollListener{
private SharedPreferences mSharedPreferences;
private RemoteServletCaller mRemoteServletCaller;
private Runnable lViewScoreRunnable;
private String mUuid;
private String mUsername;
private ProgressDialog mProgressDialog = null;
private ScoreListAdapter mScoreListAdapter;
List<Score> mAllScore = new ArrayList<Score>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mRemoteServletCaller = new RemoteServletCaller();
mSharedPreferences = this.getSharedPreferences(
"de.bc.qz.client.sharedpreferences", Context.MODE_PRIVATE);
mUuid = mSharedPreferences.getString("uuid", null);
mUsername = mSharedPreferences.getString("user", null);
mScoreListAdapter = new ScoreListAdapter(this, mAllScore);
setListAdapter(mScoreListAdapter);
lViewScoreRunnable = new Runnable() {
#Override
public void run() {
loadAllScore(mUsername, mUuid);
}
};
Thread thread = new Thread(null, lViewScoreRunnable,
"MagentoBackground");
thread.start();
mProgressDialog = ProgressDialog.show(ScoreActivity.this,
"Bitte warten...", "Lade Highscore...", true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_score_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.goToTop:
return true;
case R.id.goToBottom:
return true;
case R.id.goToMine:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
System.out.println("onScroll");
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
System.out.println("onScrollStateChanged");
}
private void loadAllScore(String pUsername, String pUuid) {
try {
if (null == mUuid || mUsername == null) {
mUuid = UUID.randomUUID().toString();
mSharedPreferences.edit().putString("uuid", mUuid).commit();
mAllScore.addAll(mRemoteServletCaller.getAllScore(1, 50));
} else {
mAllScore.addAll(mRemoteServletCaller.getAllScore(mUsername,
mUuid));
}
} catch (Exception e) {
return;
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if (mAllScore != null && mAllScore.size() > 0) {
mScoreListAdapter.notifyDataSetChanged();
for (int i = 0, N = mAllScore.size(); i < N; i++)
mScoreListAdapter.add(mAllScore.get(i));
}
mProgressDialog.dismiss();
}
};
}
getListView().setOnScrollListener(this);

Categories

Resources