getContext().getContentResolver().notifyChange(uri, null) didn't notify cursor - android

i'm trying to undestand Content Provider,but i stuck in one thing,
notification of cursor didn't work,if i update cursor in query method everything works fine.Where i get wrong.Thank you! This is full source code
https://github.com/denmariupol/StartAndroid/tree/master/lesson101_contentprovider_creation_h/src/main
MainActivity
package com.example.lesson101_contentprovider_creation_h;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.lesson101_contentprovider_creation_h.databinding.ActivityMainBinding;
import com.example.lesson101_contentprovider_creation_h.interfaces.IUpdateCursor;
import com.example.lesson101_contentprovider_creation_h.fragments.Insert;
import com.facebook.stetho.Stetho;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity implements IUpdateCursor {
public final static Uri PROVIDER_URI = Uri.parse("com.example.lesson101_contentprovider_creation_h");
private Cursor cursor;
private MyAdapter scAdapter;
private ActivityMainBinding mainActivity;
private OnClickListener clickListener;
private int colId;
private int colText;
private ArrayList<Integer> chekedItems = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stethoInit();
mainActivity = DataBindingUtil.setContentView(this, R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
cursor = getContentResolver().query(MyProvider.CONTENT_URI, null, null, null, null, null);
}
colId = cursor.getColumnIndex(MyProvider.ID);
colText = cursor.getColumnIndex(MyProvider.TEXT);
String[] from = new String[]{MyProvider.ID, MyProvider.TEXT};
int[] to = new int[]{R.id.itemId, R.id.itemText};
scAdapter = new MyAdapter(this, R.layout.item, cursor, from, to, 0);
mainActivity.listItem.setAdapter(scAdapter);
scAdapter.notifyDataSetChanged();
mainActivity.listItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final View v = view;
final LinearLayout itemUpdateLayout = (LinearLayout)view.findViewById(R.id.itemUpdateLayout);
final LinearLayout itemViewLayout = (LinearLayout)view.findViewById(R.id.itemViewLayout);
TextView idView = (TextView)view.findViewById(R.id.itemId);
TextView textView = (TextView)view.findViewById(R.id.itemText);
final EditText editText = (EditText)view.findViewById(R.id.updateTextField);
Button updateButton = (Button)view.findViewById(R.id.updateRecButton);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("!!!","onTextChanged -> "+s.toString());
// ed
}
#Override
public void afterTextChanged(Editable s) {
}
});
final String updId = idView.getText().toString();
updateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ContentValues cv = new ContentValues();
String text = editText.getText().toString();
Log.d("!!!","clicked text -> "+editText.getText().toString());
if(text.length() > 0) {
cv.put(MyProvider.TEXT, text);
Uri newUri = ContentUris.withAppendedId(MyProvider.CONTENT_URI,Long.valueOf(updId));
getContentResolver().update(newUri, cv,null,null);
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// updateCursor(cursor);
}
itemUpdateLayout.setVisibility(View.GONE);
itemViewLayout.setVisibility(View.VISIBLE);
}
});
editText.setText(textView.getText());
itemUpdateLayout.setVisibility(View.VISIBLE);
itemViewLayout.setVisibility(View.INVISIBLE);
}
});
mainActivity.insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment insertFragment = new Insert();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, insertFragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
mainActivity.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(chekedItems.size() > 0){
for (int i = 0; i < chekedItems.size(); i++) {
Uri newUri = ContentUris.withAppendedId(MyProvider.CONTENT_URI,chekedItems.get(i));
getContentResolver().delete(newUri,null,null);
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// updateCursor(cursor);
}
chekedItems.clear();
}else{
Toast.makeText(MainActivity.this,"Nothing selected",Toast.LENGTH_SHORT).show();
}
}
});
}
private void stethoInit() {
// Create an InitializerBuilder
Stetho.InitializerBuilder initializerBuilder =
Stetho.newInitializerBuilder(this);
// Enable Chrome DevTools
initializerBuilder.enableWebKitInspector(
Stetho.defaultInspectorModulesProvider(this)
);
// Enable command line interface
initializerBuilder.enableDumpapp(
Stetho.defaultDumperPluginsProvider(this)
);
// Use the InitializerBuilder to generate an Initializer
Stetho.Initializer initializer = initializerBuilder.build();
// Initialize Stetho with the Initializer
Stetho.initialize(initializer);
}
#Override
public void updateCursor(Cursor newCusor) {
scAdapter.changeCursor(newCusor);
scAdapter.notifyDataSetChanged();
//hide keyboard
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
private class MyAdapter extends SimpleCursorAdapter{
private int layout;
public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
final String id = cursor.getString(colId);
String title = cursor.getString(colText);
TextView idView = (TextView)view.findViewById(R.id.itemId);
idView.setText(id);
TextView textView = (TextView)view.findViewById(R.id.itemText);
textView.setText(title);
CheckBox checkBox = (CheckBox)view.findViewById(R.id.itemCheckBox);
checkBox.setChecked(false);
checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!chekedItems.contains(Integer.valueOf(id))){
chekedItems.add(Integer.valueOf(id));
}else{
chekedItems.remove(chekedItems.indexOf(Integer.valueOf(id)));
}
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = getLayoutInflater().inflate(layout,parent,false);
return view;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
}
}
Insert Fragment
package com.example.lesson101_contentprovider_creation_h.fragments;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.lesson101_contentprovider_creation_h.MainActivity;
import com.example.lesson101_contentprovider_creation_h.MyProvider;
import com.example.lesson101_contentprovider_creation_h.R;
import com.example.lesson101_contentprovider_creation_h.databinding.FragmentInsertBinding;
import com.example.lesson101_contentprovider_creation_h.interfaces.IUpdateCursor;
/**
* A simple {#link Fragment} subclass.
*/
public class Insert extends Fragment{
Activity activity;
public Insert() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.activity = (Activity)context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FragmentInsertBinding insertBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_insert,container,false);
View v = insertBinding.getRoot();
insertBinding.insertRecButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContentValues cv = new ContentValues();
String text = insertBinding.insertTextField.getText().toString();
if(text.length() > 0) {
cv.put(MyProvider.TEXT, text);
getContext().getContentResolver().insert(MyProvider.CONTENT_URI, cv);
getActivity().getSupportFragmentManager().beginTransaction().remove(Insert.this).commit();
insertBinding.insertTextField.clearFocus();
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContext().getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// ((IUpdateCursor)activity).updateCursor(cursor);
}
}
});
// Inflate the layout for this fragment
return v;
}
// public interface IUpdateCursor{
// void updateCursor(Cursor newCursor);
// }
}
MyProvider
package com.example.lesson101_contentprovider_creation_h;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by den on 2017-03-31.
*/
public class MyProvider extends ContentProvider{
private final String DB_NAME = "my";
private int DB_VERSION = 1;
private static final String AUTHORITY = "com.example.lesson101_contentprovider_creation_h";
private static final String PATH = "table";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH);
public static final String DB_TABLE = "MYTABLE";
public static final String ID = "_id";
public static final String TEXT = "text";
private final String CREATE_DB = "CREATE TABLE " + DB_TABLE + " ("
+ ID + " integer primary key autoincrement, "
+ TEXT + " text);";
private DBHelper dbHelper;
private SQLiteDatabase database;
private static final int TABLE = 1;
private static final int TABLE_ID = 2;
static final String CONTACT_CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd."
+ AUTHORITY + "." + PATH;
private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, PATH, TABLE);
uriMatcher.addURI(AUTHORITY, PATH + "/#", TABLE_ID);
}
#Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection,
#Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
sortOrder = ID;
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
sortOrder = TEXT;
break;
}
Cursor cursor = database.query(DB_TABLE,projection,selection,selectionArgs,null,null,sortOrder);
Log.d("!!!","query -> "+uri.toString());
cursor.setNotificationUri(getContext().getContentResolver(),CONTENT_URI);
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
return CONTACT_CONTENT_ITEM_TYPE;
}
return null;
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues values) {
database = dbHelper.getWritableDatabase();
Log.d("!!!","insert -> "+uri.toString());
if(uriMatcher.match(uri) != TABLE)
throw new IllegalArgumentException("Wrong URI: "+uri);
long id = database.insert(DB_TABLE,null,values);
Uri resultUri = ContentUris.withAppendedId(CONTENT_URI,id);
Log.d("!!!","insert after -> "+resultUri.toString());
getContext().getContentResolver().notifyChange(resultUri,null);
return resultUri;
}
#Override
public int delete(#NonNull Uri uri, #Nullable String selection, #Nullable String[] selectionArgs) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
selection = ID + " = " + id;
break;
}
int c = database.delete(DB_TABLE,selection,selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return c;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues values, #Nullable String selection, #Nullable String[] selectionArgs) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
selection = ID + " = " +id;
Log.d("!!!",id);
break;
}
int c = database.update(DB_TABLE,values,selection,null);
getContext().getContentResolver().notifyChange(uri, null);
return c;
}
private class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
updateDB(db,0,DB_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private void updateDB(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion < 1)
db.execSQL(CREATE_DB);
}
}
}

Did you check if the uri used in setNotificationUri is matching the ones used in the getContext().getContentResolver().notifyChange()?
Cursor.setNotificationUri()
will register for the underline uri for the
getContext().getContentResolver().notifyChange(uri, null);
which is called when such as at ContentProvider's insert(), update() and delete() calls, so the Cursor (has setNotificationUri()) will be notified.
If you are using CursorAdapter, by default, CursorAdapter objects will get this notification issued by getContext().getContentResolver().notifyChange.
Another thing to make sure not to do cursor.close(), the close() will cause unregister the content observer which was registered by CursorLoader. And the cursor closing is managed by CursorLoader.

Related

Inconvertible types; cannot cast 'android.content.Context' to 'com.example.xxxxx.PendingListFragment'

I'm try to set button on list view using CursorLoader. But it gives me error message saying
Inconvertible types; cannot cast 'android.content.Context' to 'com.example.xxxxx.PendingListFragment'.
I'm new to android, please answer.
#Override
public void bindView(View view, final Context context, Cursor cursor) {
final Button signUpButton = view.findViewById(R.id.sign_up_button);
TextView nameTextView = view.findViewById(R.id.name);
final int id = cursor.getColumnIndex(InfoContract.InfoEntry._ID);
int nameColumnIndex =
cursor.getColumnIndex(InfoContract.InfoEntry.COLUMN_NAME);
String name = cursor.getString(nameColumnIndex);
String phoneNumber = cursor.getString(phoneNumberColumnIndex);
final String col = cursor.getString(id);
nameTextView.setText(name);
signUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PendingListFragment pendingListFragment = (PendingListFragment)context;
pendingListFragment.upDateStatus(Integer.valueOf(col), InfoContract.InfoEntry.STATUS_SIGN_UP);
}
});
}
Code for PendingListFragment is here
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.xxxxx.data.InfoContract;
public class PendingListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int INFO_LOADER = 0;
PendingListCursorAdapter pendingListCursorAdapter;
Cursor cursor;
private ListView mInfoListView;
private View mEmptyView;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstantState) {
View view = inflater.inflate(R.layout.fragment_pending_list, container, false);
mInfoListView = view.findViewById(R.id.pending_list_view);
mEmptyView = view.findViewById(R.id.empty_view);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onViewCreated(#NonNull View view, Bundle savedInstantState) {
super.onViewCreated(view, savedInstantState);
getActivity().setTitle("Pending List");
pendingListCursorAdapter = new PendingListCursorAdapter(getActivity(), null);
mInfoListView.setAdapter(pendingListCursorAdapter);
getLoaderManager().initLoader(INFO_LOADER, null, PendingListFragment.this);
mInfoListView.setEmptyView(mEmptyView);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
InfoContract.InfoEntry._ID,
InfoContract.InfoEntry.COLUMN_NAME,
InfoContract.InfoEntry.COLUMN_MOBILE_NUMBER,
InfoContract.InfoEntry.COLUMN_DATE,
InfoContract.InfoEntry.COLUMN_STATUS
};
return new CursorLoader(getContext(),
InfoContract.InfoEntry.CONTENT_URI,
projection,
null,
null,
null);
}
public void upDateStatus(Integer id, int status) {
ContentValues values = new ContentValues();
values.put(InfoContract.InfoEntry.COLUMN_STATUS, status);
Uri upDateUri = ContentUris.withAppendedId(InfoContract.InfoEntry.CONTENT_URI, id);
int rowsAffected = getActivity().getContentResolver().update(upDateUri, values, null, null);
}
#Override
public void onLoadFinished(#NonNull Loader<Cursor> loader, Cursor cursor) {
pendingListCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(#NonNull Loader<Cursor> loader) {
pendingListCursorAdapter.swapCursor(null);
}
}
`
when button is clicked it need to update database.
PendingListFragment pendingListFragment = new PendingListFragment(); initialise like this
The error is thrown because you are trying to type cast current context of the application to PendingListFragment which is wrong and since you simply need to call the method of your PendingListFragment all you need to do is create it's object which can be acheived in java by make use of new keyword.
So to do that simply write
PendingListFragment pendingListFragment = new PendingListFragment(); //this will create new object of your PendingListFragmnet which will allow you to access it's method.
pendingListFragment.upDateStatus(Integer.valueOf(col), InfoContract.InfoEntry.STATUS_SIGN_UP);
Also make sure that your upDateStatus method is public.

Sorting a multi view type RecyclerView according to month and year

I am using a multiview type RecyclerView and the header should display the name of month and year and further in items I am loading images from gallery using Glide. First of all, I want that the name of month and year should be displayed on every header and then the images should belong to that particular month and year only.
I want my Multiview to look like this
Screenshot
Here is my code
GalleryAdapter.java
package com.jumptotv.adapter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.CursorLoader;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.jumptotv.GlideApp;
import com.jumptotv.R;
import com.jumptotv.model.HeaderModel;
import com.jumptotv.model.Movie;
import com.jumptotv.view.activity.FullScreenActivity;
import com.jumptotv.view.activity.MainActivity;
import com.jumptotv.view.activity.VideoActivity;
import com.jumptotv.view.activity.VideoPlayActivity;
import com.jumptotv.view.fragment.GalleryFragment;
import java.io.File;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class GalleryAdapter2 extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private List<HeaderModel> moviesList;
private ArrayList<String> imageData;
final int HEADER = 0;
final int ITEMS = 1;
int n = 0;
String sort[];
String month[] = {"DAY", "TODAY", "SEP 1", "SEP 2", "SEP 3", "OCT 2018", "NOV 2018", "DEC 2018", "JAN 2017", "FEB 2017"};
public GalleryAdapter2(ArrayList<String> imageData, Context context, List<HeaderModel> moviesList) {
this.imageData = imageData;
this.context = context;
this.moviesList = moviesList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == HEADER) {
view = LayoutInflater.from(context).inflate(R.layout.header_type_layout, parent, false);
return new Header2(view);
} else if (viewType == ITEMS) {
view = LayoutInflater.from(context).inflate(R.layout.grid_type_layout, parent, false);
return new MyViewHolde(view);
}
throw new RuntimeException("No match found");
}
#Override
public int getItemViewType(int position) {
int viewType = ITEMS; //Default is 1
if (position % 16 == 0) {
viewType = HEADER;
}
//return position;
//if zero, it will be a header view
return viewType;
}
private String getItem(int position)
{
return imageData.get(position);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final int itemType = getItemViewType(position);
switch (holder.getItemViewType()) {
case 1:
final String data = imageData.get(position);
String data2 = GalleryAdapter2.getMimeType(data);
if (data != null) {
if (data2.equals("jpg") || (data2.equals("png")) || (data2.equals("tif")) || (data2.equals("gif"))) {
((MyViewHolde) holder).play.setVisibility(View.GONE);
GlideApp.with(context)
.load(data)
.placeholder(R.drawable.gallery_39)
.into(((MyViewHolde) holder).singleImageView);
((MyViewHolde) holder).singleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, FullScreenActivity.class);
intent.putExtra(FullScreenActivity.IMAGE_POSITION, position);
context.startActivity(intent);
}
});
} else if (data2.equals("mkv") || (data2.equals("flv")) || (data2.equals("mov")) || (data2.equals("mp4")) || (data2.equals("3gp")) || (data2.equals("wmv")) || (data2.equals("mpg") || (data2.equals("avc")) || (data2.equals("UNKNOWN")))) {
Glide.with(context).load(data).into(((MyViewHolde) holder).singleImageView);
((MyViewHolde) holder).play.setVisibility(View.VISIBLE);
((MyViewHolde) holder).play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, VideoPlayActivity.class);
intent.putExtra("video_url", data);
intent.putExtra(VideoPlayActivity.VIDEO_POSITION, position);
context.startActivity(intent);
}
});
}
} else {
}
break;
case 0:
n++;
if(n==10)
{
n=6;
n++;
}
((Header2) holder).textView.setText(month[n]);
break;
//Header2 header2=new Header2(View itemView);
// bindHeaderItem(,position);
//((Header2) holder).textView.setText(month[n]);
/*if(position==0)
{
n=n+1;
}
*/
}
}
#Override
public int getItemCount() {
return imageData.size();
}
public boolean isHeader(int position) {
return position == 0;
}
public static String getMimeType(String url) {
Uri uri = Uri.parse(url);
String extension = MimeTypeMap.getFileExtensionFromUrl(uri.getPath());
return extension;
}
public class MyViewHolde extends RecyclerView.ViewHolder {
ImageView singleImageView, play;
public MyViewHolde(View itemView) {
super(itemView);
singleImageView = (ImageView) itemView.findViewById(R.id.gallery);
play = (ImageView) itemView.findViewById(R.id.play_video2);
}
}
public class Header2 extends RecyclerView.ViewHolder {
TextView textView;
public Header2(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.headerTitle);
// textView.setText(month[n]);
}
}
private void bindHeaderItem(Header2 holder, int position) {
TextView title = (TextView) holder.textView.findViewById(R.id.headerTitle);
title.setText(moviesList.get(position).getTitle());
}
}
GalleryFragment
package com.jumptotv.view.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.CursorLoader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.jumptotv.R;
import com.jumptotv.Utility;
import com.jumptotv.adapter.GalleryAdapter;
import com.jumptotv.adapter.GalleryAdapter2;
import com.jumptotv.model.HeaderModel;
import com.jumptotv.model.Model_Video;
import com.jumptotv.model.Movie;
import com.jumptotv.view.activity.FullScreenActivity;
import com.jumptotv.view.activity.VideoActivity;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class GalleryFragment extends Fragment {
public GalleryFragment() {
}
private Context context;
private List<HeaderModel> movieList = new ArrayList<>();
private RecyclerView recyclerView;
ArrayList<String> imageData;
GalleryAdapter2 adapter;
ImageView gallery,play,back_button;
String title;
Button play_video;
Uri uri;
TextView header;
Cursor cursor;
int column_index_data=0, column_index_folder_name;
ArrayList<String> listOfAllImages = new ArrayList<String>();
String absolutePathOfImage = null;
String month[] = {"TODAY", "SEP 1", "SEP 2","SEP 3","OCT 2018,NOV 2018,DEC 2018,JAN 2017,FEB 2017"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
context = getActivity();
HeaderModel headerModel =new HeaderModel("TODAY");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow1");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow2");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow3");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorro4");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow5");
movieList.add(headerModel);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewList);
recyclerView.setHasFixedSize(true);
back_button=(ImageButton)view.findViewById(R.id.back_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment someFragment = new FileFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.main_frame, someFragment ); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
}
});
header=(TextView)view.findViewById(R.id.see_all);
final View view2 = inflater.inflate(R.layout.grid_type_layout, container, false);
Bundle bundle = this.getArguments();
if(bundle != null) {
title = bundle.get("key").toString();
}
gallery=(ImageView)view2.findViewById(R.id.gallery);
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
}
});
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (position %16 == 0) ? 3 : 1;
}
});
recyclerView.setLayoutManager(layoutManager);
MyTask myTask = new MyTask();
myTask.execute();
return view;
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
boolean flag = Utility.checkReadStoragePermission(getActivity(),GalleryFragment.this);
if (flag) {
imageData= getAllShownImagesPath(getActivity());
Log.e("imageData: ", String.valueOf(imageData.size()));
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new GalleryAdapter2(imageData,getActivity(),movieList);
recyclerView.setAdapter(adapter);
}
}
private ArrayList<String> getAllShownImagesPath(Activity activity) {
if(title.equals("All Photos"))
{
// header.setText("All Photos");
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getActivity().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
}
else if(title.equals("All Videos"))
{
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
header.setText(title);
// Stuff that updates the UI
}
});
//header.setText("All Videos");
int column_id,thum;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME,MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
final String orderBy = MediaStore.Images.Media.DATE_ADDED;
cursor = getActivity().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
column_id = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
Log.e("column_id", cursor.getString(column_id));
Log.e("thum", cursor.getString(thum));
listOfAllImages.add(absolutePathOfImage);
}
}
else if(title.equals("All Files")){
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
header.setText(title);
String[] projection = {
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.TITLE
}; // used for query ContentResolver for mediafiles
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO; // used to select images and videos from contentResolver
Uri queryUri = MediaStore.Files.getContentUri("external");
CursorLoader cursorLoader = new CursorLoader(getActivity(),queryUri, projection, selection, null, MediaStore.Files.FileColumns.DATE_ADDED + " DESC");
cursor = cursorLoader.loadInBackground();
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
}
});
}
return listOfAllImages;
}
}

viewpager first item doesn't show content

I know there is lots of threads talk about first item problems in viewpager, I searched many time about my issue but no way I just lose time.
would you help me, please ?
I use FragmentStatePagerAdapter , fragment and loader manager that add radio buttons dynamically. the first iitem in view pager doesn't show radio buttons until I swipe to third item and back again to the first one.
screen
Image
Fragment:
package mohalim.android.egybankstest.Fragments;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import mohalim.android.egybankstest.Database.AppContract;
import mohalim.android.egybankstest.Models.Choice;
import mohalim.android.egybankstest.Models.Question;
import mohalim.android.egybankstest.R;
import mohalim.android.egybankstest.ResultActivity;
public class QuizFragement extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private static final String UPDATE = "update";
private static final int GET_CHOICES_LOADER_ID = 100;
private static final int UPDATE_CHOSEN_ANSWER_LOADER_ID = 101;
private static final String SELECTED_QUIZ = "selected_quiz";
ArrayList<Question> questions;
ArrayList<Choice> choices;
int questionPosition;
String selectedQuiz;
RadioGroup radioGroup;
TextView questionText;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
choices = new ArrayList<>();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.quiz_fragment, container, false);
questionText = view.findViewById(R.id.m);
radioGroup = view.findViewById(R.id.choices_radio);
radioGroup.removeAllViews();
questionText.setText(questions.get(questionPosition).getQuestion_text());
if (questionPosition == 0){
getActivity().getSupportLoaderManager()
.initLoader(GET_CHOICES_LOADER_ID,null,this)
.forceLoad();
}else {
getActivity().getSupportLoaderManager()
.restartLoader(GET_CHOICES_LOADER_ID,null,this)
.forceLoad();
}
/**
* end the session
*/
FloatingActionButton fab = view.findViewById(R.id.end_session);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ResultActivity.class);
intent.putExtra(SELECTED_QUIZ,selectedQuiz);
startActivity(intent);
getActivity().finish();
}
});
return view;
}
#NonNull
#Override
public Loader<Cursor> onCreateLoader(int id, #Nullable final Bundle args) {
if (id==GET_CHOICES_LOADER_ID){
Uri choicesUri = AppContract.ChoiceEntry.CONTENT_URI
.buildUpon()
.appendPath(String.valueOf(questions.get(questionPosition).getQuestionId()))
.build();
String questionId = String.valueOf(questions.get(questionPosition).getQuestionId());
String questionIDSelection = AppContract.ChoiceEntry.COLUMN_QUESTION_ID + "=?";
String[] questionIDSelectionArgs = new String[]{questionId};
return new CursorLoader(
getActivity(),
choicesUri,
null,
questionIDSelection,
questionIDSelectionArgs,
null
);
}else if(id == UPDATE_CHOSEN_ANSWER_LOADER_ID){
return new AsyncTaskLoader<Cursor>(getActivity()) {
#Nullable
#Override
public Cursor loadInBackground() {
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Uri updateChosenUri = AppContract.QuestionsEntry.CONTENT_URI
.buildUpon()
.appendPath(UPDATE)
.appendPath(String.valueOf(questions.get(questionPosition).getQuestionId())).build();
ContentValues contentValues = new ContentValues();
contentValues.put(AppContract.QuestionsEntry.COLUMN_ANSWER_CHOSEN,checkedId);
if (group.getChildAt(checkedId-1).getTag().toString().equals("1")){
contentValues.put(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT, 1);
}else if (group.getChildAt(checkedId-1).getTag().toString().equals("0")){
contentValues.put(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT, 0);
}
getActivity().getContentResolver().update(updateChosenUri,contentValues,null,null);
Cursor cursor = getActivity().getContentResolver().query(
AppContract.QuestionsEntry.CONTENT_URI.buildUpon().appendPath(String.valueOf(questions.get(questionPosition).getQuestionId())).build(),
null,null,null,null
);
if (cursor.getCount() == 1){
cursor.moveToFirst();
Log.v("string", cursor.getInt(cursor.getColumnIndex(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT))+"");
Log.v("string 2", group.getChildAt(radioGroup.getCheckedRadioButtonId()-1).getTag().toString());
}
}
});
return null;
}
};
}
return null;
}
#Override
public void onLoadFinished(#NonNull Loader<Cursor> loader, Cursor choicesCursor) {
if (questionPosition == 0){
Toast.makeText(getActivity(), ""+selectedQuiz, Toast.LENGTH_SHORT).show();
}
if (loader.getId() == GET_CHOICES_LOADER_ID){
if (choicesCursor.getCount() >0){
while (choicesCursor.moveToNext()){
String text = choicesCursor.getString(choicesCursor.getColumnIndex(AppContract.ChoiceEntry.COLUMN_CHOICE_TEXT));
int is_correct = choicesCursor.getInt(choicesCursor.getColumnIndex(AppContract.ChoiceEntry.COLUMN_IS_TRUE));
Choice choice = new Choice();
choice.setChoiceText(text);
choice.setCorrect(is_correct);
choices.add(choice);
}
for (int i=0; i<choices.size();i++){
LayoutInflater inflater = LayoutInflater.from(getContext());
final View radioButton = inflater.inflate(R.layout.radio_button,radioGroup,false);
((RadioButton) radioButton).setText(choices.get(i).getChoiceText());
radioButton.setTag(choices.get(i).isCorrect());
radioGroup.addView(radioButton);
}
for (int i = 0; i<radioGroup.getChildCount();i++){
radioGroup.getChildAt(i).setId(i+1);
}
}
if (questionPosition == 0){
getActivity().getSupportLoaderManager()
.initLoader(
UPDATE_CHOSEN_ANSWER_LOADER_ID,
null,
this).forceLoad();
}else {
getActivity().getSupportLoaderManager()
.restartLoader(
UPDATE_CHOSEN_ANSWER_LOADER_ID,
null,
this).forceLoad();
}
}
}
#Override
public void onLoaderReset(#NonNull Loader<Cursor> loader) {
}
public void setQuestions(ArrayList<Question> questions) {
this.questions = questions;
}
public void setQuestionPosition(int questionPosition) {
this.questionPosition = questionPosition;
}
public ArrayList<Question> getQuestions() {
return questions;
}
public int getQuestionPosition() {
return questionPosition;
}
public void setSelectedQuiz(String selectedQuiz) {
this.selectedQuiz = selectedQuiz;
}
}
ViewPagerAdapter
package mohalim.android.egybankstest.Adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import mohalim.android.egybankstest.Fragments.QuizFragement;
import mohalim.android.egybankstest.Models.Question;
public class MyQuizPager extends FragmentStatePagerAdapter {
ArrayList<Question> questions;
String selectedQuiz;
public MyQuizPager(FragmentManager fm, ArrayList<Question> questions, String selectedQuiz) {
super(fm);
this.questions = questions;
this.selectedQuiz = selectedQuiz;
}
#Override
public Fragment getItem(int position) {
QuizFragement fragment = new QuizFragement();
fragment.setQuestions(questions);
fragment.setQuestionPosition(position);
fragment.setSelectedQuiz(selectedQuiz);
return fragment;
}
#Override
public int getCount() {
return questions.size();
}
#Override
public int getItemPosition(Object object) {
QuizFragement fragment = (QuizFragement) object;
int position = fragment.getQuestionPosition();
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
}
}
All code is here
Finnaly I found the solution:
Quate:
By default it is viewpager.setOffscreenPageLimit(1) , meaning View
pager will by default load atleast 1 on the right and one on the left
tab of current tab.
https://stackoverflow.com/a/47054077/5862361
when i start quizActivity viewpager load the first item and the second too so the loadermanager restart before complete its work.
I solved it by adding another loadermanger
one for the first item and the second for the second one:
if (questionPosition == 0){
if (getActivity().getSupportLoaderManager() == null){
getActivity().getSupportLoaderManager().initLoader(
GET_CHOICES_LOADER_ID_FIRST,
null,
this
).forceLoad();
}else{
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID_FIRST,
null,
this
).forceLoad();
}
}else if (questionPosition == 1){
if (getActivity().getSupportLoaderManager() == null){
getActivity().getSupportLoaderManager().initLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}else {
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}
}else {
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}

ContentLoader on MediaStore, and automatic refresh/reload

I'm querying the MediaStore, joining Images and Thumbnails, and loading in a GridView. This works fine enough, but I can't figure out how to update my app when a new photo appears in the MediaStore (typically when taken by the camera). The default gallery app automatically loads the new image, but my app does nothing. I've tried registering content observers, and I've even tried adding a manual "refresh" menu button, but the only way to load the new image is to stop and restart the entire app.
Edit
Actually, that's not entirely true. If I take a new photo, and switch to some other gallery app or widget, then this other app will load the new image (thumbnail) and my app will then suddenly also refresh. This indicates that I am observing some events, right, since the new thumbnail eventually appears automatically in my app? Maybe I'm just not observing the right ones. I just don't understand how the manual refresh accomplishes nothing.
I'm posting the relevant java files, maybe someone can see what I'm forgetting, or am doing wrong?
I'm at a loss, been working at this for quite some time, so please forgive me if the post is too vague. I'll try to add whatever details are missing.
PhotoFragment
package com.example.android.galleri.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;
import com.example.android.galleri.app.data.PhotoContract;
public class PhotoFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private final static int LOADER_ID = 87;
private PhotoAdapter mPhotoAdapter;
private int mPosition;
private GridView mGridView;
private TextView mEmptyView;
private int count_mem = -1;
private static final String SELECTED_KEY = "POSITION";
private boolean mTwoPane;
private boolean DF_hidden = false;
// these are the data we want from MediaStore
private final static String[] THUMBNAIL_COLUMNS = {
PhotoContract.ThumbEntry.COLUMN_THUMB_ID,
PhotoContract.ThumbEntry.COLUMN_DATA,
PhotoContract.ThumbEntry.COLUMN_IMAGE_ID,
PhotoContract.ThumbEntry.COLUMN_TITLE,
PhotoContract.ThumbEntry.COLUMN_DESC,
PhotoContract.ThumbEntry.COLUMN_DATE
};
static final int COL_THUMB_ID = 0;
static final int COL_THUMB_DATA = 1;
static final int COL_THUMB_IMAGE_ID = 2;
static final int COL_TITLE = 3;
static final int COL_DESC = 4;
static final int COL_DATE = 5;
public void setTwoPaneUI(boolean pTwoPane) {
mTwoPane = pTwoPane;
}
// interfaces
public interface Callback {
public void onItemSelected(Uri photoUri);
}
public interface FragmentCallback {
public void onTaskDone(int count);
}
public PhotoFragment() {
}
public int getPosition() {
return mPosition;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
getLoaderManager().initLoader(LOADER_ID, null, this);
super.onActivityCreated(savedInstanceState);
}
public void onNewCameraEvent() {
Log.v("JOAKIM", "PhotoFragment.onNewCameraEvent() triggering a refresh...");
restartLoader();
}
// https://stackoverflow.com/questions/22241705/calling-a-activity-method-from-broadcastreceiver-in-android
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// internet lost alert dialog method call from here...
Log.v("JOAKIM", "PhotoFragment.broadcastReceiver.onReceive() captured the image!");
onNewCameraEvent();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().registerReceiver(broadcastReceiver, new IntentFilter("TRIGGER_A_REFRESH"));
}
#Override
public void onDestroy() {
super.onDestroy();
getActivity().unregisterReceiver(broadcastReceiver);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.photofragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
Log.v("JOAKIM", "PhotoFragment.onOptionsItemSelected() refresh clicked");
// https://stackoverflow.com/questions/15271271/android-callback-asynctask-to-fragmentnot-activity
ManualRefreshTask refreshTask = new ManualRefreshTask(
new FragmentCallback() {
#Override
public void onTaskDone(int count) {
// loader is restarted every time, since I couldn't
// get the logic to work 100%
restartLoader();
/*
// if the number of images has changed, restart loader
if (count != count_mem) restartLoader();
*/
count_mem = count;
}
});
refreshTask.execute(getActivity().getContentResolver());
return true;
}
return super.onOptionsItemSelected(item);
}
public void restartLoader() {
getLoaderManager().restartLoader(LOADER_ID, null, this);
}
#Override
public void onSaveInstanceState(Bundle outState) {
if (mPosition != GridView.INVALID_POSITION) {
outState.putInt(SELECTED_KEY, mPosition);
}
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mPhotoAdapter = new PhotoAdapter(getActivity(), null, 0);
GridView gridView = (GridView) rootView.findViewById(R.id.listview_photo);
gridView.setAdapter(mPhotoAdapter);
mEmptyView = (TextView) rootView.findViewById(R.id.list_empty);
mGridView = gridView;
// handle user clicking on an image
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
if (cursor != null) {
Uri baseUri = PhotoContract.PhotoEntry.buildPhotoUriWithId(cursor.getLong(COL_THUMB_IMAGE_ID));
Log.v("JOAKIM", "PhotoFragment.onItemClick() image_id = " + cursor.getLong(COL_THUMB_IMAGE_ID)
+ ", baseUri = " + baseUri.toString());
// make sure detail fragment is visible
if (mTwoPane) showDetailFragment();
else Utility.setPosition(position); // else (single-pane): store position clicked!
((Callback)getActivity()).onItemSelected(baseUri);
}
mPosition = position;
}
});
if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
mPosition = savedInstanceState.getInt(SELECTED_KEY);
}
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
Uri thumbs_uri = PhotoContract.ThumbEntry.CONTENT_URI;
return new CursorLoader(getActivity(), thumbs_uri, THUMBNAIL_COLUMNS,
null,null, // read everything (all thumbnails)
PhotoContract.ThumbEntry.COLUMN_THUMB_ID + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
if (cursor != null) {
// register observer onto cursor
cursor.setNotificationUri(getActivity().getContentResolver(), PhotoContract.ThumbEntry.CONTENT_URI);
mPhotoAdapter.swapCursor(cursor);
if (mPosition != GridView.INVALID_POSITION) {
mGridView.setSelection(mPosition); // scroll into view
}
}
// save (set) cursor in Utility
Utility.setCursor(cursor);
if (cursor == null) {
mEmptyView.setText("No Images on Device");
mEmptyView.setVisibility(View.VISIBLE);
if (mTwoPane) {
mGridView.setVisibility(View.GONE);
hideDetailFragment();
}
} else {
mEmptyView.setVisibility(View.GONE);
if (mTwoPane) {
mGridView.setVisibility(View.VISIBLE);
showDetailFragment();
}
}
}
public void hideDetailFragment() {
if (!DF_hidden) {
Log.v("JOAKIM", "PhotoFragment.onLoadFinished() remove detail framelayout");
FrameLayout container = (FrameLayout) getActivity().findViewById(R.id.photo_detail_container);
container.setVisibility(View.GONE);
DF_hidden = true;
Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
int numColumns = 10;
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) numColumns = 8;
else numColumns = 10;
mGridView.setNumColumns(numColumns);
}
}
public void showDetailFragment() {
if (DF_hidden) {
Log.v("JOAKIM", "PhotoFragment.onLoadFinished() show detail fragment");
FrameLayout container = (FrameLayout) getActivity().findViewById(R.id.photo_detail_container);
container.setVisibility(View.VISIBLE);
DF_hidden = false;
mGridView.setNumColumns(6);
}
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mPhotoAdapter.swapCursor(null);
}
}
PhotoContract
package com.example.android.galleri.app.data;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
public class PhotoContract {
public static final String CONTENT_AUTHORITY = "com.example.android.galleri.app";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final String PATH_THUMBS = "thumbs";
public static final String PATH_PHOTO = "photo";
public static final String PATH_COMMENT = "comment";
//public static final String PATH_AUTHOR = "author";
// define updateable fields (where to update them)
public static final String TARGET_EXIF = "EXIF";
public static final String TARGET_MEDIASTORE = "MediaStore.Images.Media";
public static final String TARGET_MEDIASTORE_THUMBS = "MediaStore.Images.Thumbnails";
public static final class ThumbEntry {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_THUMBS).build();
public static final String COLUMN_THUMB_ID = MediaStore.Images.Thumbnails._ID;
public static final String COLUMN_DATA = MediaStore.Images.Thumbnails.DATA;
public static final String COLUMN_IMAGE_ID = MediaStore.Images.Thumbnails.IMAGE_ID;
public static final String COLUMN_IMAGE_PK = MediaStore.Images.Media._ID;
public static final String COLUMN_TITLE = MediaStore.Images.Media.TITLE;
public static final String COLUMN_DESC = MediaStore.Images.Media.DESCRIPTION;
public static final String COLUMN_DATE = MediaStore.Images.Media.DATE_TAKEN;
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_THUMBS;
public static final Map<String, String> COL_TYPES;
static {
COL_TYPES = new HashMap<String, String>();
COL_TYPES.put(COLUMN_THUMB_ID, TARGET_MEDIASTORE_THUMBS);
COL_TYPES.put(COLUMN_DATA, TARGET_MEDIASTORE_THUMBS);
COL_TYPES.put(COLUMN_IMAGE_ID, TARGET_MEDIASTORE_THUMBS);
COL_TYPES.put(COLUMN_TITLE, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_DESC, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_DATE, TARGET_MEDIASTORE);
}
}
public static final class PhotoEntry {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_PHOTO).build();
public static final String COLUMN_IMAGE_ID = MediaStore.Images.Media._ID;
public static final String COLUMN_DISPLAY_NAME = MediaStore.Images.Media.DISPLAY_NAME;
public static final String COLUMN_DATA = MediaStore.Images.Media.DATA;
public static final String COLUMN_DESC = MediaStore.Images.Media.DESCRIPTION;
public static final String COLUMN_DATE_TAKEN = MediaStore.Images.Media.DATE_TAKEN;
public static final String COLUMN_DATE_ADDED = MediaStore.Images.Media.DATE_ADDED;
public static final String COLUMN_TITLE = MediaStore.Images.Media.TITLE;
public static final String COLUMN_SIZE = MediaStore.Images.Media.SIZE;
public static final String COLUMN_ORIENTATION = MediaStore.Images.Media.ORIENTATION;
public static final String COLUMN_HEIGHT = MediaStore.Images.Media.HEIGHT;
public static final String COLUMN_WIDTH = MediaStore.Images.Media.WIDTH;
public static final String COLUMN_EXIF_COMMENT = "UserComment";
public static final String COLUMN_EXIF_AUTHOR = "Author";
public static final Map<String, String> COL_TYPES;
static {
COL_TYPES = new HashMap<String, String>();
COL_TYPES.put(COLUMN_IMAGE_ID, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_DISPLAY_NAME, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_DATA, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_DESC, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_DATE_TAKEN, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_DATE_ADDED, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_TITLE, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_SIZE, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_ORIENTATION, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_HEIGHT, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_WIDTH, TARGET_MEDIASTORE);
COL_TYPES.put(COLUMN_EXIF_COMMENT, TARGET_EXIF);
COL_TYPES.put(COLUMN_EXIF_AUTHOR, TARGET_EXIF);
}
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_PHOTO;
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_PHOTO;
// makes an URI to a specific image_id
public static final Uri buildPhotoUriWithId(Long photo_id) {
return CONTENT_URI.buildUpon().appendPath(Long.toString(photo_id)).build();
}
// since we will "redirect" the URI towards MediaStore, we need to be able to extract IMAGE_ID
public static Long getImageIdFromUri(Uri uri) {
return Long.parseLong(uri.getPathSegments().get(1)); // always in position 1
}
}
}
PhotoProvider
package com.example.android.galleri.app.data;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.AbstractWindowedCursor;
import android.database.Cursor;
import android.database.CursorJoiner;
import android.database.CursorWindow;
import android.database.CursorWrapper;
import android.database.MatrixCursor;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Map;
public class PhotoProvider extends ContentProvider {
// The URI Matcher used by this content provider.
private static final UriMatcher sUriMatcher = buildUriMatcher();
// query: get all thumbnails, or get specific image
static final int THUMBS = 100;
static final int PHOTO = 101;
static final int FIRST_PHOTO = 102;
// update: set comment etc
static final int PHOTO_COMMENT = 200;
static UriMatcher buildUriMatcher() {
// 1) The code passed into the constructor represents the code to return for the root
// URI. It's common to use NO_MATCH as the code for this case. Add the constructor below.
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = PhotoContract.CONTENT_AUTHORITY;
// 2) Use the addURI function to match each of the types. Use the constants from
// WeatherContract to help define the types to the UriMatcher.
// get all thumbnails (with a JOIN towards MediaStore.Images, to get title and description, too)
matcher.addURI(authority, PhotoContract.PATH_THUMBS, THUMBS);
// matches photo (no ID). Means get first image
matcher.addURI(authority, PhotoContract.PATH_PHOTO, FIRST_PHOTO);
// matches photo/<any number> meaning any photo ID
matcher.addURI(authority, PhotoContract.PATH_PHOTO + "/#", PHOTO);
// matches photo/<photo id>/comment/ (comment text in ContentValues)
matcher.addURI(authority, PhotoContract.PATH_PHOTO + "/#/" + PhotoContract.PATH_COMMENT, PHOTO_COMMENT);
// 3) Return the new matcher!
return matcher;
}
#Override
public String getType(Uri uri) {
// Use the Uri Matcher to determine what kind of URI this is.
final int match = sUriMatcher.match(uri);
// Note: We always return single row of data, so content-type is always "a dir"
switch (match) {
case PHOTO_COMMENT:
return PhotoContract.PhotoEntry.CONTENT_TYPE;
case PHOTO:
return PhotoContract.PhotoEntry.CONTENT_TYPE;
case THUMBS:
return PhotoContract.ThumbEntry.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
#Override
public boolean onCreate() {
return true; // enough?
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
// determine whether this is THUMBS or FULLSIZE query
int match = sUriMatcher.match(uri);
switch (match) {
case THUMBS: {
// split projection into MediaStore and MediaStore.Thumbs parts
ArrayList<String> MS_proj = new ArrayList<>();
ArrayList<String> MS_proj_thumbs = new ArrayList<>();
for (String f : projection) {
if (PhotoContract.ThumbEntry.COL_TYPES.get(f).equals(PhotoContract.TARGET_MEDIASTORE)) {
MS_proj.add(f);
} else {
MS_proj_thumbs.add(f);
}
}
String[] MS_proj_thumbs_array = new String[MS_proj_thumbs.size()];
MS_proj_thumbs_array = MS_proj_thumbs.toArray(MS_proj_thumbs_array);
// add _ID column to Images.Media projection, for use in JOIN
MS_proj.add("_ID");
String[] MS_proj_array = new String[MS_proj.size()];
MS_proj_array = MS_proj.toArray(MS_proj_array);
Uri baseUri;
// first, get cursor from MediaStore.Images.Thumbnails containing all thumbnails
baseUri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
Log.v("JOAKIM", "Thumb: order by " + PhotoContract.ThumbEntry.COLUMN_DATE);
Cursor c_thumbs = getContext().getContentResolver().query(baseUri, MS_proj_thumbs_array, null, null, PhotoContract.ThumbEntry.COLUMN_IMAGE_ID);
if (c_thumbs == null || !c_thumbs.moveToFirst()) {
Log.v("JOAKIM", "MediaStore.Thumbnails cursor contains no data...");
return null;
}
// then, get cursor from MediaStore.Images.Media (for TITLE and DESCRIPTION etc)
// add _ID column to query
baseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Cursor c_images = getContext().getContentResolver().query(baseUri, MS_proj_array, null, null, PhotoContract.ThumbEntry.COLUMN_IMAGE_PK);
if (c_images == null || !c_images.moveToFirst()) {
Log.v("JOAKIM", "MediaStore.Images cursor contains no data...");
return null;
}
// join these and return
// the join is on images._ID = thumbnails.IMAGE_ID
CursorJoiner joiner = new CursorJoiner(
c_thumbs, new String[] { PhotoContract.ThumbEntry.COLUMN_IMAGE_ID },
c_images, new String[] { PhotoContract.ThumbEntry.COLUMN_IMAGE_PK }
);
MatrixCursor retCursor = new MatrixCursor(projection);
/*
Does a join on two cursors using the specified columns.
The cursors must already be sorted on each of the specified columns in ascending order.
This joiner only supports the case where the tuple of key column values is unique.
*/
for (CursorJoiner.Result joinerResult : joiner) {
switch (joinerResult) {
case LEFT:
// handle case where a row in cursorA is unique
break;
case RIGHT:
// handle case where a row in cursorB is unique
break;
case BOTH:
// handle case where a row with the same key is in both cursors
retCursor.addRow(new Object[]{
c_thumbs.getLong(0), // ID
c_thumbs.getString(1), // data
c_thumbs.getLong(2), // image id
c_images.getString(0), // title
c_images.getString(1), // desc
c_images.getLong(2) // date
});
break;
}
}
// https://stackoverflow.com/questions/12065606/getcontentresolver-query-cause-cursorwrapperinner-warning
c_thumbs.close();
c_images.close();
//retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
}
return null;
}
}

LoadMoreListView Fragment implementation using sqlite database

I need to load a large dataset from a sqlite database. This will take too much of time to load the data. Therefore I used LoadMorelistView library to load with pagination.
I followed below link and successfully load the data from hard coded list.
pull to refresh and loadmore listview like facebook
But when I tried to load from sqlite database I got the following error.
// The constructor ArrayAdapter(Activity, int, ArrayList) is Undefined
I searched the google as well as stackoverflow. But unable to find a solution.
Please find the code snippet which I used to load the data,
Code for the list loading fragment. (FragmentThree.java)
package com.load.more.list.view;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.load.more.list.model.Customer;
import com.load.more.list.data.CustomerDS;
import com.load.more.list.data.DatabaseHelper;
import android.app.Fragment;
import com.load.more.list.control.CustomerAdapter;
public class FragmentThree extends Fragment {
View view;
LoadMoreListView lyt;
ArrayAdapter<String> files;
ArrayList<Customer> mListItems;
CustomerDS customerDS;
private DatabaseHelper dbHelper;
private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private int firstVisibleItem = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_three, container, false);
lyt = (LoadMoreListView) view.findViewById(R.id.lvRouteCustomers);
mListItems = customerDS.getAllCustomersFromTo(visibleThreshold,
firstVisibleItem);
// Following Error Thrown from here
// The constructor ArrayAdapter<String>(Activity, int,
// ArrayList<Customer>) is Undefined
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
return view;
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Following Error Thrown from here
// The constructor ArrayAdapter<String>(Activity, int,
// ArrayList<Customer>) is Undefined
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
return null;
}
#Override
protected void onPostExecute(Void result) {
files.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
lyt.onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
lyt.onLoadMoreComplete();
}
}
}
Code for the database helper class. (DatabaseHelper)
package com.load.more.list.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//database information
private static final String DATABASE_NAME = "fmcgDB.db";
private static final int DATABASE_VERSION = 1;
//TABLES
//Customer table
public static final String TABLE_CUSTOMER = "customer";
public static final String CUSTOMER_ID = "customer_id";
public static final String CUSTOMER_NO = "customer_no";
public static final String CUSTOMER_NAME = "customer_name";
public static final String CUSTOMER_CONTACT_PERSON = "customer_contact_person";
public static final String CUSTOMER_TELEPHONE_NO = "customer_telephone_no";
public static final String CUSTOMER_ADDRESS = "customer_address";
public static final String CUSTOMER_LONGITUDE = "customer_longitude";
public static final String CUSTOMER_LATITUDE = "customer_latitude";
public static final String CUSTOMER_TLP = "customer_tlp";
public static final String CUSTOMER_REP_ID = "customer_rep_id";
public static final String CUSTOMER_CATEGORY_ID = "cc_id";
public static final String CUSTOMER_OUTLET_TYPE_ID = "ot_id";
public static final String CUSTOMER_PERIPHERY_TYPE_ID = "pt_id";
public static final String CUSTOMER_VOLUME_ID = "volume_id";
public static final String CUSTOMER_MARKET_ID = "market_id";
private static final String CREATE_CUSTOMER_TABLE = "CREATE TABLE " + TABLE_CUSTOMER + " ("
+ CUSTOMER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CUSTOMER_NO + " TEXT, "
+ CUSTOMER_NAME + " TEXT, "
+ CUSTOMER_CONTACT_PERSON + " TEXT, "
+ CUSTOMER_TELEPHONE_NO + " TEXT, "
+ CUSTOMER_ADDRESS + " TEXT, "
+ CUSTOMER_LONGITUDE + " REAL, "
+ CUSTOMER_LATITUDE + " REAL, "
+ CUSTOMER_TLP + " INTEGER, "
+ CUSTOMER_REP_ID + " INTEGER, "
+ CUSTOMER_CATEGORY_ID + " INTEGER, "
+ CUSTOMER_OUTLET_TYPE_ID + " INTEGER, "
+ CUSTOMER_PERIPHERY_TYPE_ID + " INTEGER, "
+ CUSTOMER_VOLUME_ID + " INTEGER, "
+ CUSTOMER_MARKET_ID + " INTEGER "
+");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase arg0) { // this order must be followed when creating tables
arg0.execSQL(CREATE_CUSTOMER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
arg0.execSQL("DROP TABLE IF EXISTS " + CREATE_CUSTOMER_TABLE);
onCreate(arg0);
}
}
Code for the sqlite data loading. (CustomerDS.java)
package com.load.more.list.data;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.load.more.list.model.Customer;
public class CustomerDS {
private SQLiteDatabase fmcgDB;
private DatabaseHelper dbHelper;
Context context;
public CustomerDS(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
fmcgDB = dbHelper.getWritableDatabase();
}
public ArrayList<Customer> getAllCustomersFromTo(int limit, int offset) {
if (fmcgDB == null) {
open();
} else if (!fmcgDB.isOpen()) {
open();
}
ArrayList<Customer> customersList = new ArrayList<Customer>();
// Newly Added
String selectQuery = "SELECT * FROM " + dbHelper.TABLE_CUSTOMER
+ " LIMIT " + limit + " OFFSET " + offset +"";
Cursor cursor = null;
try{
cursor = fmcgDB.rawQuery(selectQuery, null);
/*cursor = fmcgDB.query(dbHelper.TABLE_CUSTOMER, null, null, null,
null, null, null);
*/
while (cursor.moveToNext()) {
Customer customer = new Customer();
customer.setCustomer_id(cursor.getInt(cursor.getColumnIndex(dbHelper.CUSTOMER_ID)));
customer.setCustomer_no(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NO))));
customer.setCustomer_name(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NAME))));
customer.setCustomer_contact_person(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_CONTACT_PERSON))));
customer.setCustomer_telephone_no(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_TELEPHONE_NO))));
customer.setCustomer_address(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_ADDRESS))));
customer.setCustomer_longitude(cursor.getDouble((cursor.getColumnIndex(dbHelper.CUSTOMER_LONGITUDE))));
customer.setCustomer_latitude(cursor.getDouble((cursor.getColumnIndex(dbHelper.CUSTOMER_LATITUDE))));
int TLP = cursor.getInt((cursor.getColumnIndex(dbHelper.CUSTOMER_TLP)));
if(TLP == 0){
customer.setCustomer_TLP_member(true);
}else{
customer.setCustomer_TLP_member(false);
}
customersList.add(customer);
}
}
finally {
if (cursor!=null) {
cursor.close();
}
fmcgDB.close();
return customersList;
}
}
}
Code for the Adapter Class. (CustomerAdapter.java)
package com.load.more.list.control;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.load.more.list.model.Customer;
import com.load.more.list.view.R;
public class CustomerAdapter extends ArrayAdapter<Customer> {
Context context;
ArrayList<Customer> customerList;
public CustomerAdapter(Context context, ArrayList<Customer> customerList){
super(context, R.layout.item_customer, customerList);
this.context = context;
this.customerList = customerList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.item_customer, parent, false);
TextView tvName = (TextView) row.findViewById(R.id.tvRouteCustomerListName);
TextView tvMarket = (TextView) row.findViewById(R.id.tvRouteCustomerListMarket);
TextView tvVolume = (TextView) row.findViewById(R.id.tvRouteCustomerListVolume);
tvName.setText(customerList.get(position).getCustomer_name());
return row;
}
}
Code for the Customer Object. (Customer.java)
package com.load.more.list.model;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class Customer {
private static final String TAG_CUSTOMER = "customers";
private static final String TAG_CUSTOMER_ID = "customer_id";
private static final String TAG_CUSTOMER_NO = "CustomerCode";
private static final String TAG_CUSTOMER_NAME = "CustomerName";
private static final String TAG_CUSTOMER_ADDRESS = "Address1";
private static final String TAG_CUSTOMER_CONTACT_PERSON = "ContactPersonName";
private static final String TAG_CUSTOMER_TELEPHONE_NO = "PhoneNo";
private static final String TAG_CUSTOMER_LATITUDE = "CustomerLatitude";
private static final String TAG_CUSTOMER_LONGITUDE = "CustomerLongitude";
private static final String TAG_CUSTOMER_IS_TLP = "Istlp";
private static final String TAG_CUSTOMER_REP_ID = "";
private static final String TAG_CUSTOMER_PT_ID = "PheriheryId";
private static final String TAG_CUSTOMER_CATEGORY_ID = "CatrgoryId";
private static final String TAG_CUSTOMER_OUTLETTYPE_ID = "OutletTypeId";
private static final String TAG_CUSTOMER_VOLUME_ID = "VolumeId";
private static final String TAG_CUSTOMER_MARKET_ID = "MarketId";
private int customer_id;
private String customer_no;
private String customer_name;
private String customer_contact_person;
private String customer_telephone_no;
private String customer_address;
private double customer_longitude;
private double customer_latitude;
private boolean customer_TLP_member;
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int customer_id) {
this.customer_id = customer_id;
}
public String getCustomer_name() {
return customer_name;
}
public void setCustomer_name(String customer_name) {
this.customer_name = customer_name;
}
public String getCustomer_contact_person() {
return customer_contact_person;
}
public void setCustomer_contact_person(String customer_contact_person) {
this.customer_contact_person = customer_contact_person;
}
public String getCustomer_telephone_no() {
return customer_telephone_no;
}
public void setCustomer_telephone_no(String customer_telephone_no) {
this.customer_telephone_no = customer_telephone_no;
}
public String getCustomer_address() {
return customer_address;
}
public void setCustomer_address(String customer_address) {
this.customer_address = customer_address;
}
public double getCustomer_longitude() {
return customer_longitude;
}
public void setCustomer_longitude(double customer_longitude) {
this.customer_longitude = customer_longitude;
}
public double getCustomer_latitude() {
return customer_latitude;
}
public void setCustomer_latitude(double customer_latitude) {
this.customer_latitude = customer_latitude;
}
public boolean isCustomer_TLP_member() {
return customer_TLP_member;
}
public void setCustomer_TLP_member(boolean customer_TLP_member) {
this.customer_TLP_member = customer_TLP_member;
}
public String getCustomer_no() {
return customer_no;
}
public void setCustomer_no(String customer_no) {
this.customer_no = customer_no;
}
}
Can anyone know how to solve this problem? If yes, please help me to solve this problem.
Thanks in advance.
Finally I solved the issue,.
I have changed the type of mListItems to
ArrayList<String> mListItems;
and the return type of getAllCustomersFromTo() to String array.
It solved my issue.
Final source code of the updated classes are shown below.
Code for the list loading fragment. (FragmentThree.java)
package com.load.more.list.view;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.load.more.list.model.Customer;
import com.load.more.list.data.CustomerDS;
import com.load.more.list.data.DatabaseHelper;
import android.app.Fragment;
import com.load.more.list.control.CustomerAdapter;
public class FragmentThree extends Fragment {
View view;
LoadMoreListView lyt;
ArrayAdapter<String> files;
ArrayList<String> mListItems;
CustomerDS customerDS;
private DatabaseHelper dbHelper;
private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private int firstVisibleItem = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_three, container, false);
lyt = (LoadMoreListView) view.findViewById(R.id.lvRouteCustomers);
mListItems = customerDS.getAllCustomersFromTo(visibleThreshold,
firstVisibleItem);
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
return view;
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
return null;
}
#Override
protected void onPostExecute(Void result) {
files.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
lyt.onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
lyt.onLoadMoreComplete();
}
}
}
Code for the sqlite data loading. (CustomerDS.java)
package com.load.more.list.data;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.load.more.list.model.Customer;
public class CustomerDS {
private SQLiteDatabase fmcgDB;
private DatabaseHelper dbHelper;
Context context;
public CustomerDS(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
fmcgDB = dbHelper.getWritableDatabase();
}
public ArrayList<String> getAllCustomersFromTo(int limit, int offset) {
if (fmcgDB == null) {
open();
} else if (!fmcgDB.isOpen()) {
open();
}
ArrayList<String> customersList = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + dbHelper.TABLE_CUSTOMER
+ " LIMIT " + limit + " OFFSET " + offset +"";
Cursor cursor = null;
try{
cursor = fmcgDB.rawQuery(selectQuery, null);
while (cursor.moveToNext()) {
customersList.add(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NAME))));
}
}
finally {
if (cursor!=null) {
cursor.close();
}
fmcgDB.close();
return customersList;
}
}
}

Categories

Resources