From the second you click on the notification activity button the program immediately starts acting slow. This screen for some reason takes minutes to scroll down in a very glitchy and drawn out manner. What can I do to speed up and smooth out my notification activity screen?
NotificationActivity:
public class NotificationActivity extends BaseActivity {
public static final String TAG = LoginActivity.class.getSimpleName();
private NotificationAdapter notificationAdapter;
private HeaderLayout headerLayout;
private FooterLayout footerLayout;
private SimpleGestureFilter detector;
private ListView mNotificationLv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
mNotificationLv = (ListView) findViewById(R.id.notification_lv);
mNotificationLv = (ListView) findViewById(R.id.notification_lv);
notificationAdapter = new NotificationAdapter(this);
notificationAdapter.setList(AtlasApplication.lstNotificationModels);
mNotificationLv.setAdapter(notificationAdapter);
// Detect touched area
detector = new SimpleGestureFilter(this,this);
}
#Override
protected void onResume() {
super.onResume();
List<NotificationModel> userModelList = AtlasApplication.lstNotificationModels;
notificationAdapter = new NotificationAdapter(this);
notificationAdapter.setList(userModelList);
mNotificationLv.setAdapter(notificationAdapter);
}
}
NotificationAdapter:
public class NotificationAdapter extends BaseAdapter{
private List<NotificationModel> lstNotificationModels;
private SQLiteAdapter sqLiteAdapter;
private Context context;
public NotificationAdapter(Context context) {
this.context = context; sqLiteAdapter=new SQLiteAdapter(context, this, new Dialog(context));
}
public void setList(List<NotificationModel> genres) {
this.lstNotificationModels = genres;
notifyDataSetChanged();
}
private class ViewHolder {
TextView mNotifiactionTypeTv, mNotifiactionTextTv, mNotifiactionTimeTv;
LinearLayout rowNotificationLl;
}
public void setRead(int i){
sqLiteAdapter.updateNotificationStatus(i, "read");
lstNotificationModels.get(i).setmNotificationStatus("read");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_notification, null);
holder = new ViewHolder();
holder.rowNotificationLl = (LinearLayout) convertView.findViewById(R.id.row_notification_ll);
holder.mNotifiactionTextTv = (TextView) convertView.findViewById(R.id.notification_text_tv);
holder.mNotifiactionTimeTv = (TextView) convertView.findViewById(R.id.notification_time_tv);
holder.mNotifiactionTypeTv = (TextView) convertView.findViewById(R.id.notification_type_atv);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final NotificationModel notificationModel = lstNotificationModels.get(position);
final String newFullText = sqLiteAdapter.getFullText(notificationModel.getmLawId());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = new Date();
Date notificationDate = new Date();
String timeElapsed = "moments ago.";
try {
notificationDate = simpleDateFormat.parse(notificationModel.getmNotificationTime().trim());
} catch(ParseException e){
}
long milliElapsed = currentDate.getTime() - notificationDate.getTime() + 14400000;
if(milliElapsed>=60000){
long minutesElapsed = milliElapsed/60000;
timeElapsed = minutesElapsed + " minutes ago.";
if(minutesElapsed>=60){
long hoursElapsed = minutesElapsed/60;
timeElapsed = hoursElapsed + " hours ago.";
if(hoursElapsed>=24){
long daysElapsed = hoursElapsed/60;
timeElapsed = daysElapsed + " days ago.";
if(daysElapsed>=7){
long weeksElapsed = daysElapsed/7;
timeElapsed = hoursElapsed + " weeks ago.";
if(weeksElapsed>=4){
long monthsElapsed = weeksElapsed/4;
timeElapsed = monthsElapsed + " months ago.";
if(daysElapsed>=365){
long yearsElapsed = daysElapsed/365;
timeElapsed = yearsElapsed + " years ago.";
}
}
}
}
}
}
holder.mNotifiactionTextTv.setText(Html.fromHtml(notificationModel.getmNotificationText().trim()));
holder.mNotifiactionTimeTv.setText(timeElapsed);
if (notificationModel.getmNotificationStatus().equalsIgnoreCase("unread")) {
convertView.findViewById(R.id.unread_vw).setVisibility(View.VISIBLE);
holder.rowNotificationLl.setBackgroundResource(R.color.black);
}
else {
convertView.findViewById(R.id.unread_vw).setVisibility(View.GONE);
holder.rowNotificationLl.setBackgroundResource(R.color.grad_light);
}
switch (notificationModel.getmNotificationType().toLowerCase()){
case "traffic":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.traffic_noti_bg);
holder.mNotifiactionTypeTv.setText("f");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TRAFFIC;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(0);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TRAFFIC;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(0);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "law enforcement":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.enforcement_noti_bg);
holder.mNotifiactionTypeTv.setText("c");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ENFORCEMENT;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(1);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ENFORCEMENT;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(1);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "alcohol":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.alcohal_noti_bg);
holder.mNotifiactionTypeTv.setText("a");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ALCOHOL;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(2);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_ALCOHOL;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(2);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "taxes":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.taxes_noti_bg);
holder.mNotifiactionTypeTv.setText("e");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TAXES;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(3);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_TAXES;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(3);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "guns":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.guns_noti_bg);
holder.mNotifiactionTypeTv.setText("b");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_GUNS;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(4);
setRead(notificationModel.getmNotificaticationId());
AtlasApplication.lstLawsForLocation.get(1).setSelected(true);
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_GUNS;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(4);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
catch(Exception e){
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
case "marijuana":
holder.mNotifiactionTypeTv.setBackgroundResource(R.drawable.marijuana_noti_bg);
holder.mNotifiactionTypeTv.setText("d");
holder.mNotifiactionTypeTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_MARIJUANA;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(5);
setRead(notificationModel.getmNotificaticationId());
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
holder.mNotifiactionTextTv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
AtlasApplication.MenuTitle = Constants.CAT_MARIJUANA;
AtlasApplication.sCategoryModel = AtlasApplication.lstCategoryModels.get(5);
setRead(notificationModel.getmNotificaticationId());
AtlasApplication.lstLawsForLocation.get(1).setSelected(true);
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
} catch (Exception e) {
view.getContext().startActivity(SubMenuActivity.getIntent(view.getContext()));
}
}
});
break;
default:
break;
}
FontLoader.setAtlasFont(holder.mNotifiactionTypeTv);
FontLoader.setRalewayRegularFont(holder.mNotifiactionTextTv, holder.mNotifiactionTimeTv);
holder.rowNotificationLl.setId(position);
holder.rowNotificationLl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
}
SQLiteAdapter:
public class SQLiteAdapter {
private static final int DATABASE_VERSION = 1;
private static String DB_PATH;//= Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/";
private SQLiteDatabase mSqLiteDatabase;
private Context mContext;
private Dialog mDialog;
private SQLiteDbQueryListener sqLiteDbQueryListener;
private ExceptionHandler exceptionHandler;
public SQLiteAdapter(Context c, SQLiteDbQueryListener listener, Dialog dialog) {
mContext = c;
sqLiteDbQueryListener = listener;
exceptionHandler = new ExceptionHandler(mContext, "SQLiteAdapter");
mDialog = dialog;
DB_PATH = Environment.getExternalStorageDirectory() + "/" + mContext.getPackageName() + "/";
//call it so db get copied from assets to sdcard
//call it so db get copied from assets to sdcard
openToRead();
close();
}
public void updateLaw(int lawID, String newSummary, String newFullText){
int tagID = getTagID(lawID);
String tagName = getTagName(tagID);
int categoryID = getCategoryID(tagID);
String categoryName = getCategoryName(categoryID);
String location;
location = getLocationName(getLocationID(lawID));
if (location.toLowerCase().equals(AtlasApplication.sHometownSelected.getLocationName().toLowerCase())) {
location = "your current state";
} else if (location.toLowerCase().equals(AtlasApplication.sHometownSelected.getLocationName().toLowerCase())) {
location = "your home state";
}
openToWrite();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_SUMMARY, newSummary);
if(newFullText!=null)
contentValues.put(Constants.KEY_FULL_TEXT, newFullText);
mSqLiteDatabase.update(Constants.TABLE_LAW, contentValues, Constants.KEY_LAW_ID + "=" + lawID, null);
close();
insertNotification(lawID, categoryName, tagName + " has changed in " + location + ".");
}
public int getCategoryID(int tagID){
openToRead();
int categoryID = 0;
String Query = "SELECT * from " + Constants.TABLE_CATEGORY_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if (cursor.getInt(cursor.getColumnIndex(Constants.KEY_TAG_ID)) == tagID) {
int indexCategoryID = cursor.getColumnIndex(Constants.KEY_CATEGORY_ID);
categoryID = cursor.getInt(indexCategoryID);
}
cursor.moveToNext();
}
}
close();
return categoryID;
}
public String getCategoryName(int categoryID){
String categoryName = "";
openToRead();
String Query = "SELECT * from " + Constants.TABLE_CATEGORY;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if (cursor.getInt(cursor.getColumnIndex(Constants.KEY_CATEGORY_ID)) == categoryID) {
int indexCategoryName = cursor.getColumnIndex(Constants.KEY_CATEGORY_NAME);
categoryName = cursor.getString(indexCategoryName);
}
cursor.moveToNext();
}
}
close();
return categoryName.toLowerCase();
}
public int getLocationID(int lawID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LAW_LOCATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
int locationID = 0;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LAW_ID)) == lawID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_LOCATION_ID);
locationID = cursor.getInt(indexTagID);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getLocationID()");
}
cursor.moveToNext();
}
}
close();
return locationID;
}
public String getLocationName(int locationID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LOCATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
String locationName = "";
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LOCATION_ID)) == locationID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_LOCATION_NAME);
locationName = cursor.getString(indexTagID);
}
cursor.moveToNext();
}
}
close();
return locationName;
}
public int getTagID(int lawID){
openToRead();
String Query = "SELECT * from " + Constants.TABLE_LAW_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
int tagID = 0;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_LAW_ID)) == lawID) {
int indexTagID = cursor.getColumnIndex(Constants.KEY_TAG_ID);
tagID = cursor.getInt(indexTagID);
cursor.moveToNext();
}
}
close();
return tagID;
}
public String getTagName(int tagID){
openToRead();
String tagName = "";
String Query = "SELECT * from " + Constants.TABLE_TAG;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if(cursor.moveToFirst()){
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_TAG_ID)) == tagID) {
int indexTagName = cursor.getColumnIndex(Constants.KEY_TAG_NAME);
tagName = cursor.getString(indexTagName);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getTagName()");
}
cursor.moveToNext();
}
}
close();
return tagName;
}
public void insertNotification(int lawID, String type, String text){
openToWrite();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_LAW_ID, lawID);
contentValues.put(Constants.KEY_NOTIFICATION_TYPE, type);
contentValues.put(Constants.KEY_NOTIFICATION_TEXT, text);
contentValues.put(Constants.KEY_NOTIFICATION_STATUS, "unread");
mSqLiteDatabase.insert(Constants.TABLE_NOTIFICATION, null, contentValues);
}
catch(Exception e){
exceptionHandler.alert(e, "insertNotification()");
}
close();
}
public void dropNotifications(){
openToWrite();
try{
mSqLiteDatabase.execSQL("DROP TABLE IF EXISTS notification");
}
catch(Exception e){
}
close();
}
public void updateNotificationStatus(int notificationID, String status){
openToWrite();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_NOTIFICATION_STATUS, status);
mSqLiteDatabase.update(Constants.TABLE_NOTIFICATION, contentValues, Constants.KEY_NOTIFICATION_ID + "=" + notificationID, null);
}
catch(Exception e){
exceptionHandler.alert(e, "updateNotificationStatus()");
}
close();
}
public String getNotificationStatus(int notificationID){
openToRead();
String Query = "SELECT * FROM " + Constants.TABLE_NOTIFICATION + " WHERE " + Constants.KEY_NOTIFICATION_ID + "=" + notificationID;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
String notificationStatus = "";
if(cursor.moveToFirst()){
while (cursor.isAfterLast() == false) {
try {
if(cursor.getInt(cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID)) == notificationID) {
int indexNotificationStatus = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_STATUS);
notificationStatus = cursor.getString(indexNotificationStatus);
}
} catch (Exception e) {
exceptionHandler.alert(e, "getNotificationStatus()");
}
cursor.moveToNext();
}
}
close();
return notificationStatus;
}
public int getNotificationId(int lawID, String time){
openToRead();
int notificationId = 0;
String query = "SELECT * FROM " + Constants.TABLE_NOTIFICATION +
" WHERE " + Constants.KEY_NOTIFICATION_TIME + " = " + time;
Cursor cursor = mSqLiteDatabase.rawQuery(query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
int indexNotificationID = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID);
notificationId = cursor.getInt(indexNotificationID);
}
}
close();
return notificationId;
}
public List<NotificationModel> getNotificationList(){
List<NotificationModel> lstNotifications = new ArrayList<NotificationModel>();
openToRead();
String Query = "SELECT * from " + Constants.TABLE_NOTIFICATION;
Cursor cursor = mSqLiteDatabase.rawQuery(Query, null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
try {
int indexNotificationID = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_ID);
int indexLawID = cursor.getColumnIndex(Constants.KEY_LAW_ID);
int indexNotificationTime = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TIME);
int indexNotificationType = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TYPE);
int indexNotificationText = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_TEXT);
int indexNotificationStatus = cursor.getColumnIndex(Constants.KEY_NOTIFICATION_STATUS);
int notificationID = cursor.getInt(indexNotificationID);
int lawID = indexLawID;
String notificationTime = cursor.getString(indexNotificationTime);
String notificationType = cursor.getString(indexNotificationType);
String notificationText = cursor.getString(indexNotificationText);
String notificationStatus = cursor.getString(indexNotificationStatus);
lstNotifications.add(new NotificationModel(notificationID, lawID, notificationType, notificationText, notificationTime, notificationStatus));
} catch (Exception e) {
exceptionHandler.alert(e, "getNotificationList()");
}
cursor.moveToNext();
}
}
close();
Collections.reverse(lstNotifications);
return lstNotifications;
}
}
MainActivity:
sqLiteAdapter.updateLaw(962, "test", "test");
The issue you described is pretty hard to detect in this code but here is a list of notes/best practices you should take into consideration:
You should ALWAYS do your DB queries on a secondary thread and not on your main thread (Try an AsyncTask).
you have a SimpleGestureFilter which I can't say what is for or what it does. If you have some ugly logic there, that may affect scrolling.
You create tons of LayoutInflater variables in your getView() method which is pretty bad. Make it a global variable and initialize it in the Adapter's constructor. Do you have an idea of how many times the getView() method gets called when you scroll? Put a log there and analyse :).
Definitely not hold an instance to your SQLiteAdapter object in the adapter. Do that in your activity and update your adapter when you need it. The Adapter should always be the representation of your data and not doing having logic and whatever else.
Not sure what the FontLoader does but if you read a font from the assets every time the getView() is called, you have a huuuge problem. Try to load fonts as few times as possible because that's a heavy operation.
Never catch general Exceptions. Try to focus on the specific ones.
Related
View Complaint Activity:
In this i have done debugging but i was unable to know the reason why the data is coming twice after scrolling. I have even check the data coming from server through postman but the data is not coming duplicate its coming perfectly fine the problem seems to be in front end while we are putting the data through adapter inside activity on scrolling.
public class ViewComplaintActivity extends AppCompatActivity implements AbsListView.OnScrollListener, View.OnClickListener {
TextView tv_notData;
List<Ticket> _data = new ArrayList<Ticket>();
ComplaintsAdapter settlementAdapter;
private String TAG = "ViewComplaintActivity";
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
private boolean userScrolled = false;
a) Its is a Complaints Activity where we are showing the data comimg from server through adapter.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_compliants);
ButterKnife.bind(this);
try {
settlementAdapter = new ComplaintsAdapter(ViewComplaintActivity.this, _data);
AlphaInAnimationAdapter animationAdapter = new AlphaInAnimationAdapter(settlementAdapter);
animationAdapter.setAbsListView(ll_complaint_list);
ll_complaint_list.setAdapter(animationAdapter);
getComplaints(Utility.getTerminalId(ViewComplaintActivity.this), 0);
ll_complaint_list.setOnScrollListener(this);
fab_raise_complaint.setOnClickListener(this);
fab_call_customer.setOnClickListener(this);
ivBackButton.setOnClickListener(this);
} catch (NullPointerException e) {
Log.e(TAG, e.toString());
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
private void getComplaints(String terminalid, int pagenumber) {
if (!NetworkConnection.isConnected(this)) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("subIdentifier", terminalid);
jsonObject.addProperty("pageLimit", "10");
jsonObject.addProperty("lastPageIndex", "" + pagenumber);
IRetrofit iRetrofit = MoApplication.getInstance().getRetrofitOsTickets(this).create(IRetrofit.class);
Log.e(TAG,"jsonObject "+jsonObject);
iRetrofit.getAllTicket(jsonObject, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
progressBar.setVisibility(View.GONE);
try {
if (response.getStatus() == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody().in()));
String resultFromJson = bufferedReader.readLine();
/* Log.e(TAG, "resultFromJson " + resultFromJson);*/
GetTicketsResponse getSettlementsResDTO = new Gson().fromJson(resultFromJson, GetTicketsResponse.class);
switch (getSettlementsResDTO.getResCode()) {
case "0001":
if (null != getSettlementsResDTO.getTickets()) {
_data.addAll(getSettlementsResDTO.getTickets());
settlementAdapter.notifyDataSetChanged();
if (_data.isEmpty()) {
tv_notData.setVisibility(View.VISIBLE);
} else {
tv_notData.setVisibility(View.GONE);
}
} else {
Utility.showToast(ViewComplaintActivity.this, "No data found.");
}
break;
default:
Utility.showToast(ViewComplaintActivity.this, "Please try later.");
break;
}
}
} catch (NullPointerException e) {
Log.e(TAG, "" + e.toString());
} catch (Exception e) {
Log.e(TAG, "" + e.toString());
}
}
#Override
public void failure(RetrofitError error) {
if (Utility.parseException(error)){
Utility.mPosLogoutService((AppCompatActivity) ViewComplaintActivity.this);
}
progressBar.setVisibility(View.GONE);
}
});
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
/*Log.e(TAG,"one");*/
Log.e(TAG,"scrollState "+scrollState);
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
fab_call_customer.hide();
fab_raise_complaint.hide();
} else {
fab_call_customer.show();
fab_raise_complaint.show();
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
/*Log.e(TAG,"two");*/
view.getSelectedItemPosition();
if (userScrolled) {
Log.e(TAG,"loading "+loading);
if (loading) {
Log.e(TAG,"totalItemCount "+totalItemCount);
Log.e(TAG,"previousTotal "+previousTotal);
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
Log.e(TAG,"loadin after scroll "+loading);
if (!loading && ((totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold))) {
getComplaints(Utility.getTerminalId(ViewComplaintActivity.this), currentPage);
loading = true;
}
}
else {
Log.e(TAG,"user is idle");
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public void onClick(View v) {
if (NetworkConnection.isConnected(this)) {
if (v == fab_raise_complaint) {
Utility.navigate(this, RaiseComplaintActivity.class);
} else if (v == fab_call_customer) {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + Uri.encode(Constant.helplineNumber.trim())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
} else if (v == ivBackButton) {
startActivity(new Intent(ViewComplaintActivity.this, HomeQrActivity.class));
finish();
}
} else {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
}
}
public class ComplaintsAdapter extends BaseAdapter {
private static String TAG = "ComplaintsAdapter";
List<Ticket> _data;
Context _c;
ViewHolder holder;
public ComplaintsAdapter(Context context, List<Ticket> getData) {
_data = getData;
_c = context;
}
#Override
public int getCount() {
Log.e(TAG,"_data.size()"+_data.size());
return _data.size();
}
#Override
public Object getItem(int position) {
Log.e(TAG,"_data.get(position)"+_data.get(position));
return _data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
/*Log.e(TAG,"getData"+_data.toString());*/
try {
if (view == null) {
/*Log.e(TAG,"getData1"+_data.toString());*/
LayoutInflater li = (LayoutInflater)
_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.row_item_view_complaints,
null);
} else {
/*Log.e(TAG,"getData2"+_data.toString());*/
view = convertView;
}
holder = new ViewHolder();
holder.tv_ticketNo = (TextView)
view.findViewById(R.id.tv_ticketNo);
holder.tv_submitDate = (TextView)
view.findViewById(R.id.tv_submitDate); //ticket comments
holder.tv_updatedDate = (TextView)
view.findViewById(R.id.tv_updatedDate);//will act as ticket
last modified time
holder.tv_ticketStatus = (TextView)
view.findViewById(R.id.tv_ticketStatus); //ticket status open
or close
holder.tv_comment = (TextView)
view.findViewById(R.id.tv_comment);
holder.tv_subject = (TextView)
view.findViewById(R.id.tv_subject);
final Ticket ticket = _data.get(position);
holder.tv_ticketNo.setText("#" + ticket.getTicketNo());
holder.tv_submitDate.setText(Html.fromHtml("<b> Created On:
</b>" + Utility.dateReformatting("yyyy-MM-dd HH:mm:ss", "dd
MMM yyyy", ticket.getCreated())));
holder.tv_updatedDate.setText(Html.fromHtml("<b> Modified On:
</b>" + Utility.dateReformatting("yyyy-MM-dd HH:mm:ss", "dd
MMM yyyy", ticket.getModified())));
holder.tv_ticketStatus.setText(ticket.getStatus());
holder.tv_subject.setText(null != ticket.getSubject() && !ticket.getSubject().isEmpty() ? ticket.getSubject().trim().replace("|", "") : "NA"); //comments
if (null != ticket.getComment() && !ticket.getComment().isEmpty()) {
holder.tv_comment.setText(Html.fromHtml(ticket.getComment()));
holder.tv_comment.setVisibility(View.VISIBLE);
} else {
holder.tv_comment.setVisibility(View.GONE);
}
//holder.tv_comment.setText(null != ticket.getComment() && !ticket.getComment().isEmpty() ? ticket.getComment() : ""); //comments
if (ticket.getStatus().startsWith("Open"))
holder.tv_ticketStatus.setTextColor(_c.getResources().getColor(R.color.green_success));
else
Log.e(TAG,"getData4"+_data.toString());
holder.tv_ticketStatus.setTextColor(_c.getResources().getColor(R.color_color));
} catch (NullPointerException e) {
Log.e(TAG, e.toString());
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return view;
}
public void set_data(List<Ticket> _data) {
this._data = _data;
}
static class ViewHolder {
public TextView tv_ticketStatus, tv_ticketNo, tv_submitDate,
tv_updatedDate, tv_comment, tv_subject;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Apologies first of all because it is going to be a long question.
I am creating a to do list using 2 RecyclerViews in 2 fragments following is the code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TaskDbHelper mHelper;
public Tab1 incompleteTasks;
public Tab2 completedTasks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
final EditText taskEditText = new EditText(MainActivity.this);
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try{
mHelper = new TaskDbHelper(MainActivity.this);
String task = String.valueOf(taskEditText.getText());
mHelper.adddata(MainActivity.this, task);
//incompleteTasks.addTask(mHelper.getAddedTask("0").get(0));
incompleteTasks.updateUI();
}
catch(Exception ex1){
Toast.makeText(MainActivity.this, (String)ex1.getMessage(), Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}catch (Exception ex) {
Log.d("MainActivity", "Exception: " + ex.getMessage());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
//Tab1 incompleteTasks = new Tab1();
incompleteTasks = new Tab1();
incompleteTasks.setContext(MainActivity.this);
return incompleteTasks;
case 1:
//Tab2 completedTasks = new Tab2();
completedTasks = new Tab2();
completedTasks.setContext(MainActivity.this);
return completedTasks ;
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Incomplete";
case 1:
return "Completed";
}
return null;
}
}
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.TaskHolder> {
private ArrayList<Task> mTasks;
private boolean completedStatus;
private Context contextFromTab;
private int lastPosition = -1;
private RecyclerViewAnimator mAnimator;
//1
public class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//2
private TextView mTask_id;
private TextView mTask_title;
private TextView mTask_created_date;
private ImageButton mImageButtonDone;
private ImageButton mImageButtonUndo;
private ImageButton mImageButtonEdit;
private ImageButton mImageButtonDelete;
//3
//private static final String PHOTO_KEY = "PHOTO";
//4
public TaskHolder(View v) {
super(v);
try{
//v.geti
mTask_id = v.findViewById(R.id.task_id);
mTask_title = v.findViewById(R.id.task_title);
mTask_created_date = v.findViewById(R.id.task_created_date);
mImageButtonDone = v.findViewById(R.id.imageButtonDone);
mImageButtonUndo = v.findViewById(R.id.imageButtonUndo);
mImageButtonEdit = v.findViewById(R.id.imageButtonEdit);
mImageButtonDelete = v.findViewById(R.id.imageButtonDelete);
v.setOnClickListener(this);
mImageButtonDone.setOnClickListener(this);
mImageButtonUndo.setOnClickListener(this);
mImageButtonEdit.setOnClickListener(this);
mImageButtonDelete.setOnClickListener(this);
//v.setAnimation();
}
catch (Exception ex){
Log.d("TaskHolder", ex.getMessage());
}
}
//5
#Override
public void onClick(View v) {
if(v.equals(mImageButtonDone)){
View parent = (View) v.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_id);
String _id = String.valueOf(taskTextView.getText());
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
mHelper.changeTaskStatus(contextFromTab,true, _id);
removeAt(getAdapterPosition());
}
else if(v.equals(mImageButtonUndo)) {
View parent = (View) v.getParent();
TextView taskTextView = parent.findViewById(R.id.task_id);
String _id = String.valueOf(taskTextView.getText());
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
mHelper.changeTaskStatus(contextFromTab,false, _id);
}
else if(v.equals(mImageButtonEdit)) {
View parent = (View) v.getParent();
TextView taskIdTextView = (TextView) parent.findViewById(R.id.task_id);
TextView taskTitleTextView = (TextView) parent.findViewById(R.id.task_title);
final String _id = String.valueOf(taskIdTextView.getText());
String _title = String.valueOf(taskTitleTextView.getText());
/*Intent intent = new Intent(this, TaskDetails.class);
intent.putExtra("_id", _id);
intent.putExtra("_title", _title);
startActivity(intent);*/
try{
final EditText taskEditText = new EditText(contextFromTab);
taskEditText.setText(_title);
AlertDialog dialog = new AlertDialog.Builder(contextFromTab)
.setTitle("Edit task")
.setView(taskEditText)
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try{
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
String task = String.valueOf(taskEditText.getText());
mHelper.editTask(contextFromTab, task, _id);
updateAt(getAdapterPosition(), _id);
/*Tab1 tab1 = new Tab1();
tab1.setContext(MainActivity.this);
tab1.updateUI();*/
}
catch(Exception ex1){
Toast.makeText(contextFromTab, (String)ex1.getMessage(), Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}catch (Exception ex) {
Log.d("MainActivity", "Exception: " + ex.getMessage());
}
}
else if(v.equals(mImageButtonDelete)) {
View parent = (View) v.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_id);
String _id = String.valueOf(taskTextView.getText());
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
mHelper.deleteTask(_id);
removeAt(getAdapterPosition());
}
Log.d("RecyclerView", "CLICK!");
}
public void bindTask(Task task, boolean completedStatus) {
try{
mTask_id.setText(Integer.toString(task._id) );
mTask_title.setText(task.title);
mTask_created_date.setText("created on: " + task.created_datetime);
if(completedStatus){
mImageButtonDone.setVisibility(View.INVISIBLE);
mImageButtonUndo.setVisibility(View.VISIBLE);
}else{
mImageButtonDone.setVisibility(View.VISIBLE);
mImageButtonUndo.setVisibility(View.INVISIBLE);
}
}
catch (Exception ex){
Log.d("bindTask", ex.getMessage());
}
}
public void addTask(Task task){
mTasks.add(0, task);
notifyItemInserted(0);
//smoothScrollToPosition(0);
}
public void removeAt(int position) {
mTasks.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
}
public void updateAt(int position, String task_id){
//mTasks.
//mTasks.set(position);
try{
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
Task updatedTask = mHelper.getTaskById(task_id);
mTasks.set(position, updatedTask);
notifyItemChanged(position);
}
catch (Exception ex){
}
}
}
public RecyclerAdapter(ArrayList<Task> tasks, boolean tasksCompletedStatus, Context context, RecyclerView recyclerView) {
mTasks = tasks;
completedStatus = tasksCompletedStatus;
contextFromTab = context;
mAnimator = new RecyclerViewAnimator(recyclerView);
}
#Override
public RecyclerAdapter.TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
try{
View inflatedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_todo, parent, false);
mAnimator.onCreateViewHolder(inflatedView);
return new TaskHolder(inflatedView);
}
catch(Exception ex){
Log.d("onCreateViewHolder", ex.getMessage());
return null;
}
}
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(contextFromTab, android.R.anim.slide_in_left);
animation.setDuration(3000);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public void onBindViewHolder(RecyclerAdapter.TaskHolder holder, int position) {
try{
Task itemTask = mTasks.get(position);
holder.bindTask(itemTask, completedStatus);
mAnimator.onBindViewHolder(holder.itemView, position);
}
catch(Exception ex){
Log.d("onBindViewHolder", ex.getMessage());
}
}
#Override
public int getItemCount() {
try{
return mTasks.size();
}
catch(Exception ex){
Log.d("getItemCount", ex.getMessage());
return 0;
}
}
public ArrayList<Task> getListTasks(){
return mTasks;
}
}
TaskDBHelper.java
public class TaskDbHelper extends SQLiteOpenHelper{
// Table Name
public static final String TABLE_NAME = "tasks";
// Table columns
public static final String _ID = "_id";
public static final String COL_TASK_TITLE = "title";
public static final String COL_TASK_PARENT_ID = "parent_id";
public static final String COL_TASK_COMPLETED_STATUS = "completed_status";
public static final String COL_TASK_CREATED_DATETIME = "created_datetime";
public static final String COL_TASK_MODIFIED_DATETIME = "modified_datetime";
// Database Information
static final String DB_NAME = "com.sagarmhatre.simpletodo";
// database version
static final int DB_VERSION = 1;
public TaskDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
String createTable = "CREATE TABLE " + TABLE_NAME + " ( " +
_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_TASK_TITLE + " TEXT NOT NULL," +
COL_TASK_PARENT_ID + " INTEGER DEFAULT 0," +
COL_TASK_COMPLETED_STATUS + " BOOLEAN DEFAULT 0," +
COL_TASK_CREATED_DATETIME + " DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'LOCALTIME'))," +
COL_TASK_MODIFIED_DATETIME + " DATETIME" +");";
db.execSQL(createTable);
}
catch (Exception ex){
Log.d("TaskDbHelper", "Exception: " + ex.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Insert Value
public void adddata(Context context,String task_title) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TASK_TITLE, task_title);
db.insert(TABLE_NAME, null, values);
db.close();
}
public Task adddataWithReturnTask(Context context,String task_title) {
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TASK_TITLE, task_title);
db.insert(TABLE_NAME, null, values);
db.close();
ArrayList<Task> taskList = this.getAddedTask("0");
return taskList.get(0);
}
catch(Exception ex){
Log.d("MainActivity", "Exception: " + ex.getMessage());
return null;
}
}
//Delete Query
public void deleteTask(String id) {
String deleteQuery = "DELETE FROM " + TABLE_NAME + " where " + _ID + "= " + id ;
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(deleteQuery);
}
public void changeTaskStatus(Context context,Boolean taskStatus, String id) {
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if(taskStatus)
values.put(COL_TASK_COMPLETED_STATUS, 1);
else
values.put(COL_TASK_COMPLETED_STATUS, 0);
db.update(TABLE_NAME, values, _ID + "=" + id, null);
db.close();
}
catch(Exception ex){
Log.d("changeTaskStatus() ", "Exception: " + ex.getMessage());
}
}
// Edit task - by me
public void editTask(Context context,String task_title, String id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TASK_TITLE, task_title);
db.update(TABLE_NAME, values, _ID + "=" + id, null);
db.close();
}
//Get Row Count
public int getCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}
//Get FavList
public ArrayList<Task> getTaskList(String ParentID, Boolean completedStatus){
try{
String selectQuery;
if(completedStatus){
selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 1 + " ORDER BY " + _ID + " DESC";
}else{
selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 0 + " ORDER BY " + _ID + " DESC";
}
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<Task> TaskList = new ArrayList<Task>();
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
task.title = cursor.getString(1);
task.parent_id = Integer.parseInt(cursor.getString(2));
task.completed_status = Boolean.parseBoolean(cursor .getString(3));
task.created_datetime = cursor.getString(4);
task.modified_datetime = cursor.getString(5);
TaskList.add(task);
} while (cursor.moveToNext());
}
return TaskList;
}
catch(Exception ex){
Log.d("getTaskList() ", "Exception: " + ex.getMessage());
return null;
}
}
public Task getTaskById(String _id){
try{
String selectQuery;
selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ _ID + "="+_id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<Task> TaskList = new ArrayList<Task>();
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
task.title = cursor.getString(1);
task.parent_id = Integer.parseInt(cursor.getString(2));
task.completed_status = Boolean.parseBoolean(cursor .getString(3));
task.created_datetime = cursor.getString(4);
task.modified_datetime = cursor.getString(5);
TaskList.add(task);
} while (cursor.moveToNext());
}
return TaskList.get(0);
}
catch(Exception ex){
Log.d("getTaskList() ", "Exception: " + ex.getMessage());
return null;
}
}
public ArrayList<Task> getAddedTask(String ParentID){
try{
String selectQuery;
selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 0 + " ORDER BY " + _ID + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<Task> TaskList = new ArrayList<Task>();
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
task.title = cursor.getString(1);
task.parent_id = Integer.parseInt(cursor.getString(2));
task.completed_status = Boolean.parseBoolean(cursor .getString(3));
task.created_datetime = cursor.getString(4);
task.modified_datetime = cursor.getString(5);
TaskList.add(task);
} while (cursor.moveToNext());
}
return TaskList;
}
catch(Exception ex){
Log.d("getTaskList() ", "Exception: " + ex.getMessage());
return null;
}
}
}
Tab1.java
public class Tab1 extends Fragment {
private static final String TAG = "Tab1";
private TaskDbHelper mHelper;
//int listResourceID;
//ViewAdapter viewAdapter;
Context incompleteListContext;
Toolbar toolbar;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
RecyclerAdapter adapter;
public void setContext(Context context){
this.incompleteListContext = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
mRecyclerView = rootView.findViewById(R.id.list_todo);
mRecyclerView.setHasFixedSize(true);
//mRecyclerView.setItemAnimator(new SlideInLeftAnimator());
//SlideInUpAnimator animator = new SlideInUpAnimator(new OvershootInterpolator());
//mRecyclerView.setItemAnimator(animator);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLinearLayoutManager);
updateUI();
return rootView;
}
//#Override
//public void onViewCreated(View rootView, Bundle savedInstanceState){
//incompleteList = rootView.findViewById(R.id.list_todo_completed);
//updateUI();
//}
public void updateUI() {
try {
mHelper = new TaskDbHelper(incompleteListContext);
ArrayList<Task> taskList = mHelper.getTaskList("0",false);
adapter = new RecyclerAdapter(taskList, false, incompleteListContext, mRecyclerView);
mRecyclerView.setAdapter(adapter);
}
catch (Exception ex) {
Log.d(TAG, "Exception: " + ex.getMessage());
}
}
public RecyclerView getRecyclerView(){
return mRecyclerView;
}
}
So far I am successful in implementing delete and update operation without reloading the whole list in Tab1. But after adding an item I want to add it to the top and I am unable to do it as seen in most of RecyclerView tutorials. SO currently I reload the whole list (which I Know is not appropriate).
Need a way to not load whole list and add item at the top of list.
Being new to android development, any kind of help is welcome.
It's a bit hard to read Your code -> Please don't mix camelcase pascalcase prefix and non-prefix naming for variable.
For adding item on the top try with (PSEUDO CODE):
items.add(0, ITEM_HERE);
adapter.notifyDataSetChanged();
recyclerView.smoothScrollToPosition(0);
This addTask method not working like You want?
public void addTask(Task task){
mTasks.add(0, task);
notifyItemInserted(0);
smoothScrollToPosition(0);
}
I have list of music that user set time to play. I want to have a button to cancel m count down timer .
I test some way but it doesn't work at all.
here is my code to play and set time to play.
public class Main extends Activity {
public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;
List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();
InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
indexStore = new MyIndexStore(getApplicationContext());
setContentView(R.layout.main_activity);
splash = new Splash(this);
splash.set_identity("1");
initiate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
//lastview = null;
listView = (ListView) findViewById(R.id.list);
ReadText1();
names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
ReadText2();
infos = lines2.toArray(new String[0]);
tracks = array_audio.toArray(new String[0]);
adaptor = new Adaptor(getApplicationContext(), tracks, names, infos);
listView.setAdapter(adaptor);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
if (lastview != null) {
ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
play.setImageResource(R.drawable.n_btn_play_unselected);
}
}
});
}
private static void initiate() {
Field[] fields = R.raw.class.getFields();
array_audio.clear();
for (int count = 0; count < fields.length; count++) {
array_audio.add("a" + (count + 1));
}
}
private void play(int index) {
mediaPlayer.release();
index++;
String s = "a" + index;
Resources resources = getResources();
final int resourceId = resources.getIdentifier(s, "raw", getPackageName());
try {
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
mediaPlayer.release();
listView.invalidateViews();
super.onPause();
}
private void ReadText1() {
lines1.clear();
line = "1";
try {
in = this.getAssets().open("names.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines1.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReadText2() {
lines2.clear();
line = "1";
try {
in = this.getAssets().open("infos.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines2.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Adaptor extends ArrayAdapter<String> {
private final Context context;
private final String[] tracks;
private final String[] names;
private final String[] infos;
private HashMap<Integer,String> textMap;
Typeface type_face;
public Adaptor(Context context, String[] tracks, String[] names, String[] infos) {
super(context, R.layout.track, tracks);
this.context = context;
this.tracks = tracks;
this.names = names;
this.infos = infos;
type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
this.textMap = new HashMap<>();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.track, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.track_name);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
name.setText(names[position]);
name.setTypeface(type_face);
name.setTypeface(type_face);
final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
if (position == indexStore.getindex())
ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
ringtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(Main.this);
final View deleteDialogView = factory.inflate(
R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
deleteDialog.setView(deleteDialogView);
TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
hour_device = hour;
minute_device = minute;
device_time.setText(hour_device + ":" + minute_device);
deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);
hour_user = timePicker.getCurrentHour();
minute_user = timePicker.getCurrentMinute();
String time1 = hour_device + ":" + minute_device;
String time2 = hour_user + ":" + minute_user;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
try {
date1 = format.parse(time1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
long result = date2.getTime() - date1.getTime();
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info int'o it
textMap.put(new Integer(position), "seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info into it
textMap.put(new Integer(position),null);
//notify about the data change
notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
});
return rowView;
}
}
}
make the count down timer an instance variable;
private CountDownTimer timer;
then delegate your count to this variable:
#Override
public void onClick(View v) {
...
timer = new CountDownTimer(result, 1000) {
...
}
}
now you can stop the timer whenever you want to:
timer.cancel();
Check this code, working Successfull
call class from here
timer = new CounterClass(timeInmilles, 1000);
timer.start();
CounterClass is here
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
}
public void onTick(long millisUntilFinished) {
}
}
use to cancel see below line
timer.cancel()
having one text and audio(recording) and saving the name and path in db.while clicking the name that audio has to play its playing also.But while editing if i supposed to change the name alone,it will not take the old file name of the respective one,its make that one as null.
How to take the old audio file name if people will not update the audio(recording)
audioactivity.java
private void saveState() {
String audioname = et1.getText().toString();
String audiofilename = gfilename;
String audiocount = et2.getText().toString();
if(audiocount.equals("")){
audiocount ="1";
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String audiodate = sdf.format(new Date());
if (mRowId == null || mRowId.longValue() == 0)
{
long id = mDbHelper.createProject4(audioname, audiofilename, audiocount, audiodate);
if (id > 0) {
mRowId = id;
}
} else {
audiofilename=gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
}
public View.OnClickListener btnClick = new View.OnClickListener()
{
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:{
AppLog.logString("Start Recording");
enableButtons(true);
startRecording();
break;
}
case R.id.btnstop:{
AppLog.logString("Start Recording");
enableButtons(false);
stopRecording();
break;
}
}
}
};
public MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
AppLog.logString("Error: " + what + ", " + extra);
}
};
public MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
AppLog.logString("Warning: " + what + ", " + extra);
}
};
public void setButtonHandlers() {
((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnstop)).setOnClickListener(btnClick);
}
public void enableButton(int id,boolean isEnable){
((Button)findViewById(id)).setEnabled(isEnable);
}
public void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart,!isRecording);
enableButton(R.id.btnstop,isRecording);
}
#SuppressLint("NewApi")
private void startRecording(){
//displayFormatDialog();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = {"MPEG 4", "3GPP", "AMR"};
builder.setTitle(getString(R.string.choose_format_title))
.setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
dialog.dismiss();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
//recorder.setOnErrorListener(errorListener);
//recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.show();
}
private void stopRecording(){
if(null != recorder)
{
//mDbHelper.updateProject4FileName(mRowId, gfilename);
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
else
{
recorder.stop();
recorder.release();
}
}
public String getFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
gfilename = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
return (gfilename);
}
#Override
public void onCompletion (MediaPlayer arg0)
{
}
public void playSong(String gfilename){
// Play song
try
{
mp.reset();
mp.setDataSource(gfilename);
mp.prepare();
mp.start();
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I checked in debugging also,if we didnt update the recording its taking that place as null only.
Here i attached my db updated code also
public boolean updateProject4(long _id, String audioname, String audiofilename,String audiocount,String audiodate) {
ContentValues args = new ContentValues();
args.put(CATEGORY_COLUMN_AUDIONAME, audioname );
args.put(CATEGORY_COLUMN_AUDIOFILENAME, audiofilename );
args.put(CATEGORY_COLUMN_AUDIOCOUNT, audiocount );
args.put(CATEGORY_COLUMN_AUDIODATE, audiodate );
return mDb.update(DATABASE_TABLE_AUDIOPRAYER, args, CATEGORY_COLUMN_ID4 + "=" + _id, null) > 0;
}
Actually i got the way for my question.
Want to fetchfile from db if my filename becomes null while updating
private void saveState() {
String audioname = et1.getText().toString();
String audiofilename = gfilename;
String audiocount = et2.getText().toString();
if(audiocount.equals("")){
audiocount ="1";
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String audiodate = sdf.format(new Date());
//String reqname= spin.getSelectedItem().toString();
//Log.i(" save state mathod "," values are "+title+Desc+Body+reqname);
if (mRowId == null || mRowId.longValue() == 0)
{
long id = mDbHelper.createProject4(audioname, audiofilename, audiocount, audiodate);
if (id > 0) {
mRowId = id;
}
} else {
if(audiofilename.equals("")){
Cursor filename = mDbHelper.fetchProject4FileName(mRowId, audiofilename);
startManagingCursor(filename);
gfilename =filename.getString(filename.getColumnIndexOrThrow(GinfyDbAdapter.CATEGORY_COLUMN_AUDIOFILENAME));
//mDbHelper.fetchProject4FileName(mRowId, audiofilename);
audiofilename = gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
else
{
audiofilename = gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
}
we have to fetch the filename from db and check whether our audiofilename is null means,we have to set the older filename
I am having a problem on the line where I call the query to PostCategoryContent Provider
I get an error stating:
11-13 10:23:40.674: E/AndroidRuntime(26012): android.database.sqlite.SQLiteException: no such column: category_id (code 1): , while compiling: SELECT * FROM post WHERE (category_id=39)
Even though the URI points to another Table postCategory
Can anyone guide me on what I'm doing wrong?
public class PostFragment extends SherlockListFragment implements LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
private boolean dataRetrieved;
private SlidingArea parent;
PullToRefreshListView pullToRefreshView;
EditText searchBox;
Bundle args = new Bundle();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parent = (SlidingArea) getActivity();
setHasOptionsMenu(true);
fillData(false);
}
#Override
public void onResume() {
super.onResume();
parent.getSupportActionBar().setCustomView(R.layout.kpmg_actionbar_list_view);
parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ImageView searchButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_search_list);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (searchBox.getVisibility() == View.GONE)
{
searchBox.setVisibility(View.VISIBLE);
searchBox.requestFocus();
InputMethodManager imm = (InputMethodManager) parent.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchBox, InputMethodManager.SHOW_IMPLICIT);
} else {
searchBox.setVisibility(View.GONE);
searchBox.clearFocus();
hideKeyboard(v);
}
}
});
final ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getData(getString(R.string.kpmg_json_get_articles), true);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh_dark);
fillData(true);
}
});
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
filterData(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
//Constant used as key for ID being passed in the bundle between fragments
public static final String NEWS_ID = "newsID";
private void getData(String url, boolean showProgressDialog) {
new Request(showProgressDialog).execute(new String[] {url});
}
public class Request extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
/* This is the only file that needs to be edited */
private GetResponse response = null;
private boolean showProgressDialog = true;
public Request(boolean showProgressDialog)
{
super();
this.showProgressDialog = showProgressDialog;
response = new GetResponse();
}
#Override
protected void onPreExecute() {
if (showProgressDialog) {
dialog = new ProgressDialog(parent);
dialog.setMessage("Retrieving latest information...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
//This method must return the type specified in the constructor
#Override
protected String doInBackground(String... url) {
response.setUrl(url[0]);
String res = response.execute();
// When it returns the "res" it will call onPostExecute
return res;
}
#Override
protected void onPostExecute(String result) {
// Here we have response from server
if ( isNetworkAvailable() ){
try {
JSONObject json = new JSONObject(result);
JSONArray arr = json.getJSONArray("posts");
for (int i = arr.length() - 1; i >= 0; --i) {
JSONObject row = arr.getJSONObject(i);
JSONArray arrCategories = row.getJSONArray("categories");
int Created = 0;
int Updated = 0;
for (int j = arrCategories.length() -1; j >= 0; --j){
JSONObject rowCategory = arrCategories.getJSONObject(j);
ContentValues categoryValues = new ContentValues();
categoryValues.put(PostCategoryTable.CATEGORY_ID, rowCategory.getInt("id"));
Cursor categoryCursor = parent.getContentResolver().query(PostCategoryContentProvider.CONTENT_URI, null, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null, null);
int categoryCount = categoryCursor.getCount();
if (categoryCount == 0) {
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().insert(PostCategoryContentProvider.CONTENT_URI, categoryValues);
Created++;
}
else {
categoryCursor.moveToFirst();
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().update(PostCategoryContentProvider.CONTENT_URI, categoryValues, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null);
Updated++;
}
categoryCursor.close();
}
Toast.makeText(parent,"Created : " + "" + Created + " | Updated : " + "" + Updated, Toast.LENGTH_SHORT).show();
if (row.getString("status").equals("publish")) {
ContentValues values = new ContentValues();
values.put(PostTable.POST_ID, row.getString("id"));
values.put(PostTable.CONTENT, Html.fromHtml(row.getString(PostTable.CONTENT)).toString());
values.put(PostTable.EXCERPT, Html.fromHtml(row.getString(PostTable.EXCERPT)).toString());
//image
//imageurl
values.put(PostTable.DATE_MODIFIED, row.getString(PostTable.DATE_MODIFIED));
values.put(PostTable.DATE_PUBLISHED, row.getString(PostTable.DATE_PUBLISHED));
//thumbnail
//thumbnailurl
values.put(PostTable.TITLE, row.getString(PostTable.TITLE));
values.put(PostTable.URL, row.getString("online-url"));
values.put(PostTable.VIDEO_URL, row.getString("video-url"));
//Check for new Categories
//getThumbnail
// byte[] image = AppHelper.getBlobFromURL(row.getString(BlogTable.THUMBNAIL));
// if (image != null) {
//
// values.put(BlogTable.THUMBNAIL, image);
//
// }
Cursor c = parent.getContentResolver().query(PostContentProvider.CONTENT_URI, null, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null, null);
int count = c.getCount();
if (count == 0) {
parent.getContentResolver().insert(PostContentProvider.CONTENT_URI, values);
}
else {
c.moveToFirst();
if (!(c.getString(c.getColumnIndex(PostTable.DATE_MODIFIED)).equalsIgnoreCase(values.getAsString(PostTable.DATE_MODIFIED)))) {
//
//
// if (c.getString(c.getColumnIndex(BlogTable.THUMBNAIL)) != values.get(BlogTable.THUMBNAIL)){
// //reset image
// }
//
parent.getContentResolver().update(PostContentProvider.CONTENT_URI, values, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null);
}
}
c.close();
//Here we should last retrieved time and used as part of the condition before retrieving data
}
else {
String currentID = row.getString("id");
// Delete unpublished fields
parent.getContentResolver().delete(PostContentProvider.CONTENT_URI, "_id = " + currentID, null);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Toast toast = Toast.makeText( parent , "You are not connected to the internet. Please check your connection, or try again later",
Toast.LENGTH_SHORT);
toast.show();
}
// Call onRefreshComplete when the list has been refreshed.
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh);
if (showProgressDialog) {
dialog.dismiss();
}
}
}
private void fillData(boolean isRefresh){
//_id is expected from this method that is why we used it earlier
String[] from = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT};
int[] to = new int[] { R.id.kpmg_text_news_title, R.id.kpmg_text_news_date, R.id.kpmg_text_news_excerpt};
//initialize loader to call this class with a callback
if (!isRefresh){
getLoaderManager().initLoader(0, null, this);
}
else {
if (searchBox.getText().length() == 0) {
getLoaderManager().restartLoader(0, null, this);
}
else {
getLoaderManager().restartLoader(0, args, this);
}
}
//We create adapter to fill list with data, but we don't provide any data as it will be done by loader
adapter = new SimpleCursorAdapter(parent, R.layout.kpmg_list_view, null, from, to, 0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
if( column == cursor.getColumnIndex(PostTable.DATE_PUBLISHED) ){ // let's suppose that the column 0 is the date
TextView textDate = (TextView) view.findViewById(R.id.kpmg_text_news_date);
String dateStr = cursor.getString(cursor.getColumnIndex(PostTable.DATE_PUBLISHED));
String formattedDate = AppHelper.calculateRelativeDate(dateStr);
textDate.setText( "Posted - " + formattedDate);
return true;
}
return false;
}
});
setListAdapter(adapter);
}
private void filterData(CharSequence cs){
args.putString("Selection", cs.toString());
getLoaderManager().restartLoader(0, args, this /*LoaderCallbacks<Cursor>*/);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle args) {
String[] projection = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT, PostTable.ID };
CursorLoader loader;
if (args == null) {
Log.i("Arguments","None");
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, null, null, PostTable.DATE_PUBLISHED + " DESC");
}
else {
Log.i("Arguments","Full");
String selectionKeyword = args.getString("Selection");
String selection = PostTable.TITLE + " LIKE ? OR " + PostTable.CONTENT + " LIKE ? OR " + PostTable.EXCERPT + " LIKE ?";
String[] selectionArgs = new String[] {"%" + selectionKeyword + "%","%" + selectionKeyword + "%","%" + selectionKeyword + "%"};
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, selection, selectionArgs, PostTable.DATE_PUBLISHED + " DESC");
}
return loader;
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
On which line is the exception thrown? The problem is more likely an issue with your SQLite syntax than with anything having to do with Loaders or Cursors. Make sure your table is getting initialized as you require. Do a DatabaseUtils.dumpCursor(cursor) to analyze the contents of the Cursor between the exception is thrown. Also, I would look into your use of LIKE... I have seen people having issues with that keyword before.