Only one column of data inserted in the sqlite database - android

So I'm using multiple radiogroup and an EditText to insert the data into the database. The problem is that only one column of data is inserted and it is always the the collection_time column.
This is the coding to insert the data:
BtnNext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SelectPrintingDetails.this, Summary.class);
int selectedId = rgCP.getCheckedRadioButtonId();
if(selectedId != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId);
String rbCP = selectedRadioButton.getText().toString();
Boolean insertPD = db.insertcolor(rbCP);
if(insertPD == true)
{
intent.putExtra("Color", rbCP);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Radiobutton is not selected",Toast.LENGTH_SHORT).show();
}
int selectedId1 = rgFP.getCheckedRadioButtonId();
if(selectedId1 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId1);
String rbFP = selectedRadioButton.getText().toString();
Boolean insertPD1 = db.insertflip(rbFP);
if(insertPD1 == true)
{
intent.putExtra("Flip", rbFP);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Radiobutton is not selected",Toast.LENGTH_SHORT).show();
}
int selectedId2 = rgPC.getCheckedRadioButtonId();
if(selectedId1 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId2);
String rbPC = selectedRadioButton.getText().toString();
Boolean insertPD2 = db.insertpc(rbPC);
if(insertPD2 == true)
{
intent.putExtra("Plastic", rbPC);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Radiobutton is not selected",Toast.LENGTH_SHORT).show();
}
int selectedId3 = rgBind.getCheckedRadioButtonId();
if(selectedId1 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId3);
String rbBind = selectedRadioButton.getText().toString();
Boolean insertPD3 = db.insertbind(rbBind);
if(insertPD3 == true)
{
intent.putExtra("Bind", rbBind);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Radiobutton is not selected",Toast.LENGTH_SHORT).show();
}
String timecollect = etCT.getText().toString();
Boolean insertPD4 = db.insertct(timecollect);
if(insertPD4 == true)
{
intent.putExtra("Collect", timecollect);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
startActivity(intent);
}
});
This is the databasehelper :
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "hdatabase1.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table printingdetails (color text, binding text, collection_time text, flipped_page text, plastic_cover text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if exists printingdetails");
}
public boolean insertcolor(String color)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("color", color);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
public boolean insertflip(String flipped_page)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("flipped_page", flipped_page);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
public boolean insertpc(String plastic_cover)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("plastic_cover", plastic_cover);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
public boolean insertbind(String binding)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("binding", binding);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
public boolean insertct (String collection_time)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("collection_time", collection_time);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
I hope you guys guide me how to insert all the data in every column. I'm still new and I had already refer to several related post here and none of it really helping

Currently you seem to be inserting the value of each column separately. This means instead of a single row, you end up with multiple rows where only one column has a value and the rest are empty.
In order to fix this, you need a single method which is something like this:
public boolean insertRow(String color, String binding, String time, String flipped_page, String plastic_cover) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("color", color);
contentValues.put("binding", binding);
contentValues.put("collection_time", time);
contentValues.put("flipped_page", flipped_page);
contentValues.put("plastic_cover", plastic_cover);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
Each individual insert command should be removed. Now, your onClick method will have to retrieve all the selected items and then call this insert method. Handling of unselected radio groups will depend on your application. In the sample below, I am simply interrupting the method, thus cancelling the submission. If some radio groups are optional, then you can set the corresponding strings to empty ("") and proceed with the method rather than cancelling the submission by returning.
public void onClick(View v) {
Intent intent = new Intent(SelectPrintingDetails.this, Summary.class);
String color, binding, time, page, cover;
int selectedId = rgCP.getCheckedRadioButtonId();
if(selectedId != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId);
color = selectedRadioButton.getText().toString();
}
else
{
Toast.makeText(getApplicationContext(), "Color is not selected",Toast.LENGTH_SHORT).show();
return; // this prevents the rest of the code from executing
}
int selectedId1 = rgFP.getCheckedRadioButtonId();
if(selectedId1 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId1);
page = selectedRadioButton.getText().toString();
}
else
{
Toast.makeText(getApplicationContext(), "FlipPage is not selected",Toast.LENGTH_SHORT).show();
return;
}
int selectedId2 = rgPC.getCheckedRadioButtonId();
if(selectedId2 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId2);
cover = selectedRadioButton.getText().toString();
}
else
{
Toast.makeText(getApplicationContext(), "Plastic Cover is not selected",Toast.LENGTH_SHORT).show();
return;
}
int selectedId3 = rgBind.getCheckedRadioButtonId();
if(selectedId3 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId3);
binding = selectedRadioButton.getText().toString();
}
else
{
Toast.makeText(getApplicationContext(), "Binding is not selected",Toast.LENGTH_SHORT).show();
return;
}
time = etCT.getText().toString();
// since all attributed have been read, now we call insert
// you can read the returned boolean to determine if the insertion was successful
db.insertRow(color, binding, time, page, cover);
// Also add all of them as intent extras
intent.putExtra("Color", color);
intent.putExtra("Bind", binding);
intent.putExtra("Collect", time);
intent.putExtra("Flip", page);
intent.putExtra("Plastic", cover);
startActivity(intent);
}
I hope this helps you understand where you were going wrong, and how you can take this forward.

Related

Update textview data sqlite Android

I have a textview that gets data from sqlite database but when I delete a row,or change it ,I also want to change what the textview has,the data the textview contains is basically the sum of all rows specific column,so how can I update the textview when updating sqlite data?
here is my main code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tinyDB = new TinyDB(getApplicationContext());
listView = findViewById(R.id.listt);
pharmacynme = findViewById(R.id.pharmacynme);
constraintLayout = findViewById(R.id.thelayout);
mBottomSheetDialog2 = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
inflater2 = (LayoutInflater) LoggedIn.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mBottomSheetDialog = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
content = inflater2.inflate(R.layout.activity_main2, null);
content2 = inflater2.inflate(R.layout.smalldialog, null);
total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
pharmacydescrr = findViewById(R.id.pharmacydiscribtion);
String nme = getIntent().getStringExtra("pharmacy_name");
String diskr = getIntent().getStringExtra("pharmacy_disk");
pharmacydescrr.setText(diskr);
pharmacynme.setText(nme);
//Listview Declaration
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListItems>();// Connection Class Initialization
etSearch = findViewById(R.id.etsearch);
etSearch.setSingleLine(true);
chat = findViewById(R.id.chat);
mDatabaseHelper = new DatabaseHelper(this);
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
System.out.println("IDKSDKASDJKAS"+mDatabaseHelper.ifExists());
if (mDatabaseHelper.ifExists()){
mBottomSheetDialog2.show();
total.setText(mDatabaseHelper.getPriceSum());
}else {
}
chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameid = getIntent().getStringExtra("nameid");
Intent intent = new Intent(LoggedIn.this,ChatActivity.class);
intent.putExtra("nameid",nameid);
startActivity(intent);
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
// myAppAdapter.filter(text);
}
});
SyncData orderData = new SyncData();
orderData.execute("");
}
public void AddData(String newEntry,String price,String amount){
boolean insertData = mDatabaseHelper.addData(newEntry,price,amount);
if (insertData){
toastMessage("Data Successfully inserted!");
}else {
toastMessage("Al anta 4abebto da ya youssef >:(");
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(LoggedIn.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String nme = getIntent().getStringExtra("pharmacy_name");
System.out.println(nme);
String query = "Select StoreArabicName,StoreEnglishName,StoreSpecialty,StoreCountry,StoreLatitude,StoreLongitude,Store_description,ProductData.ProductArabicName,ProductData.ProductImage,ProductData.ProductEnglishName,ProductData.ProductDescription,ProductData.ProductPrice FROM StoresData INNER JOIN ProductData ON StoresData.StoreID = ProductData.StoreID WHERE StoreEnglishName = '"+nme+"'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("ProductEnglishName"), rs.getString("ProductDescription"), rs.getString("ProductPrice"),rs.getString("ProductImage")));
System.out.println(rs.getString("ProductImage"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg!=null){
Toast.makeText(LoggedIn.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, LoggedIn.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter//has a class viewholder which holds
{
private ArrayList<ClassListItems> mOriginalValues; // Original Values
private ArrayList<ClassListItems> mDisplayedValues;
public class ViewHolder {
TextView textName;
TextView textData;
TextView textImage;
ImageView producticon;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.sdadprice);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.setContentView(content);
total.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoggedIn.this,Listitemsbought.class);
startActivity(intent);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
final Float allitemscount = Float.parseFloat(parkingList.get(position).getImage());
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
AddData(parkingList.get(position).getProname(),String.valueOf(last),String.valueOf(counter));
total.setText(mDatabaseHelper.getPriceSum());
mBottomSheetDialog2.show();
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
// if (tinyDB.getString("selecteditem").equals("English")){
// Toast.makeText(LoggedIn.this,"Sorry this ability isn't here yet",Toast.LENGTH_LONG).show();
// }else {
// Toast.makeText(LoggedIn.this,"عفوا هذه الخاصية ليست متوفرة حاليا",Toast.LENGTH_LONG).show();
// }
}
});
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
itemArrayList.clear();
if (charText.length() == 0) {
itemArrayList.addAll(arraylist);
} else {
for (ClassListItems st : arraylist) {
if (st.getProname().toLowerCase(Locale.getDefault()).contains(charText)) {
itemArrayList.add(st);
}
}
}
notifyDataSetChanged();
}
}
private Float parseFloat(String s){
if(s == null || s.isEmpty())
return 0.0f;
else
return Float.parseFloat(s);
}
And here is my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "DatabaseHelper";
private static final String NAME = "Name";
private static final String PRICE = "Price";
private static final String AMOUNT = "Amount";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null , 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " ("+PRICE+" TEXT, "+ NAME + " TEXT,"+ AMOUNT +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String Price,String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PRICE,Price);
contentValues.put(NAME, item);
contentValues.put(AMOUNT, amount);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long insert = db.insert(TABLE_NAME,null,contentValues);
if (insert == -1){
return false;
}else {
return true;
}
}
public Cursor getDataOfTable(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT Name,Amount FROM " + TABLE_NAME ;
Cursor data = db.rawQuery(query, null);
return data;
}
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor price = db.rawQuery(query, null);
String result = "" + price.getString(0);
price.close();
db.close();
return result;
}
public boolean ifExists()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String checkQuery = "SELECT * FROM " + TABLE_NAME + " LIMIT 1";
cursor= db.rawQuery(checkQuery,null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
public void delete(String nameofrow) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+TABLE_NAME+" where "+NAME+"='"+nameofrow+"'");
}
}
Any help?!
The method getPriceSum() should return the sum and not a Cursor:
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(query, null);
String result = "";
if (c.moveToFirst()) result = "" + c.getString(0);
c.close();
db.close();
return result;
}
I don't think that you need the if block:
if (mDatabaseHelper.ifExists()) {
.......................
}
All you need to do is:
total.setText(mDatabaseHelper.getPriceSum());

Display each row from Database on a new line in a TextView

I have created a database that stores all the correct values. I need for each row stored in the database to be displayed on a new line in one TextView.
Current Output
Current Output
After adding to database it adds on and updates current values instead of going to new line.
Required Output
Required Output
Each row from the database displayed on a new line in TextView
Insert data to database
public static void InsertOrUpdateRatingPoints(Context context, int point, SelfToSelfActivity.Rating activity) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE,};
String where = TYPE + " = ?";
String[] whereArgs = {String.valueOf(activity)};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, where, whereArgs, null, null, orderBy);
boolean sameDay = false;
Date currentTime = Calendar.getInstance().getTime();
int StoredPoint = 0;
long lastStored = 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
lastStored = cursor.getLong(cursor.getColumnIndex(TIME));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sameDay = (sdf.format(new Date(lastStored))).equals(sdf.format(currentTime));
if (sameDay) StoredPoint = cursor.getInt(cursor.getColumnIndex(POINT));
}
cursor.close();
}
ContentValues cv = new ContentValues();
cv.put(POINT, point + StoredPoint);
if (sameDay) {
db.update(TABLE_NAME, cv, TIME + " = ?", new String[]{String.valueOf(lastStored)});
} else {
cv.put(TYPE, activity.ordinal());
cv.put(TIME, currentTime.getTime());
cv.put(POINT, point);
db.insert(TABLE_NAME, null, cv);
}
}
Execute
public void execute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
do {
WorkoutDetails temp = getWorkoutFromCursor(c);
if (details == null) {
details = temp;
continue;
}
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
} while (c.moveToNext());
if (details != null) mWorkoutDetailsList.add(details);
if (DBG)
Log.d(LOG_TAG, "AsyncTask: list size " + mWorkoutDetailsList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mWorkoutsAdapter.updateList(mWorkoutDetailsList);
//AVG_THIRTY.setText(String.valueOf(EmotionListAdapter.thirtyday));
//Today_Score.setText(String.valueOf(EmotionListAdapter.day));
}
});
}
c.close();
}
}
});
}
Display Data
#Override
public void onBindViewHolder(RatingListViewHolder holder, int position)
{
WorkoutDetails details = mWorkoutsList.get(position);
holder.textSTS.setText(String.valueOf(totalSTS));
holder.textLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.LOSS)));
holder.textRateLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.RATELOSS)));
}
I assume you want to display every item of ArrayList in separate lines.
Try this, hope this help.
TextView conciergeServicesTv = (TextView) findViewById(R.id.activity_get_quote_final_concierge_services_tv);
if (arrayListConciergeServices.size() != 0) { //ArrayList you are receiving\\
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayListConciergeServices.size(); i++) {
if (i == arrayListConciergeServices.size() - 1) {
stringBuilder.append(arrayListConciergeServices.get(i));
} else {
stringBuilder.append(arrayListConciergeServices.get(i)).append("\n");
}
}
conciergeServicesTv.setText(stringBuilder);
} else {
conciergeServicesTv.setText("No concierge services selected");
}

Android - adding validation to input fields

I am making an Android app that uses a sqlite database to store the app data, an activity class to edit / insert data, a DbHelper to manage the database creation and version, and a content provider which manages access to the database.
I have managed to get data to be queried, inserted, deleted and edited from the database. However, I'm not too sure on how to add visual feedback to the user. I've tried adding a Toast in place where I have put an IllegalArgumentException but the app will simply add the content to the database.
If I omit the Name, the app will trigger the defined IllegalArgumentException and then crash the application.
This is a snippet for the insert method in the content provider
#Override
public Uri insert(Uri uri, ContentValues contentValues) {
final int match = sUriMatcher.match(uri);
switch (match) {
case PATIENT:
return insertPatient(uri, contentValues);
default:
throw new IllegalArgumentException("Insertion is not supported for " + uri);
}
}
/**
* Insert a patient into the database with the given content values.
*/
private Uri insertPatient(Uri uri, ContentValues values) {
String name = values.getAsString(PatientEntry.COLUMN_PATIENT_NAME);
if (name == null || name.length()==0) {
//Toast.makeText(getContext(), "Patient requires a name", Toast.LENGTH_SHORT).show();
throw new IllegalArgumentException("Patient requires a name");
}
Integer weight = values.getAsInteger(PatientEntry.COLUMN_PATIENT_WEIGHT);
if (weight != null && weight < 0) {
throw new IllegalArgumentException("Patient requires valid weight");
}
SQLiteDatabase database = mDbHelper.getWritableDatabase();
long id = database.insert(PatientEntry.TABLE_NAME, null, values);
if (id == -1) {
Log.e(LOG_TAG, "Failed to insert row for " + uri);
return null;
}
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
}
This is a snippet from the activity file
private void savePatient() {
String nameString = mNameEditText.getText().toString().trim();
String weightString = mWeightEditText.getText().toString().trim();
if (mCurrentPatientUri == null &&
TextUtils.isEmpty(nameString) && TextUtils.isEmpty(weightString) {
Toast.makeText(this, "Data was not saved", Toast.LENGTH_SHORT).show();
return;
}
ContentValues values = new ContentValues();
values.put(PatientEntry.COLUMN_PATIENT_NAME, nameString);
int weight = 0;
if (!TextUtils.isEmpty(weightString)) {
weight = Integer.parseInt(weightString);
}
values.put(PatientEntry.COLUMN_PATIENT_WEIGHT, weight);
// Determine if this is a new or existing Patient by checking if mCurrentPatientUri is null or not
if (mCurrentPatientUri == null) {
// This is a NEW patient
Uri newUri = getContentResolver().insert(PatientEntry.CONTENT_URI, values);
if (newUri == null) {
Toast.makeText(this, getString(R.string.editor_insert_patient_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_insert_patient_successful),
Toast.LENGTH_SHORT).show();
}
} else {
// Otherwise this is an EXISTING patient
int rowsAffected = getContentResolver().update(mCurrentPatientUri, values, null, null);
if (rowsAffected == 0) {
Toast.makeText(this, getString(R.string.editor_update_patient_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_update_patient_successful),
Toast.LENGTH_SHORT).show();
}
}
}
Could someone kindly lend a hand?
.................................................................
EDIT 1:
This is the menu in the activity which calls savePatient:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
case R.id.action_save:
savePatient();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!mPatientHasChanged) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
// Otherwise if there are unsaved changes, setup a dialog to warn the user.
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
}
};
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
For visual feedback validations are to be done as early as possible.
For example before you call save patient on some user action just call validatePatient() which if fails save will not be called.
For Visual feedback you can have error texts below your fields that will become visible only if validation related to that field fails.

Doesn't wait Timer for user to click on answers in Android Quiz Game, and quickly run

I have navigation drawer with menu nav items. Now I define for one item, for when clicking on it, open a new activity.Inside this activity, I design layout for start flag game quiz.When clicking on play game Button, the game started so fast without waiting for click user, and finish. Inside "PlayGame" layout, I define one imageView for flags and 4 buttons for answers. Flags name and answers come from the External database. When I debug the app, countDownTimer realise null amount, Everything is correct, Just Timer doesn't wait for use, and playing Quiz is so quickly.
this is my database.
WorldCountryDatabase
public class WorldCountryDatabase extends SQLiteOpenHelper {
private static final String TAG = "databaseHelper";
private static final String DB_NAME = "worldCountries.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "country";
private static String DB_PATH = "";
private Context mContext;
private SQLiteDatabase database;
public WorldCountryDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
DB_PATH = context.getDatabasePath(DB_NAME).getPath();
File file = new File(DB_PATH + "worldCountries.db");
if (file.exists())
openDataBase();
this.mContext = context;
}
public void createDatabase() {
boolean dbExist = checkDatabase();
if (dbExist) {
Log.d("MIN1", "Database already Exist");
} else {
this.getReadableDatabase();
}
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
Log.i("MIN2", e.getMessage());
}
}
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
e.printStackTrace();
Log.d("MIN3", e.getMessage());
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
public synchronized void close() {
if (database != null) {
database.close();
SQLiteDatabase.releaseMemory();
}
super.close();
}
private void copyDataBase() throws IOException {
try {
InputStream in = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream out = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
out.close();
in.close();
Log.d("MIN4", "Database copy");
} catch (SQLiteException e) {
Log.d("MIN5", e.getMessage());
}
}
public Cursor QueryData(String query) {
return database.rawQuery(query, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("MIN6", "onCreate");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion +
"Which will destroy all oldest data");
if (newVersion > oldVersion) {
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void openDataBase() {
String myPath = DB_PATH + DB_NAME;
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
Log.d("MIN7", "Opened database");
}
// CRUD Table
public List<Questions> getAllQuestions() {
List<Questions> questionsList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null);
if (c == null) return null;
c.moveToFirst();
do {
int Id = c.getInt(c.getColumnIndex("id"));
String Image = c.getString(c.getColumnIndex("Image"));
String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionsList.add(question);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
database.close();
return questionsList;
}
// Insert Score to Ranking table.
public void insertScore(double score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put("Score", score);
db.insert("Ranking", null, content);
}
// Get score and sort Ranking.
public List<Ranking> getRanking() {
List<Ranking> rankingList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Score DESC;", null);
if (c == null) return null;
c.moveToFirst();
do {
int ID = c.getInt(c.getColumnIndex("id"));
int Score = c.getInt(c.getColumnIndex("Score"));
Ranking ranking = new Ranking(ID, Score);
rankingList.add(ranking);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
db.close();
return rankingList;
}
public int getPlayCount(int level)
{
int result = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c;
try{
c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level="+level+";",null);
if(c == null) return 0;
c.moveToNext();
do{
result = c.getInt(c.getColumnIndex("PlayCount"));
}while(c.moveToNext());
c.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
return result;
}
public void updatePlayCount(int level,int playCount)
{
String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d",playCount,level);
database.execSQL(query);
}
this is my ChoicGame class.
ChoiceGame
public class ChoiceGame extends AppCompatActivity {
TextView modeText;
SeekBar seekBarMode;
Button playGame, scoreGame;
WorldCountryDatabase worldCountryDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_flag);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
modeText = (TextView) findViewById(R.id.modeText);
seekBarMode = (SeekBar) findViewById(R.id.seekBarMode);
playGame = (Button) findViewById(R.id.playGame);
scoreGame = (Button) findViewById(R.id.scoreGame);
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
} catch (Exception e) {
e.printStackTrace();
}
//Event
seekBarMode.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == 0)
modeText.setText(Common.MODE.EASY.toString());
else if (progress == 1)
modeText.setText(Common.MODE.MEDIUM.toString());
else if (progress == 2)
modeText.setText(Common.MODE.HARD.toString());
else if (progress == 3)
modeText.setText(Common.MODE.HARDEST.toString());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
playGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayGameCountry.class);
intent.putExtra("Mode", getPlayMode()); // Send Mode to Playing page
startActivity(intent);
finish();
}
});
scoreGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ScoreGame.class);
startActivity(intent);
finish();
}
});
}
private String getPlayMode() {
if (seekBarMode.getProgress() == 0)
return Common.MODE.EASY.toString();
else if (seekBarMode.getProgress() == 1)
return Common.MODE.MEDIUM.toString();
else if (seekBarMode.getProgress() == 2)
return Common.MODE.HARD.toString();
else
return Common.MODE.HARDEST.toString();
}
}
and at last this is my PlayingGame class.
PlayingGmae
public class PlayGameCountry extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 1; // 1 second
final static long TIMEOUT = 7; // 1 second
CountDownTimer countDownTimer;
int progressValue = 0;
int score = 0, index = 0, thisQuestion = 0, correctAnswer, totalQuestions;
List<Questions> questionsList = new ArrayList<>();
String mode;
ProgressBar progressBar;
ImageView flagCountry;
TextView scoreText, numberQuestion;
Button answerA, answerB, answerC, answerD;
WorldCountryDatabase worldCountryDatabase;
ChoiceGame choiceGame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game_country);
// Get data from ChoiceGame
Bundle bundle = getIntent().getExtras();
if (bundle != null)
mode = bundle.getString("Mode");
worldCountryDatabase = new WorldCountryDatabase(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
flagCountry = (ImageView) findViewById(R.id.flagQuiz);
scoreText = (TextView) findViewById(R.id.scoreText);
numberQuestion = (TextView) findViewById(R.id.trueAnswer);
answerA = (Button) findViewById(R.id.firstAnswer);
answerB = (Button) findViewById(R.id.secondAnswer);
answerC = (Button) findViewById(R.id.thirthAnswer);
answerD = (Button) findViewById(R.id.forthAnswer);
progressBar = (ProgressBar) findViewById(R.id.progressUser);
answerA.setOnClickListener(this);
answerB.setOnClickListener(this);
answerC.setOnClickListener(this);
answerD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionsList = this.getQuestionMode(mode);
assert questionsList != null;
totalQuestions = questionsList.size();
countDownTimer = new CountDownTimer(INTERVAL, TIMEOUT) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
countDownTimer.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestions) {
thisQuestion++;
numberQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestions));
progressBar.setProgress(0);
progressValue = 0;
int ImageId = this.getResources().getIdentifier(questionsList.get(index).getImage().toLowerCase(), "drawable", getPackageName());
flagCountry.setBackgroundResource(ImageId);
answerA.setText(questionsList.get(index).getAnswerA());
answerB.setText(questionsList.get(index).getAnswerB());
answerC.setText(questionsList.get(index).getAnswerC());
answerD.setText(questionsList.get(index).getAnswerD());
countDownTimer.start();
} else {
Intent scoreIntent = new Intent(getApplicationContext(), Done.class);
Bundle bundle = new Bundle();
bundle.putInt("SCORE", score);
bundle.putInt("TOTAL", totalQuestions);
bundle.putInt("CORRECT", correctAnswer);
scoreIntent.putExtras(bundle);
startActivity(scoreIntent);
finish();
}
}
#Override
public void onClick(View v) {
countDownTimer.cancel();
if (index < totalQuestions) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionsList.get(index).getCorrectAnswer()))
{
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else
showQuestion(++index); // If choose right , just go to next question
scoreText.setText(String.format("%d", score));
}
}
private List<Questions> getQuestionMode(String mode) {
List<Questions> questionList = new ArrayList<>();
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
} catch (Exception e) {
e.printStackTrace();
}
int limit = 0;
if (mode.equals(Common.MODE.EASY.toString()))
limit = 30;
else if (mode.equals(Common.MODE.MEDIUM.toString()))
limit = 50;
else if (mode.equals(Common.MODE.HARD.toString()))
limit = 100;
else if (mode.equals(Common.MODE.HARDEST.toString()))
limit = 200;
try {
Cursor cursor = worldCountryDatabase.QueryData(String.format("SELECT * FROM country ORDER BY Random() LIMIT %d", limit));
if (cursor == null) return null;
if (cursor.moveToNext()) {
do {
int Id = cursor.getInt(cursor.getColumnIndex("id"));
String Image = cursor.getString(cursor.getColumnIndex("Image"));
String AnswerA = cursor.getString(cursor.getColumnIndex("AnswerA"));
String AnswerB = cursor.getString(cursor.getColumnIndex("AnswerB"));
String AnswerC = cursor.getString(cursor.getColumnIndex("AnswerC"));
String AnswerD = cursor.getString(cursor.getColumnIndex("AnswerD"));
String CorrectAnswer = cursor.getString(cursor.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionList.add(question);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return questionList;
}
}
At the first, I defining "getQuestionMode" method inside WorldCountryDatabase, but the app doesn't go to the PlayingCountryGame layout and open ScoreGame class. After I define "getQuestionMode" method inside PlayingCountryGame class. I hope to tell clear my problem.
Please help me, good friends. Thanks to all of you.
I think that you problem is the constructor and values.
https://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long, long)
The constructor need the time on milliseconds and not seconds. Y ou need convert 1 second to 1000 ms.
final static long INTERVAL = 1000; // 1 second -> 1000 milliseconds
final static long TIMEOUT = 7000; // 7 seconds -> 7000 milliseconds
And the order of the params.
If you want wait 7 second the constructor is:
countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL){ ... }

Listview gets popuplated from the database everytime I start the activity

I am fetching some json data into an EventApp and I am trying to store in SQLite database some of the events. I am showing the events in another activity, not the main one and whenever I go back from that activity to the main one and the I go back to the activity with the listview, the data gets duplicated every time. SO if I click to go to that activity 10 time, my data gets 10 times in the listview and in the database as well. How can I fix this?
SQLiteDatabase db = getWritableDatabase();
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add new row to the database
public void addEvent(Event ev){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TITLE, ev.getTitle());
contentValues.put(DatabaseHelper.START_DATE, ev.getStartTime());
contentValues.put(DatabaseHelper.END_DATE, ev.getEndTime());
contentValues.put(DatabaseHelper.IMAGE_URL, ev.getImageURL());
contentValues.put(DatabaseHelper.URL, ev.getUrl());
contentValues.put(DatabaseHelper.SUBTITLE, ev.getSubtitle());
contentValues.put(DatabaseHelper.DESCRIPTION, ev.getDescription());
db.insert(TABLE_NAME, null, contentValues);
//db.close();
}
//Delete event from database
public void deleteEvent(String eventTitle){
db.execSQL("DELETE FROM " + TABLE_NAME + "WHERE " + TITLE + "=\"" + eventTitle + "\";" );
}
public int deleteEvents() {
return db.delete(DatabaseHelper.TABLE_NAME, null, null);
}
//Print the database as string
public String databaseToString(){
String dbString="";
//points to a location in results
Cursor c = getEvents();
while (c.moveToNext()){
if(c.getString(c.getColumnIndex("Title")) != null){
dbString += c.getString(c.getColumnIndex("Title"));
dbString += "\n";
}
}
//db.close();
return dbString;
}
public Cursor getEvents(){
return db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
}
}
This is the activity where I show the data from the database
public class StoredEventsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stored_events);
ListView listView = (ListView) findViewById(R.id.lv_stored_events);
Intent intent = getIntent();
ArrayList<Event> events = new ArrayList<Event>();
events = (ArrayList<Event>) intent.getSerializableExtra("storedEvents");
EventAdapter adapter = new EventAdapter(this, R.layout.list_view_row, R.id.stored, events );
listView.setAdapter(adapter);
}
}
Here is the method that returns the stored events
public static ArrayList<Event> returnStoredEvents(){
long id = -1;
//getStoredEvents();
Cursor c = eventsDB.getEvents();
while (c.moveToNext()){
id = c.getInt(c.getColumnIndex(eventsDB.ID));
String title = c.getString(c.getColumnIndex(eventsDB.TITLE));
String start = c.getString(c.getColumnIndex(eventsDB.START_DATE));
String end = c.getString(c.getColumnIndex(eventsDB.END_DATE));
organizeEvents.add(new Event(title, start, end, true));
}
c.close();
Log.d("DATABASE", organizeEvents.toString());
return organizeEvents;
}
Here is where I actually add some of the events:
private void readEvents(String str){
Event ev = null;
try {
JSONObject geoJSON = new JSONObject(str);
JSONArray jsonEvents = geoJSON.getJSONArray("events");
for (int i = 0; i < jsonEvents.length(); i++) {
JSONObject event = jsonEvents.getJSONObject(i);
JSONArray timeJsonEvent = event.getJSONArray("datelist");
JSONObject time = timeJsonEvent.getJSONObject(0);
title = event.getString("title_english");
Date date = new Date(time.getLong("start"));
startDate = dateFormat.format(date);
date = new Date(time.getLong("end"));
endDate = dateFormat.format(date);
imageURL = event.getString("picture_name");
url = event.getString("url");
subtitle = event.getString("subtitle_english");
description = event.getString("description_english");
if (title.charAt(0) == 'T') {
ev = new Event(title, startDate, endDate, true);
eventsDB.addEvent(ev);
}else {
ev = new Event(title, startDate, endDate, false);
}
// Process a newly found event
final Event finalEv = ev;
handler.post(new Runnable() {
public void run() {
addNewEvent(finalEv);
}
});
}
}catch (Exception e) {
Log.d(null, e.getMessage());
}
}
And here is my main:
public class MainActivity extends AppCompatActivity{
DatabaseHelper eventsDB;
ListFragment listFragment;
SimpleCursorAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventsDB = new DatabaseHelper(this);
//storedEvents.addAll(EventsListFragment.returnStoredEvents());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Sort by name")){
Toast.makeText(this, "ITEM 2 CLICKED", Toast.LENGTH_LONG).show();
EventsListFragment.sort(-1);
}else if (item.getTitle().equals("Sort by date")) {
EventsListFragment.sort(1);
}else if (item.getTitle().equals("Stored events")){
showSavedEvents();
Toast.makeText(this, "ITEM 3 CLICKED", Toast.LENGTH_LONG).show();
}
return true;
}
public void showSavedEvents(){
intent = new Intent(this, StoredEventsActivity.class);
intent.putExtra("storedEvents", EventsListFragment.returnStoredEvents());
startActivity(intent);
}
}

Categories

Resources