I have a table layout where rows are dynamically added. I want 30 data to be shown in one page.pages should be automatically added with increasing data. This is my code.
int increment = 0;
public int TOTAL_LIST_ITEMS;
public int NUM_ITEMS_PAGE = 50;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.frag_tab1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tableLayout = (TableLayout) view.findViewById(R.id.tableLay);
buttonNext = (Button) view.findViewById(R.id.next);
listView = (ListView) view.findViewById(R.id.list);
title = (TextView) view.findViewById(R.id.text);
buttonPrev = (Button) view.findViewById(R.id.prev);
buttonPrev.setEnabled(false);
// data = new ArrayList<String>();
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment++;
loadList(increment);
Toast.makeText(getActivity(),"the page is"+increment,Toast.LENGTH_LONG).show();
checkEnable();
}
});
buttonPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment--;
loadList(increment);
Toast.makeText(getActivity(),"the page is"+increment,Toast.LENGTH_LONG).show();
checkEnable();
}
});
db = getActivity().openOrCreateDatabase("hitechData.db", Context.MODE_PRIVATE, null);
DBHelper dh = new DBHelper(getActivity(), "hitechData.db", null, 1);
tableLayout.setColumnStretchable(0, true);
tableLayout.setColumnStretchable(2, true);
tableLayout.setStretchAllColumns(true);
tableLayout.bringToFront();
db = getActivity().openOrCreateDatabase("hitechData.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
dh.onCreate(db);
db.setLockingEnabled(true);
String query = "SELECT * FROM leadData3 Order by id DESC";
Cursor cur;
cur = db.rawQuery(query, null);
TOTAL_LIST_ITEMS = cur.getCount();
data=TOTAL_LIST_ITEMS;
int val = TOTAL_LIST_ITEMS % NUM_ITEMS_PAGE;
val = val == 0?0:1;
pageCount = TOTAL_LIST_ITEMS / NUM_ITEMS_PAGE;
if (cur != null && cur.getCount() > 0) {
if (cur.moveToFirst()) {
try {
while (cur.isAfterLast() == false ){
TableRow tr = new TableRow(getActivity().getBaseContext());
final TextView compName = new TextView(getActivity().getBaseContext());
compName.setBackgroundResource(R.drawable.borderr);
final TextView firstName = new TextView(getActivity().getBaseContext());
firstName.setBackgroundResource(R.drawable.borderr);
final TextView midName = new TextView(getActivity().getBaseContext());
midName.setBackgroundResource(R.drawable.borderr);
final TextView lastName = new TextView(getActivity().getBaseContext());
lastName.setBackgroundResource(R.drawable.borderr);
compName.append(cur.getString(1));
compName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
compName.setPadding(30, 0, 0, 0);
firstName.append(cur.getString(21));
firstName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
firstName.setPadding(30, 0, 0, 0);
midName.append(cur.getString(22));
midName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
midName.setPadding(30, 0, 0, 0);
lastName.append(cur.getString(23));
lastName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
lastName.setPadding(30, 0, 0, 0);
// String name =firstName.getText().toString()+midName.getText().toString()+lastName.getText().toString();
firstName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameValue = firstName.getText().toString();
String companyValue = compName.getText().toString();
Intent intent = new Intent(getActivity().getApplicationContext(), ShowDetailData.class);
intent.putExtra("name", nameValue);
intent.putExtra("accNo", companyValue);
Toast.makeText(getActivity().getApplicationContext(), nameValue, Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
tr.addView(firstName);
tr.addView(compName);
tableLayout.addView(tr);
cur.moveToNext();
/* count++;
nextPage++;
Toast.makeText(getActivity().getApplicationContext(), "count is : " + count, Toast.LENGTH_LONG).show();*/
//cur.close();
}
} finally {
cur.close();
db.close();
}
} else {
Toast.makeText(getActivity().getApplicationContext(), "no Data", Toast.LENGTH_LONG).show();
}
}
}
/*
*/
/*
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextPage++;
Toast.makeText(getActivity(), "next page is"+nextPage, Toast.LENGTH_SHORT).show();
}
});*/
private void loadList(int number){
ArrayList<String> sort = new ArrayList<String >();
title.setText("Page "+(number+1+" of " +pageCount));
int start = number * NUM_ITEMS_PAGE;
for (int i=start; i<(start)+NUM_ITEMS_PAGE; i++)
{
if(i<data)
{
sort.add(String.valueOf(data));
}
else {
break;
}
// adapter = new ArrayAdapter<String>(getActivity(), //android.R.layout.simple_list_item_1,sort);
// tablerow.setAdapter(adapter);
//implement table row in adapter
}}
private void checkEnable(){
if(increment+1 == pageCount)
{
buttonNext.setEnabled(false);
}
else if(increment == 0){
buttonPrev.setEnabled(false);
}
else {
buttonPrev.setEnabled(true);
buttonNext.setEnabled(true);
}
}
}
I want to know how can i change the page after no. of rows exceeds 30. I am unable to do pagination.
Currently i am using Sqlite and all the filled data is appearing on the first page.
I want to divide the data and want it appear in set of 30 after click of previous and next.
Related
I'm trying to make a laundry ordering application. I've made it to the order process, at the end of the order process, the user clicks the next button to checkout the ordered results, I have successfully made the checkout results, but what I made is still in one variable string. how to put the checkout results into an array variable so that I can post the results in the form of JSONArray?
HERE IS MY ORDER ACTIVITY CODE :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
listProduk.setAdapter(productAdapter);
listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
productAdapter.setCheckBox(position);
}
});
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
tvTotal.setText(String.valueOf(0));
radioReguler.isChecked();
regular = true;
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);
txtnamaProduk.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
AND HERE IS THE CODE OF THE RESULT :
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
in my code above, I still use the variable checkbox to accommodate all the results of the order chosen by the user. how to put all the result into array variable so i can post to server as a JSONArray? Please help me to solve this problem. because i'm still a beginner in android.
HERE IS MY ADAPTER CODE IF NEEDED :
public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;
public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
this.context = context;
this.productItems = items;
this.produk = produk;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
final ProductModel items = productItems.get(position);
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_produk, null, true);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
viewHolder.count = (TextView) view.findViewById(R.id.count_product);
viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
viewHolder.price = (TextView) view.findViewById(R.id.product_price);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.checkBox.setText(items.getProduct_name());
viewHolder.price.setText(items.getProduct_price());
viewHolder.count.setText(String.valueOf(items.getCountProduct()));
//fungsi untuk set posisi textview + dan -
viewHolder.increase.setTag(R.integer.btn_plus_view, view);
viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);
//fungsi untuk disable textview + dan - jika checkbox tidak di klik
viewHolder.decrease.setOnClickListener(null);
viewHolder.increase.setOnClickListener(null);
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
viewHolder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);
int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.tambah(pos);
}
});
viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);
int total = productItems.get(pos).getCountProduct();
if (total>0){
int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.kurang(pos);
}
}
});
} else {
viewHolder.checkBox.setChecked(false);
//fungsi untuk reset jumlah harga dan produk pada checkbox
String count = viewHolder.count.getText().toString();
int jumlah = Integer.parseInt(count);
int harga = Integer.parseInt(productItems.get(position).getProduct_price());
int kurang = jumlah * harga;
viewHolder.count.setText("0");
productItems.get(position).setCountProduct(0);
produk.kurangCheckbox(kurang);
}
return view;
}
public ArrayList<ProductModel> getAllData(){
return productItems;
}
public void setCheckBox(int position){
ProductModel items = productItems.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
static class ViewHolder{
TextView decrease, count, increase, price;
CheckBox checkBox;
}
}
just create getter setter method of Arraylist like below
CompleteOrder:-
public class CompleteOrder {
List<OrderItem> order_items;
public List<OrderItem> getOrder_items() {
return order_items;
}
public void setOrder_items(List<OrderItem> order_items) {
this.order_items = order_items;
}
}
Create another Getter setter class of variable you want to add in arraylist
OrderItem:-
public class OrderItem {
String product_name;
int product_total;
public OrderItem(String product_name, int product_total) {
this.product_name = product_name;
this.product_total = product_total;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_total() {
return product_total;
}
public void setProduct_total(int product_total) {
this.product_total = product_total;
}
}
Now in your onClick method just create new List as below
public void onClick(View view) {
String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
List<OrderItem> masterProductorderCount=new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);
}
}
completeOrder.setOrder_items(masterProductorderCount);
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(completeOrder);//pass object of CompleteOrder
}
});
CompleteOrder object give JSON output as below
{
"CompleteOrder":[
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
}
]
}
make a model that contains product name , total and etc,
then put each data into an object and put each object into an array
finally use Gson to map properties to model / list of models or the other way around.
ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
Model model = new Model();
model.productName = hold.getProduct_name();
model.total = total;
list.add(model);
}
}
String jsonArray = Gson().toJson(list);
You need to create a JSONObject for each entry in the JSONArray.
As far as I can see this should take care of it:
public void onClick(View view) {
String checkbox = "";
JSONArray jsonArray = new JSONArray();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
JSONObject jsonObj = new JSONObject();
jsonObj.put("product_name", hold.getProduct_name());
jsonObj.put("product_total", total);
jsonArray.put(jsonObj);
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
String jsonArrayString = jsonArray.toString();
formSubmit(dipilih);
}
Depending on your data the resulting string from jsonArrayString would be:
{[
{"product_name":"product1","product_total":1},
{"product_name":"product2","product_total":2},
{"product_name":"product3","product_total":3}
]}
I really do not know what you intend on doing with the JSON data so I just created a String "jsonArrayString".. do what ever you need to with it.
I'm creating an alarm clock application, and I'd like the homepage to have multiple Alarm objects shown, like the default Android clock application. To do this, I've been trying a ListView to create a button for each Alarm in an ArrayList of Alarms.
Debugging the crashes this caused, I've found that it can't implement Serializable or Parcelable due to the Context object within it, and thus I have no way to pass it from one activity to another. The ListView works fine when I create the alarms from the MainActivity itself, but when I use the CreateAlarmActivity that takes input from the user, the ListView won't pass through and it crashes.
I haven't found this precise problem on StackOverflow. This problem is close (Implementing Parcelable Class That Requires Context) but involves a database, which seems overkill for my needs.
If a ListView is even the best way to go about this, how should I pass the ListView between activities? If there's a better way, what would be a better implementation?
I apologise for the large amount of code. I'm not sure exactly what may prove relevant, so I've erred on the side of too much information rather than too little.
Code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
ListView alarmListView;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
int[] testArray = {0, 0, 0, 0, 0, 0, 0};
Alarm testAlarm = new Alarm("testAlarm", 6, 1, true, testArray, 10);
Alarm testAlarm2 = new Alarm("testAlarm2", 6, 1, true, testArray, 10);
AlarmAdapter alarmAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmListView = (ListView) findViewById(R.id.alarmListView);
alarmList.add(testAlarm);
alarmList.add(testAlarm2);
alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList);
alarmListView.setAdapter(alarmAdapter);
alarmAdapter.notifyDataSetChanged();
}
// Create alarm when user presses FAB on activity_main.xml.
public void createNewAlarm(View view) {
Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
createAlarmIntent.putExtra("alarmList", alarmList);
createAlarmIntent.putExtra("alarmAdapter", alarmAdapter);
startActivity(createAlarmIntent);
}
public void testAlarmActivated(View view){
Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
startActivity(activateAlarmIntent);
}
}
AlarmAdapter.java:
public class AlarmAdapter extends BaseAdapter implements Parcelable {
private Context alarmContext;
private ArrayList<Alarm> alarmList;
public AlarmAdapter(Context context, ArrayList arrayList) {
super();
alarmContext = context;
alarmList = arrayList;
}
public int getCount() {
return alarmList.size();
}
// getView method is called for each item of ListView
public View getView(int position, View view, ViewGroup parent) {
// inflate the layout for each item of listView
LayoutInflater inflater = (LayoutInflater) alarmContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.alarm_row, parent, false);
// get the reference of textView and button
TextView alarmName = (TextView) view.findViewById(R.id.title);
// Button alarmButton = (Button) view.findViewById(R.id.alarmButton);
// Set the title and button name
Alarm tempAlarm = alarmList.get(position);
alarmName.setText(tempAlarm.name);
// btnAction.setText("Action " + position);
// Click listener of button
/*btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Logic goes here
}
});*/
return view;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
protected AlarmAdapter(Parcel in) {
alarmContext = (Context) in.readValue(Context.class.getClassLoader());
if (in.readByte() == 0x01) {
alarmList = new ArrayList<Alarm>();
in.readList(alarmList, Alarm.class.getClassLoader());
} else {
alarmList = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(alarmContext);
if (alarmList == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(alarmList);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<AlarmAdapter> CREATOR = new Parcelable.Creator<AlarmAdapter>() {
#Override
public AlarmAdapter createFromParcel(Parcel in) {
return new AlarmAdapter(in);
}
#Override
public AlarmAdapter[] newArray(int size) {
return new AlarmAdapter[size];
}
};
}
Alarm.java:
public class Alarm implements Serializable {
String name;
int hour;
int minute;
boolean isPm;
int[] daysActive;
int snoozeTimer;
public Alarm(String startName, int startHour, int startMinute,
Boolean startIsPm, int[] startDaysActive, int startSnoozeTimer){
name = startName;
hour = startHour;
minute = startMinute;
isPm = startIsPm;
daysActive = startDaysActive;
snoozeTimer = startSnoozeTimer;
}
}
CreateAlarmActivity.java:
public class CreateAlarmActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");
alarmAdapter = (AlarmAdapter)getIntent().getParcelableExtra("alarmAdapter)");
}
int alarmHour = 6;
int alarmMinute = 0;
boolean isPm = false;
int snoozeTimer = 10;
int [] daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
AlarmAdapter alarmAdapter;
// Add one to the hour of the alarm.
public void changeHour(View view) {
Button btn = findViewById(R.id.buttonHours);
if (alarmHour == 12){
alarmHour = 0;
}
else {
alarmHour++;
}
btn.setText(Integer.toString(alarmHour));
}
// Add one to the minute of the alarm.
public void changeMinute(View view) {
Button btn = findViewById(R.id.buttonMinutes);
if (alarmMinute == 59) {
alarmMinute = 0;
}
else {
alarmMinute++;
}
if (alarmMinute < 10) {
// Ensure minute 1 becomes 01, e.g, 6:01 am.
btn.setText("0" + Integer.toString(alarmMinute));
}
else {
btn.setText(Integer.toString(alarmMinute));
}
}
public void changeAmPm(View view) {
Button btn = findViewById(R.id.buttonAmPm);
if (isPm == true) {
isPm = false;
btn.setText("am");
}
else {
isPm = true;
btn.setText("pm");
}
}
public void changeSnoozeTimer(View view) {
Button btn = findViewById(R.id.buttonSnoozeTimer);
if (snoozeTimer == 15){
snoozeTimer = 1;
}
else {
snoozeTimer++;
}
btn.setText(Integer.toString(snoozeTimer));
}
public void finishAlarm(View view){
EditText alarmName = findViewById(R.id.alarmName);
String name = alarmName.getText().toString();
Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);
alarmList.add(alarm);
alarmAdapter.notifyDataSetChanged();
Intent finishAlarmIntent = new Intent(this, MainActivity.class);
finishAlarmIntent.putExtra("alarmList", alarmList);
startActivity(finishAlarmIntent);
}
public void cancelAlarm(View view){
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
startActivity(cancelAlarmIntent);
}
public void changeSunday(View view) {
Button btn = findViewById(R.id.buttonSunday);
if (daysActive[0] == 0){
daysActive[0] = 1;
// Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
// Credit goes to EddieB for the below line.
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[1] = 0;
// Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
// Credit goes to Ivo for the below line.
btn.getBackground().clearColorFilter();
}
}
public void changeMonday(View view) {
Button btn = findViewById(R.id.buttonMonday);
if (daysActive[1] == 0){
daysActive[1] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[1] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeTuesday(View view) {
Button btn = findViewById(R.id.buttonTuesday);
if (daysActive[2] == 0){
daysActive[2] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[2] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeWednesday(View view) {
Button btn = findViewById(R.id.buttonWednesday);
if (daysActive[3] == 0){
daysActive[3] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[3] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeThursday(View view) {
Button btn = findViewById(R.id.buttonThursday);
if (daysActive[4] == 0){
daysActive[4] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[4] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeFriday(View view) {
Button btn = findViewById(R.id.buttonFriday);
if (daysActive[5] == 0){
daysActive[5] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[5] = 0;
btn.getBackground().clearColorFilter();
}
}
public void changeSaturday(View view) {
Button btn = findViewById(R.id.buttonSaturday);
if (daysActive[6] == 0){
daysActive[6] = 1;
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
}
else {
daysActive[6] = 0;
btn.getBackground().clearColorFilter();
}
}
}
I am working on a simple Grading app project with 3 activities, the first one is storing some data in a database and i am replicating that data in both the first activity and the third activity.
The second activity is doing an average calculation and showing the results on that same page, but i want that result to also be shown on the third page. I tried using intents but when i click the button to go to the third page it forces close. What am i doing wrong.
I am trying to show this results in a textview
This is the Second Activity code:
public class AverageActivity extends AppCompatActivity {
EditText editmanner, editinstances, editshortstance, editstrikes, editboxingskills, editknocks, editkicks, editResults;
Button btnResults, btnnewresults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.average_page);
editmanner = (EditText) findViewById(R.id.editText8);
editinstances = (EditText) findViewById(R.id.editText9);
editshortstance = (EditText) findViewById(R.id.editText10);
editstrikes = (EditText) findViewById(R.id.editText11);
editboxingskills = (EditText) findViewById(R.id.editText12);
editknocks = (EditText) findViewById(R.id.editText13);
editkicks = (EditText) findViewById(R.id.editText14);
editResults = (EditText) findViewById(R.id.editText15);
btnResults = (Button) findViewById(R.id.button10);
btnnewresults = (Button) findViewById(R.id.botonresultnuevo);
btnResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int first;
if (editmanner.getText().toString().equals("")) {
first = 0;
} else {
first = Integer.valueOf(editmanner.getText().toString());
}
int second;
if (editinstances.getText().toString().equals("")) {
second = 0;
} else {
second = Integer.valueOf(editinstances.getText().toString());
}
int third;
if (editshortstance.getText().toString().equals("")) {
third = 0;
} else {
third = Integer.valueOf(editshortstance.getText().toString());
}
int fourth;
if (editstrikes.getText().toString().equals("")) {
fourth = 0;
} else {
fourth = Integer.valueOf(editstrikes.getText().toString());
}
int fifth;
if (editboxingskills.getText().toString().equals("")) {
fifth = 0;
} else {
fifth = Integer.valueOf(editboxingskills.getText().toString());
}
int sixth;
if (editknocks.getText().toString().equals("")) {
sixth = 0;
} else {
sixth = Integer.valueOf(editknocks.getText().toString());
}
int seventh;
if (editkicks.getText().toString().equals("")) {
seventh = 0;
} else {
seventh = Integer.valueOf(editkicks.getText().toString());
}
int results;
first = Integer.parseInt(editmanner.getText().toString());
second = Integer.parseInt(editinstances.getText().toString());
third = Integer.parseInt(editshortstance.getText().toString());
fourth = Integer.parseInt(editstrikes.getText().toString());
fifth = Integer.parseInt(editboxingskills.getText().toString());
sixth = Integer.parseInt(editknocks.getText().toString());
seventh = Integer.parseInt(editkicks.getText().toString());
results = (first + second + third + fourth + fifth + sixth + seventh) / 7;
editResults.setText(String.valueOf(results));
}
});
}
public void knowtheresults(View view) {
switch (view.getId()) {
case R.id.botonresultnuevo:
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
Bundle miBundle = new Bundle();
miBundle.putString("nombre", editResults.getText().toString());
miintent.putExtras(miBundle);
startActivity(miintent);
break;
}
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Summary")) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
}
}
}
And This is the Third activity code:
public class ResultActivity extends Activity {
TextView texto;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
texto = (TextView) findViewById(R.id.editText15);
Bundle mibundle=this.getIntent().getExtras();
if(mibundle!=null){
String dato = mibundle.getString("nombre");
texto.setText(dato);
}
mDatabaseHelper = new DatabaseHelper(this);
displayDatabaseInfo();
}
private void displayDatabaseInfo() {
// To access our database, we instantiate our subclass of SQLiteOpenHelper
// and pass the context, which is the current activity.
DatabaseHelper mDbHelper = new DatabaseHelper(this);
// Create and/or open a database to read from it
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Perform this raw SQL query "SELECT * FROM pets"
// to get a Cursor that contains all rows from the pets table.
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
TextView displayView = findViewById(R.id.textViewR1);
try {
displayView.setText("The Student...\n\n");
displayView.append(COL1 + "--" +
COL2 + "--" +
COL4 +
"\n");
// Figure out the index
int idColumnIndex = cursor.getColumnIndex(COL1);
int nameColumnIndex = cursor.getColumnIndex(COL2);
int rankColumnIndex = cursor.getColumnIndex(COL4);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currenRank = cursor.getString(rankColumnIndex);
displayView.append(currentID + "--" +
currentName + "--" +
currenRank + "\n");
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
public void knowtheresults(View view) {
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Start Page")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (button_text.equals("Back...")) {
Intent intent = new Intent(this, AverageActivity.class);
startActivity(intent);
}
}
}
Remove Bundle from your code and use following code
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
miintent.putString("nombre", editResults.getText().toString());
startActivity(miintent);
In you third Activity
String number = getIntent().getStringExtra("nombre");
I have an RecycleView. i take an ArrayList for Fetch all my Category that i inserted in mySqliteDatabase. and finally i set this ArrayList into RecycleView using its Adapter.
Problem:
(1) First Open CategoryActivity. (no categories)
(2) Add First Category, Second, Third no one is Refreshing.
(3) but after Adding First if i go back. and come again in that Activity. and if now i am insert Second categories then all [next items] are getting refresh.
My Problem is whenever i insert 1st Category. it insert successfully but it is not shown in my RecycleView or an ArrayList [means Recycleview not refreshing].
but my Main Problem is my RecycleView is not Refreshing only FirstCategory on My ArrayList.. After adding First item my next all Arraylist item is getting Refreshed.
Below is my All Code.
CategoryAdapter
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> implements Filterable {
private ArrayList<CategoryModel> dataList;
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCategoryItem;
MyViewHolder(View view) {
super(view);
tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
}
}
CategoryAdapter(ArrayList<CategoryModel> dataSet) {
this.dataList = dataSet;
this.filterList = dataSet;
}
// I used this method too. but same problem.
void refreshAdapter(ArrayList<CategoryModel> dataSet) {
dataList.clear();
dataList.addAll(dataSet);
notifyDataSetChanged();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_row_category_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
CategoryModel categoryModel = dataList.get(position);
holder.tvCategoryItem.setText(categoryModel.getCategoryName());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
CategoryListActivity
MyDatabase myDb;
CategoryModel categoryModel;
RecyclerView recyclerCategory;
RecyclerView.LayoutManager layoutManager;
CategoryAdapter adapter;
ArrayList<CategoryModel> allCategory;
int CategoryType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = myDb.getCategoryByType(CategoryType);
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
recyclerCategory.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerCategory,
new RecyclerItemClickListener.OnItemTouchListener() {
#Override
public void onItemClick(View view, int position) {
TextView tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
String CategoryName = tvCategoryItem.getText().toString();
Intent intent = new Intent();
CategoryId = allCategory.get(+position).getCategoryId();
intent.putExtra("CategoryId", String.valueOf(CategoryId));
Log.e("Clicked Cat Id is ", "" + CategoryId);
intent.putExtra("CategoryName", CategoryName);
setResult(Activity.RESULT_OK, intent);
finish();
}
#Override
public void onLongItemClick(View view, int position) {
}
}
));
}
private void openAlert() {
final EditText etCategoryName = new EditText(this);
CustomAlertDialog dialog1 = new CustomAlertDialog(this);
dialog1.setTitle("Add Category");
dialog1.setView(etCategoryName);
dialog1.setCancelable(true);
dialog1.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String CategoryName = etCategoryName.getText().toString().trim();
final String storedCategoryName = myDb.ExistCategory(CategoryName);
if (CategoryName.equals("") && CategoryName.length() == 0) {
Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Enter Category Name");
builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
} else {
if (CategoryName.equals(storedCategoryName)) {
Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Category Already Exists");
builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
} else {
dialogInterface.dismiss();
categoryModel = new CategoryModel(CategoryName, String.valueOf(CategoryType));
myDb.createCategory(categoryModel);
Toast.makeText(CategoryListActivity.this, "CategoryName " + CategoryName
+ "\nCategoryType " + CategoryType, Toast.LENGTH_SHORT).show();
allCategory.clear();
allCategory = myDb.getCategoryByType(CategoryType);
adapter.notifyDataSetChanged();
}
}
}
});
dialog1.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
openAlert();
default:
return super.onOptionsItemSelected(item);
}
}
}
my createCategory() method.
public long createCategory(CategoryModel categoryModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CATEGORY_NAME, categoryModel.getCategoryName());
values.put(CATEGORY_TYPE, categoryModel.getCategoryType());
long CategoryId = db.insert(TABLE_CATEGORY, null, values);
db.close();
return CategoryId;
}
and Finally my getCategoryByType() method on My Database.
public ArrayList<CategoryModel> getCategoryByType(int CategoryType) {
ArrayList<CategoryModel> Categories = new ArrayList<>();
// String selectQuery = "SELECT " + CATEGORY_NAME + " FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType;
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType + " ORDER BY CategoryId DESC";
Log.e(DB_LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
CategoryModel categoryModel = new CategoryModel();
categoryModel.setCategoryId(cursor.getInt(cursor.getColumnIndex(CATEGORY_ID)));
categoryModel.setCategoryName(cursor.getString(cursor.getColumnIndex(CATEGORY_NAME)));
categoryModel.setCategoryType(cursor.getString(cursor.getColumnIndex(CATEGORY_TYPE)));
Categories.add(categoryModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return Categories;
}
Any Type of Help, Suggestion is much Appreciated.....Thanks in advance
Below is Screenshot after adding First Item.
First Item Inserted but not shown in RecycleView
My LogCat Screenshot is below.
Logcat Screenshot
change your onCreate in this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = myDb.getCategoryByType(CategoryType);
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
}
and now you can use adapter.notifyDataSetChanged(); without recreation of adapter and set them to RecyclerView
if you make in setPositiveButton allCategory = myDb.getCategoryByType(CategoryType); then your reference to allCategory is lost.
you need instead
allCategory.clear();
allCategory.addAll(myDb.getCategoryByType(CategoryType));
Change your Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = new ArrayList<>();
adapter = new CategoryAdapter(allCategory);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
recyclerCategory.setAdapter(adapter);
allCategory = myDb.getCategoryByType(CategoryType);
adapter.notifyDataSetChange();
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
}
and inside setPositiveButton, replace
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
with
adapter.notifyDataSetChanged();
Also replace
allCategory = myDb.getCategoryByType(CategoryType);
with
allCategory.addAll(myDb.getCategoryByType(CategoryType));
And try to run your program again.
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.