I'm making an android app which displays the list of male and female from database with a user specified age. I almost managed to write the code
the below is my code as far as I made
public class UserList{
private ArrayList<String> maleList;
private ArrayList<String> femaleList;} //getter setter for Arraylists
// method to get data
public UserList getUserLists (Context context, String age){
public UserList userList = new UserList();
public ArrayList<String> maleList = new ArrayList<String>();
public ArrayList<String> femaleList = new ArrayList<String>();
db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery(
"select * from USER_INFO where AGE = ?", new String[]{age});
if(cursor != null)
{
if(cursor.moveToFirst())
{
do{
String user_id = cursor.getString(cursor.getColumnIndex("USER_NAME"));
String gender = cursor.getString(cursor.getColumnIndex("GENDER"));
if(gender.equalsIgnorease("MALE"))
maleList.add(user_id);
else
femaleList.add(user_id);
}while(cursor.moveToNext());
cursor.close();
}
}
userList.setMaleList(maleList);
userList.setFemaleList(femaleList);
return userList;
}
But now I need to call this function for getting data from database to cursor in certain intervals like after every 5 minutes. Please help me in doing that the age variale used is age.
You should implement a broadcast receiver and setup an alarm scheduled at regular interval.
There is a simple tutorial on how to do that here : alarm-manager-example
Related
I have a table that store two variables Days and percent’s. I want to assign them to a specific variable. From the Database Helper class, I’m getting the last 7 entries:
//----------------Graping the last seven elements ----------------------------------//
public ArrayList<StatsitcsHelper> GetWeaklyPrograss() {
SQLiteDatabase db = this.getReadableDatabase ();
Cursor cursor = db.rawQuery ("select * from " + TABLE_PROGGRES, null);
ArrayList<StatsitcsHelper> datas = new ArrayList<>();
if (cursor != null) {
cursor.moveToFirst ();
for (int i = cursor.getCount () - 7 ; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
StatsitcsHelper data = new StatsitcsHelper();
data.WeakleyDate= cursor.getString(cursor.getColumnIndex(COL_P_Date));
data.WeakleyPercent = cursor.getInt (cursor.getColumnIndex(COL_P_Percentage));
datas.add(data);
cursor.moveToNext ();
}
cursor.close ();
}
return datas;
}
I want to build if statement that will say if day is Saturday then assign Saturday Percent Variable is Statistics Class to the percent associated from the database. Same goes for Sunday ….etc.
Inside the Statistics Class:
public void WeaklyStatstics(){
int saturday = 0,
sunday = 0,
monday = 0,
tuesday = 0,
wednsday = 0,
thersday = 0,
friday = 0;
StatsitcsHelper statsitcsHelper = new StatsitcsHelper ();
DatabaseHelper databaseHelper = new DatabaseHelper (getActivity ());
//---------------------TO DO----------------------------------------//
}}
I don’t know how to analysis each item from the list in the database to another class.
Here is the Insertion of the Table:
// ----------------Proggres Table ------------------------------------//
public boolean insertPrograss(String Date, Integer percentage) {
SQLiteDatabase db = this.getWritableDatabase ();
ContentValues contentValues = new ContentValues ();
contentValues.put (COL_P_Date, Date);
contentValues.put (COL_P_Percentage, percentage);
long result = db.insert (TABLE_PROGGRES, null, contentValues);
db.close ();
return result != -1;
}
the method is called by scheduler that will store the date into just day by using date formate, and the output will be Monday, 87.
i want to write a method to get the last 7 inputs through GetWeaklyPrograss method. and assign it to the variables something like this
if(statsitcsHelper.WeakleyDate.equals ("monday")){
saturday = statsitcsHelper.WeakleyPercent;
}
and here is the statsitcsHelper:
public class StatsitcsHelper {
//-------------- Weakly Progress -----------------------/
public String WeakleyDate;
public int WeakleyPercent;
}
can you try this logic ,
public void WeaklyStatstics(){
int saturday = 0,
sunday = 0,
monday = 0,
tuesday = 0,
wednsday = 0,
thersday = 0,
friday = 0;
//StatsitcsHelper statsitcsHelper = new StatsitcsHelper ();
DatabaseHelper databaseHelper = new DatabaseHelper (getActivity());
ArrayList<StatsitcsHelper> statsitcsHelperList = databaseHelper.GetWeaklyPrograss();
for (StatsitcsHelper statsitcsHelper : statsitcsHelperList)
{
if(statsitcsHelper.WeakleyDate.equals("Monday")){
monday = statsitcsHelper.WeakleyPercent;
}else if (statsitcsHelper.WeakleyDate.equals("Tuesday")){
tuesday = statsitcsHelper.WeakleyPercent;
}
//todo and write for other days too
}
// In here you can use all valid data
}
I am not sure I understand what the problem is.
However to check the day of week, you can get some ideas from this:
check if date() is monday? java
On a side note:
Your cursor contains all of the data in the table! It is usually better to get the results you want (last seven elements) on your cursor.
Limit your DB query, down to the interesting data. Instead of taking all data from the DB (select * from), you should specialize your query.
Look for SQL expressions ORDER BY, ASC, DESC, LIMIT, and you will get there.
I developed this app for my senior project and used SQLite and stored everything locally. I want to convert everything to Firebase now but there aren't that many tutorials out there, at least for what I'm trying to do. My question is how would I go about converting a query like the below to a Firebase database query?
public ArrayList<String> getAllBeautyItems() {
itemsList.clear();
dbHelper.getReadableDatabase();
ArrayList<String> itemNames = new ArrayList<>();
String[] tableColumns = new String[]{
Constants.ITEM_NAME, Constants.CATEGORY
};
String whereClause = Constants.CATEGORY + "=?";
String[] whereArgs = new String[]{
"beauty"
};
Cursor result = db.query(Constants.ITEMS_TABLE_NAME, tableColumns, whereClause, whereArgs,
null, null, null, null);
if (result.moveToFirst()) {
do {
itemNames.add(result.getString(result.getColumnIndex(Constants.ITEM_NAME)));
} while (result.moveToNext());
}
result.close();
return itemNames;
}
and then in a fragment I'm calling a setName, so how do I get the result of that query and apply it like in the below?
private ArrayList<Items> refreshData() {
dbItems.clear();
final ArrayList<String> itemNames = adapter.getAllBeautyItems();
ArrayList<String> itemImages = adapter.getAllBeautyImages();
ArrayList<Integer> itemPrices = adapter.getAllBeautyPrices();
ArrayList<String> itemDescriptions = adapter.getAllBeautyDescriptions();
ArrayList<String> itemLocations = adapter.getAllBeautyLocations();
ArrayList<String> itemLats = adapter.getAllBeautyLats();
int totalItems = adapter.getTotalBeautyItems();
String formattedItems = Utils.formatNumber(totalItems);
totalItemsText.setText("Total Items: " + formattedItems);
ArrayList<Items> items = new ArrayList<>();
for (int i = 0; i < itemNames.size(); i++) {
Items item = new Items();
item.setItemName(itemNames.get(i));
item.setItemImage(itemImages.get(i));
item.setItemPrice(itemPrices.get(i));
item.setItemDescription(itemDescriptions.get(i));
item.setItemLocation(itemLocations.get(i));
item.setLatLocation(itemLats.get(i));
items.add(item);
}
return items;
}
First of all, I wanna recommend you this: https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html
It's a tutorial that show you how yo make typical SQL queries in Firebase, BUT, like the owner says:
While this post still contains some useful and relevant information, we have released advanced query functionality which solves a lot of the problems this post discusses.
So, now, I will tell you the basic query that may solve your problem.
As I see, you have a table about Items, and you are doing a SELECT where that item's Category is beauty.
I will assume that you already know how data is stored in Firebase, so I'm not making us lose time explaining to you about the database tree.
Reading
You will need something like:
Query query = FirebaseDatabase.getInstance().getReference()
.child("items")
.orderByChild("Category")
.equalTo("beauty");
This, after attaching the listener to it, will search in the items tree, those items where the value of its category child, is beauty. The logic here is:
FirebaseDatabase.getInstance().getReference() -> Go to the main node
.child("items") -> Go to the Items node
.orderByChild("Category") -> Order them by its Category child
.equalTo("beauty") -> Look only at those with the "beauty" value
You will always need to do an orderBy*() to append an equalTo() and mimic the WHERE clause.
And, in your listener you will have something like:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
List<Item> list = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Item item = snapshot.getValue(Item.class);
list.add(item);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//
}
};
query.addValueEventListener(eventListener);
And, since all Firebase connections are async, you will need a calback method to return the list after the for.
Writing
Now, for the upload, you will need a DatabaseReference, instead of a Query, like:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("items");
And all you need to do is:
ref.push().setValue(item); -> For a random ID
ref.child(key).setValue(item); -> For an specific ID (key)
I'm pretty new to an Android development and currently trying to write an app that will show tomorrow's weather of multiple cities. Sorry for any incorrent termins that I might use in this question.
What I want to reach:
App will fetch data from local database, then build a HTTP query on the data fetched from a DB, get JSON response and form a list elements.
What I currently have:
Everything except SQL functionality.
Here is the snapshot of my main activity code. I use LoaderCallbacks<List<Weather>> to build URI with needed parameters in onCreateLoader(int i, Bundle bundle), send HTTP query and get the data via WeatherLoader(this, uriList), and form elements results in a List using WeatherAdapter.
public class WeatherActivity extends AppCompatActivity
implements LoaderCallbacks<List<Weather>>,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final int WEATHER_LOADER_ID = 1;
private WeatherAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_activity);
ListView weatherListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
weatherListView.setEmptyView(mEmptyStateTextView);
mAdapter = new WeatherAdapter(this, new ArrayList<Weather>());
weatherListView.setAdapter(mAdapter);
...
weatherListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Weather currentWeather = mAdapter.getItem(position);
Uri forecastUri = Uri.parse(currentWeather.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, forecastUri);
startActivity(websiteIntent);
}
});
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(WEATHER_LOADER_ID, null, this);
} else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
#Override
public Loader<List<Weather>> onCreateLoader(int i, Bundle bundle) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String tempUnit = sharedPrefs.getString(
getString(R.string.settings_temp_unit_key),
getString(R.string.settings_temp_unit_default));
List<String> uriList = new ArrayList<>();
/***
*
* Here we input cities for which we want to see the forecast
*
* ***/
List<String> cities = new ArrayList<>();
cities.add("London,uk");
cities.add("Kiev,ua");
cities.add("Berlin,de");
cities.add("Dubai,ae");
//For each city in the list generate URI and put it in the URIs list
for (String city : cities){
Uri baseUri = Uri.parse(OWM_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("q", city);
uriBuilder.appendQueryParameter("cnt", "16");
uriBuilder.appendQueryParameter("units", tempUnit);
uriBuilder.appendQueryParameter("appid", "some_key");
uriList.add(uriBuilder.toString());
}
return new WeatherLoader(this, uriList);
}
#Override
public void onLoadFinished(Loader<List<Weather>> loader, List<Weather> weatherList) {
mAdapter.clear();
// If there is a valid list of forecasts, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (weatherList != null && !weatherList.isEmpty()) {
mAdapter.addAll(weatherList);
}
}
#Override
public void onLoaderReset(Loader<List<Weather>> loader) {
mAdapter.clear();
}
As you see, cities are "hardcoded" via List<String> cities = new ArrayList<>(); in onCreateLoader(int i, Bundle bundle). That's why I've decided to implement SQL storage of cities in my app. I know how to implement SQL functionality in android app using ContentProvider and CursorAdapter.
So what's the problem?
If I am correct we should use LoaderManager.LoaderCallbacks<Cursor> if we want to make a query to a local DB.
Unfortunately, I can't imagine how to merge current LoaderCallbacks<List<Weather>> and LoaderCallbacks<Cursor> in one activity to make it work as I want.
Actually, I want to change
List<String> cities = new ArrayList<>();
on something like
Cursor cursor = new CursorLoader(this, WeatherEntry.CONTENT_URI, projection, null, null, null); to build the URI on the results that CursorLoader returns.
But, we should make SQL query in separate thread and HTTP query also(!) in separate thread. Should we do nested threads/loaders (http query in a scope of sql fetching data and return a List<T>)? Even can't imagine how it's possible to do, if so...
Help me please, I've stuck!
Ok, it was not obvious to me at the first sight, but I finally solved the problem.
In the question above we had a list of cities that were hardcoded:
List<String> cities = new ArrayList<>();
cities.add("London,uk");
cities.add("Kiev,ua");
cities.add("Berlin,de");
cities.add("Dubai,ae");
Even if we assume that we will change it to a DB query, like this:
// Connect to a DB
...
Cursor forecastCitiesDataCursor = mDb.query(true, WeatherContract.WeatherEntry.TABLE_NAME, projection,
null, null, null,
null, null, null);
...
// Fetch data from cursor
...we will have that SQL query on the main thread. So we need a solution.
The best thing that I've found for me, it is put that SQL query in CustomLoader class and pass needed parameters in a constructor (in my case, it is SharedPreferences parameter to built an HTTP query).
Here is my code:
WeatherActivity.java
public class WeatherActivity extends AppCompatActivity implements LoaderCallbacks<List<Weather>>,
SharedPreferences.OnSharedPreferenceChangeListener {
...
#Override
public Loader<List<Weather>> onCreateLoader(int i, Bundle bundle) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String tempUnit = sharedPrefs.getString(
getString(R.string.settings_temp_unit_key),
getString(R.string.settings_temp_unit_default));
return new WeatherLoader(this, tempUnit);
}
#Override
public void onLoadFinished(Loader<List<Weather>> loader, List<Weather> weatherList) {
// Hide loading indicator because the data has been loaded
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
// Set empty state text to display "No forecasts found."
mEmptyStateTextView.setText(R.string.no_forecasts);
// Clear the adapter of previous forecasts data
mAdapter.clear();
// If there is a valid list of forecasts, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (weatherList != null && !weatherList.isEmpty()) {
mAdapter.addAll(weatherList);
}
}
WeatherLoader.java
public class WeatherLoader extends AsyncTaskLoader<List<Weather>> {
...
// Pass parameters here from WeatherActivity
public WeatherLoader(Context context, String tmpUnit) {
super(context);
mTempUnit = tmpUnit;
}
#Override
protected void onStartLoading() {
forceLoad();
}
/**
* This is on a background thread.
*/
#Override
public List<Weather> loadInBackground() {
// List for storing built URIs
List<String> uriList = new ArrayList<>();
// List for storing forecast cities
List<String> cities = new ArrayList<>();
// Define a projection that specifies the columns from the table we care about.
...
Cursor forecastCitiesDataCursor = mDb.query(true, WeatherContract.WeatherEntry.TABLE_NAME, projection,
null, null, null,
null, null, null);
// Get list of cities from cursor
...
//For each city in the list generate URI and put it in the URIs list
for (String city : cities){
Uri baseUri = Uri.parse(OWM_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("q", city);
uriBuilder.appendQueryParameter("cnt", "16");
uriBuilder.appendQueryParameter("units", mTempUnit);
uriBuilder.appendQueryParameter("appid", /*some id*/);
uriList.add(uriBuilder.toString());
}
if (uriList == null) {
return null;
}
// Perform the network request, parse the response, and extract a list of forecasts.
List<Weather> forecasts = QueryUtils.fetchForecastData(uriList);
return forecasts;
}
So what we've got?
We've implemented persistent data storage within the work with ArrayAdapter that are used to do an HTTP query then. SQL query are on the separate thread and we'll have no problem with app performance.
Hope that solution will help somebody, have a nice day!
I have a SQLite table (on Android) that has numerous fields, but certain fields are repeated/denormalized. I would like to select a distinct set of this data and use them as actual objects.
Example
books table
title summary author
Little Johnny A funny kid Johnny Himself
Big Johnny A funny adult Johnny Himself
I would like to extract one author from this list ("Johnny Himself") and would expect I should be able to do this with ORMLite instead of manually with Java.
I would like to select a distinct set of this data and use them as actual objects.
ORMLite supports a distinct() method on the QueryBuilder that should do what you want. So your code would look something like:
List<Book> results = booksDao.queryBuilder()
.distinct().selectColumns("author").query();
In this case, the resulting Book objects would only have the author field set and not the id field or anything else. If you just wanted the author names instead of objects then you could do:
GenericRawResults<String[]> rawResults =
booksDao.queryRaw("SELECT DISTINCT author FROM books");
for (String[] resultColumns : rawResults) {
String author = resultColumns[0];
...
}
This is my application code
public class DbHelper<T> {
private Class<T> c;
private DatabaseHelper db;
public DbHelper(Class<T> c) {
this.c = c;
db = DatabaseHelper.getInstance();
}
This is a good idea
public List<T> queryForBuilderDistinct(int offset, int limit, String ColumnsName,
String orderName, boolean isAsc) {
try {
Dao<T, Integer> dao = db.getDao(c);
QueryBuilder<T, Integer> queryBuilder = dao.queryBuilder();
if (offset != 0) {
queryBuilder.offset((long) offset);
}
if (limit != 0) {
queryBuilder.limit((long) limit);
}
if (orderName != null) {
queryBuilder.orderBy(orderName, isAsc);
}
queryBuilder.distinct().selectColumns(ColumnsName);
return dao.query(queryBuilder.prepare());
} catch (SQLException e) {
LogUtil.e(TAG, "queryForBuilderDistinct", e);
}
return new ArrayList<T>();
}
I want to query all rows from my sqlite database and then pass it to a listview to display on my app.
Here is the code(I do have a student.java implemented):
StudentDAO.java:
public void add(Student student)
{
db = helper.getWritableDatabase();
db.execSQL("insert into t_student (sid, name, age) values (?,?,?)", new Object[]
{ student.getId(), student.getName(), student.getAge()}
);
}
public Student findAll()
{
db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery("select sid, name, age from t_student", (String[]) new Object()
);
if(cursor.moveToNext())
return new Student(cursor.getInt(cursor.getColumnIndex("sid")), cursor.getString(cursor.getColumnIndex("name")), cursor.getShort(cursor.getColumnIndex("age")));
return null;
}
MultiList.java:
public class MultiList extends ListActivity {
ListView lv;
SimpleAdapter sd;
StudentDAO dao = new StudentDAO(MultiList.this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Student Alex = new Student();
chan.setId(1);
chan.setAge((short) 18);
chan.setName("Alex ");
dao.add(Alex );
Student Queena = new Student();
chan2.setId(2);
chan2.setAge((short) 19);
chan2.setName("Queena");
dao.add(Queena);
Student Tom = new Student();
chan3.setId(3);
chan3.setAge((short) 20);
chan3.setName("Tom");
dao.add(Tom);
dao.findAll();////how to store them???
As you can see, now, after i inserted all three students object into my database, how do i read them and store them? Because my findAll() method return a student object.
Sorry this might be a easy question, please help
There is two easy options, the best in my view is to use a CursorAdapter and pass a cursor with your query, in this case listView will load only showed elements and will dinamicaly load from database while you scroll.
Or you can execute the query for your self and store objects in an array to show with a SimpleCursorAdapter.