I want to show the GPS location of the user on google maps by retrieving the longitude and latitude from SQLite. Please tell me the procedure to show the information from SQLite on Google map. Here is the code I am using for saving the longitude and latitude. And I am also using the link
http://www.androidhive.info/2012/01/android-working-with-google-maps/
for maps but don't know how to retrieve the longitude and latitude from SQLite.
MAiN ACTIVITY:
public class MainActivity extends Activity {
ListView list;
mylocation loc = new mylocation();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager mylocman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener myloclist = new mylocation();
mylocman.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,myloclist);
loc.updateDatabase(this);
GPSdatabase myDatabase=new GPSdatabase(this);
myDatabase.open();
Cursor cursor=myDatabase.getAllRows();
cursor.moveToFirst();
ArrayList listContents = new ArrayList();
for (int i = 0; i < cursor.getCount(); i++)
{
listContents.add("Lat=" +cursor.getString(1) +" "+"Log "+ cursor.getString(2));
cursor.moveToNext(); } myDatabase.close();
ListAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line, listContents);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
/*public void updateDatabase(){
GPSDatabase myDatabase=new GPSDatabase(context);
myDatabase.open();
myDatabase.insertRow(lat.substring(0,4),log.substring(0,4));
myDatabase.close();
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}
My Location class:
public class mylocation implements LocationListener {
String lat=null;
String log=null;
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String text="my latitude="+location.getLatitude()+"longitude="+location.getLongitude();
lat=location.getLatitude()+"";
log=location.getLongitude()+"";
//updateDatabase();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void updateDatabase(Context context)
{
if(lat!=null || log!=null)
{
GPSdatabase myDatabase=new GPSdatabase(context);
myDatabase.open();
myDatabase.insertRows(lat.substring(0,4),log.substring(0,4));
myDatabase.close();
}
}
}
My DATABASE CLASS:
public class GPSdatabase {
private Context context;
private DbHelper dbHelper;
public final String DBNAME = "gps1";
public final int DBVERSION = 3;
public SQLiteDatabase db;
public final String COLUMN2 = "latitude";
public final String COLUMN3 = "longitude";
public final String COLUMN1 = "locationId";
public final String TABLENAME = "location";
public final String CREATERDB = "create table location(locationId integer primary key autoincrement, latitude text not null, longitude text not null);";
public GPSdatabase(Context context) {
this.context = context;
dbHelper = new DbHelper(context);
}
public class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE = "CREATE TABLE " + "location" + "(" +
"latitude" + " TEXT," +
"longitude" + " TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public long insertRows(String column2, String column3) {
ContentValues value = new ContentValues();
value.put(COLUMN2, column2);
value.put(COLUMN3, column3);
return db.insert(TABLENAME, null, value);
}
public Cursor getAllRows() {
Cursor cursor = db.query(TABLENAME, new String[] {
COLUMN1,
COLUMN2,
COLUMN3
}, null, null, null, null, null);
return cursor;
}
public void open() throws SQLException {
db = dbHelper.getWritableDatabase();
//return true;
}
public void close() {
dbHelper.close();
//return true;
}
}
Why not showing directly the location of the user without saving and retrieving back and forth?
if you tell to the map to show user location, it is done automatically:
http://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.html#setMyLocationEnabled(boolean)
map.setMyLocationEnabled(true);
Related
I am having trouble displaying the data in listview. In the dialogbox the user enters the item and click save button it stores the data in sqlite database but it does not displaying in listview. when i moved to MainActivity.java and returns back to AddCount.java it display the item which is stored in sqlite database. How can i display the item in listview as soon as user clicks save in dialogbox
public class AddCount extends AppCompatActivity {
ArrayList<User>userList;
User user;
DbHandler myDB;
Cursor data;
int numRows;
Two_columnListAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_count);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ListView listView = (ListView)findViewById(R.id.listview);
myDB = new DbHandler(this);
userList = new ArrayList<>();
data = myDB.getListContents();
numRows = data.getCount();
if (numRows == 0) {
Toast.makeText(AddCount.this, "There is nothing in database", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
user = new User(data.getString(1), data.getString(2));
userList.add(user);
}
}
adapter = new Two_columnListAdapter(this,R.layout.list_item_layout,userList);
listView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDialog();
}
});
}
public void openDialog() {
final AlertDialog.Builder mydialog = new AlertDialog.Builder(AddCount.this);
mydialog.setTitle("Add Count");
LinearLayout layout = new LinearLayout(AddCount.this);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText title = new EditText(AddCount.this);
title.setHint("Title");
layout.addView(title);
final EditText value = new EditText(AddCount.this);
value.setHint("Count");
layout.addView(value);
mydialog.setView(layout);
mydialog.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String UserTitle = title.getText().toString();
String UserCount = value.getText().toString();
if (UserTitle.length()!= 0 && UserCount.length() != 0) {
AddData(UserTitle,UserCount);
title.setText("");
value.setText("");
adapter.notifyDataSetChanged();
}
else {
Toast.makeText(AddCount.this ,"Empty!",Toast.LENGTH_SHORT).show();
}
}
}).create();
mydialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).create();
mydialog.show();
}
public void AddData(String title,String count){
boolean insertData = myDB.insertUserInputs(title, count);
if (insertData==true){
Toast.makeText(AddCount.this ,"Saved",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(AddCount.this ,"Some thing went wrong",Toast.LENGTH_SHORT).show();
}
}
}
DbHandler.java (create and manage the database)
public class DbHandler extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "users.db";
private static final String TABLE_Inputs = "userinputs";
private static final String KEY_ID = "id";
private static final String KEY_Title = "Title";
private static final String KEY_Count = "Count";
public DbHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// Create a new table
String CREATE_TABLE = "CREATE TABLE " + TABLE_Inputs + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + "Title,Count)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if exist
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inputs);
// Create tables again
onCreate(db);
}
public boolean insertUserInputs(String UserTitle, String UserCount) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_Title, UserTitle);
contentValues.put(KEY_Count, UserCount);
long newRowId = db.insert(TABLE_Inputs, null, contentValues);
if (newRowId == -1){
return false;
}
else {
return true;
}
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_Inputs,null);
return data;
}
}
Two_columnListAdapter.java
public class Two_columnListAdapter extends ArrayAdapter<User> {
private LayoutInflater layoutInflater;
private ArrayList<User>users;
private int mviewResourceId;
public Two_columnListAdapter(Context context,int textViewResourceId,ArrayList<User>users){
super(context,textViewResourceId,users);
this.users = users;
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mviewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = layoutInflater.inflate(mviewResourceId,null);
User user= users.get(position);
if (user != null){
TextView text = (TextView)convertView.findViewById(R.id.title);
TextView num = (TextView)convertView.findViewById(R.id.value);
if (text != null){
text.setText(user.getText());
}
if (num != null){
num.setText(user.getNum());
}
}
return convertView;
}
}
You don't add anything to the list via your adapter, nor you add anything to the list directly when the data is saved to the DB.
You shuold add items to the list via your adapter:
adapter.add(someItem);
or you can add items to the list, then call notifyDataSetChanged
userlist.add(user);
adapter.notifyDataSetChanged();
In your OnClickListener add the user to the list via the adapter...
mydialog.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String UserTitle = title.getText().toString();
String UserCount = value.getText().toString();
if (UserTitle.length()!= 0 && UserCount.length() != 0) {
AddData(UserTitle,UserCount);
title.setText("");
value.setText("");
adapter.add(new User(....));
...
Check out this answer on adapters.
I have an app where a user can put in three inputs (name, quantity and type) I want the input to go into the database and then when the user clicks the status button then they can view all of the user inputs in a listview. In my case when i run the app the items get added to the database but then when i click to view them in the inventorystatus activity the app exits off. Does anyone know where I have gone wrong or what im missing? It might be a stupid question im new to this sorry.
DatabaseHelperUser class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Inventory.db";
public static final String TABLE_NAME = "Inventory_table";
public static final String COL1 = "Name";
public static final String COL2 = "Quantity";
public static final String COL3 = "Type";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (Name TEXT, Quantity Text, Type Text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String Name, String Quantity, String Type){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, Name);
contentValues.put(COL2, Quantity);
contentValues.put(COL3, Type);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("select * from " + TABLE_NAME, null);
return data;
}
public String deletedata(){
SQLiteDatabase myDB = this.getWritableDatabase();
myDB.delete(TABLE_NAME, null, null);
myDB.close();
return null;
}
}
AddItem Class:
public class AddItem extends AppCompatActivity {
DatabaseHelper myDB;
EditText etName, etQuantity, etType;
Button btAdd2, btStatus2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
myDB = new DatabaseHelper(this);
final EditText etName = findViewById(R.id.editTextName);
final EditText etQuantity = findViewById(R.id.editTextQuantity);
final RadioButton rbBiscuit = findViewById(R.id.radioButtonBiscuit);
final RadioButton rbCookie = findViewById(R.id.radioButtonCookie);
final RadioButton rbCake = findViewById(R.id.radioButtonCake);
final RadioButton rbIngredient = findViewById(R.id.radioButtonIngredient);
final RadioButton rbOther = findViewById(R.id.radioButtonOther);
Button btAdd2 = findViewById(R.id.buttonAdd2);
final Button btStatus2 = findViewById(R.id.buttonStatus2);
final EditText etType = findViewById(R.id.editTextType1);
btAdd2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String edtName = etName.getText().toString();
String edtQuantity = etQuantity.getText().toString();
String edtType = etType.getText().toString();
if (etName.length() !=0 || etQuantity.length() !=0 || etType.length() !=0){
// myDB.insertData(edtName, edtQuantity, edtType);
AddData(edtName, edtQuantity, edtType);
etName.setText("");
etQuantity.setText("");
etType.setText("");
}
else{
Toast.makeText(AddItem.this, "Fill in all of the fields", Toast.LENGTH_SHORT).show();
}
}
public void AddData(String edtName, String edtQuantity, String edtType){
boolean insert = myDB.insertData(edtName, edtQuantity, edtType);
if(insert){
Toast.makeText(AddItem.this, "Data Inserted", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(AddItem.this, "Error, Data not Inserted", Toast.LENGTH_SHORT).show();
}
}
});
btStatus2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(AddItem.this, InventoryStatus.class);
startActivity(i);
}
});
}
}
InventoryStatus class:
public class InventoryStatus extends AppCompatActivity {
DatabaseHelper myDB;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_status);
ListView listView = findViewById(R.id.listViewStock);
myDB = new DatabaseHelper(this);
populateListView();
}
public void populateListView(){
Cursor data = myDB.getAllData();
ArrayList<String> list = new ArrayList<>();
while(data.moveToNext()){
list.add(data.getString(1));
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
}
}
You forgot to pass list to adapter constructor.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, **list**);
And try type-casting listview in InventoryStatus.class as:
ListView listView = (ListView) findViewById(R.id.listViewStock);
I've been stuck in this problem for a week. I have a listview dialog fragment that uses a custom base adapter and connect with sqlite database.
My database adapter:
public class DBAdapter {
// Column Product
static final String ROWID = "id";
static final String NAME = "name";
static final String DESC = "desc";
static final String PRICE = "price";
static final String DISPLAY = "display";
// DB Properties
static final String DBNAME = "db_prototype";
static final String TBNAME = "tbl_product";
static final int DBVERSION = 1;
static final String CREATE_TABLE = "CREATE TABLE tbl_product(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL," +
" desc TEXT NOT NULL, price TEXT NOT NULL, display INTEGER NOT NULL)";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context c) {
this.c = c;
helper = new DBHelper(c);
}
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
}catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DBHelper.class.getName(), "Upgrading DB");
db.execSQL("DROP TABLE IF EXIST tbl_product");
}
}
// Open Database
public DBAdapter openDB(){
try{
db = helper.getWritableDatabase();
}catch (SQLException e){
e.printStackTrace();
}
return this;
}
public void closeDB(){
helper.close();
}
// Insert Into Table
public long add(String name, String desc, String price, int display){
try{
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(DESC, desc);
cv.put(PRICE, price);
cv.put(DISPLAY, display);
return db.insert(TBNAME, ROWID, cv);
}catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
// Delete Table
public long delete(String name){
try{
return db.delete(TBNAME, NAME + "='" + name + "'", null);
}catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
// Get All Value
public Cursor getAllValue(){
String[] columns = {ROWID, NAME, DESC, PRICE, DISPLAY};
return db.query(TBNAME, columns, null, null, null, null, null);
}
}
My Listview adapter (void refreshAdapter to refresh dataset):
public class CartAdapter extends BaseAdapter {
private Context c;
private ArrayList<Integer> display;
private ArrayList<String> nama;
private ArrayList<String> harga;
public CartAdapter(Context c, ArrayList<Integer> display, ArrayList<String> nama, ArrayList<String> harga) {
this.c = c;
this.display = display;
this.harga = harga;
this.nama = nama;
}
#Override
public int getCount() {
return nama.size();
}
#Override
public Object getItem(int position) {
return nama.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_display, null);
}
// Get View
TextView txtNama = (TextView) convertView.findViewById(R.id.txtNama);
TextView txtHarga = (TextView) convertView.findViewById(R.id.txtHarga);
ImageView imgGambar = (ImageView) convertView.findViewById(R.id.imgGambar);
//Assign Data
txtNama.setText(nama.get(position));
txtHarga.setText(harga.get(position));
imgGambar.setImageResource(display.get(position));
return convertView;
}
public void refreshAdapter(ArrayList<Integer> display, ArrayList<String> nama, ArrayList<String> harga){
this.display.clear();
this.harga.clear();
this.nama.clear();
this.display = display;
this.harga = harga;
this.nama = nama;
this.notifyDataSetChanged();
}
}
My Listview dialog fragment:
public class CartDialog extends DialogFragment {
ArrayList<String> cart_name;
ArrayList<String> cart_price;
ArrayList<Integer> cart_pict;
DBAdapter dbAdapter;
CartAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_cart_dialog, null);
ListView LV = (ListView) rootView.findViewById(R.id.listCart);
Button btnDelete = (Button) rootView.findViewById(R.id.button);
// Prepare ArrayList to assign with DB
cart_pict = new ArrayList<Integer>();
cart_name = new ArrayList<String>();
cart_price = new ArrayList<String>();
getDialog().setTitle("Keranjang Belanjaan");
dbAdapter = new DBAdapter(getActivity());
adapter = new CartAdapter(getActivity(), cart_pict, cart_name, cart_price);
refreshDB();
LV.setAdapter(adapter);
LV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = adapter.getItem(position).toString();
// Delete Selected Item on SQLite Database
dbAdapter.openDB();
long result = dbAdapter.delete(name);
dbAdapter.closeDB();
//Refresh Cart
refreshDB();
adapter.refreshAdapter(cart_pict, cart_name, cart_price);
}
});
return rootView;
}
public void refreshDB(){
// Refresh Data
dbAdapter.openDB();
Cursor c = dbAdapter.getAllValue();
while(c.moveToNext()){
String name = c.getString(1);
String price = c.getString(3);
int display = c.getInt(4);
cart_name.add(name);
cart_price.add(price);
cart_pict.add(display);
}
Toast.makeText(getActivity(), "Jumlah: " + c.getCount(), Toast.LENGTH_SHORT).show();
dbAdapter.closeDB();
}
}
So, whenever I click an item in the listview, DBAdapter will remove these items from SQLite Database and then CartAdapter will refresh listview. I've been looking for references to this problem, add notifyDatasetChange (), but the problem is after I called the refreshData() method, the data in listview will empty.
Try this bro
public void refreshDB(){
// Refresh Data
ArrayList<Integer> displayBaru = new ArrayList<Integer>();
ArrayList<String> namaBaru = new ArrayList<String>();
ArrayList<String> hargaBaru = new ArrayList<String>();
dbAdapter.openDB();
Cursor c = dbAdapter.getAllValue();
while(c.moveToNext()){
String name = c.getString(1);
String price = c.getString(3);
int display = c.getInt(4);
namaBaru.add(name);
hargaBaru.add(price);
displayBaru.add(display);
}
adapter.refreshAdapter(displayBaru, namaBaru, hargaBaru);
dbAdapter.closeDB();
}
I have a listview with a getCount() of 7. I want all 7 items to be shown regardless if any data from my database is available to populate them. If no data is available then an item should just be blank with predetermined text.
When I have not hardcoded 7 database entries beforehand to go into the 7 views then I get an indexoutofbound exception when running the app due to the 7 items not being able to be populated accordingly. This happens in ListMealsAdapter.java when method Meal currentItem = getItem(position); is called and triggers public Meal getItem(int position).
I am looking for a condition statement that I can use for my listview/adapter that can handle an empty database so that the index does not go out of bounds. Also, is the BaseAdapter suited for what I want to do?
MainActivity.java
public class MainActivity extends BaseActivity {
public static final String TAG = "MainActivity";
private ListView mListviewMeals;
private MealDAO mMealDao;
private List<Meal> mListMeals;
private ListMealsAdapter mAdapter;
private SQLiteDatabase mDatabase;
DatabaseHelper mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activateToolbar(1);
// initialize views
initViews();
// fill the dailyListView
mMealDao = new MealDAO(this);
mListMeals = mMealDao.getAllMeals();
mAdapter = new ListMealsAdapter(this, mListMeals, MainActivity.this);
mListviewMeals.setAdapter(mAdapter);
}
private void initViews() {
this.mListviewMeals = (ListView) findViewById(R.id.view_daily_list);
}
ListMealsAdapter.java
public class ListMealsAdapter extends BaseAdapter {
public static final String TAG = "ListMealsAdapter";
Activity mActivity;
private List<Meal> mItems;
private LayoutInflater mInflater;
public ListMealsAdapter(Context context, List<Meal> listMeals, Activity activity) {
super();
mActivity = activity;
this.setItems(listMeals);
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return 7;
}
#Override
public Meal getItem(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position) : null;
}
#Override
public long getItemId(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position).getId() : position;
}
#Override
public View getView(int position, final View convertView, final ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
v = mInflater.inflate(R.layout.list_item_daily, parent, false);
holder = new ViewHolder();
holder.txtDescription = (TextView) v.findViewById(R.id.txtBreakfast);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
// fill row data
Meal currentItem = getItem(position);
if (currentItem != null) {
holder.txtDescription.setText(currentItem.getDescription());
}
return v;
}
public List<Meal> getItems() {
return mItems;
}
public void setItems(List<Meal> mItems) {
this.mItems = mItems;
}
class ViewHolder {
TextView txtDescription;
}
}
Meal.java
public class Meal implements Serializable {
public static final String TAG = "Meal";
private static final long serialVersionUID = -7406082437623008161L;
private long mId;
private int mType;
private String mDescription;
public Meal() {
}
public Meal(int type, String description) {
this.mType = type;
this.mDescription = description;
}
public long getId() {
return mId;
}
public void setId(long mId) {
this.mId = mId;
}
public int getType() {
return mType;
}
public void setType(int mType) {
this.mType = mType;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
}
MealDAO.java
public class MealDAO {
public static final String TAG = "MealDAO";
private SQLiteDatabase mDatabase;
private DatabaseHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = { DatabaseHelper.COLUMN_MEAL_ID,
DatabaseHelper.COLUMN_MEAL_TYPE, DatabaseHelper.COLUMN_MEAL_DESCRIPTION};
public MealDAO(Context context) {
this.mContext = context;
mDbHelper = new DatabaseHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on opening database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public List<Meal> getAllMeals() {
List<Meal> listMeals = new ArrayList<Meal>();
Cursor query = mDatabase.rawQuery("SELECT * from meal", null);
if(query.moveToFirst()) {
do {
// Cycle through all records
Meal meal = cursorToMeal(query);
listMeals.add(meal);
} while(query.moveToNext());
}
return listMeals;
}
public Meal getMealById(long id) {
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_MEALS, mAllColumns,
DatabaseHelper.COLUMN_MEAL_ID + " = ?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Meal meal = cursorToMeal(cursor);
return meal;
}
protected Meal cursorToMeal(Cursor cursor) {
Meal meal = new Meal();
meal.setId(cursor.getLong(0));
meal.setType(cursor.getInt(1));
meal.setDescription(cursor.getString(2));
return meal;
}
}
After a LOT of trial and error I finally found an acceptable solution to my problem. What I did was to add a default row to my database for the view items that I wanted to have a predetermined database entry when no data had been entered beforehand.
I then made sure to start at index 2, making sure that index 1 would be reserved for my default value. If the index comes out of bounds then the exception is caught and the default database entry will be added to the array.
public Meal getItem(int position) {
Meal result;
try {
result = (getItems() != null && !getItems().isEmpty()) ? getItems().get(position) : null;
} catch (Exception e) {
Meal default = getItem(0);
return default;
}
return result;
}
Meal currentItem = getItem(position + 1);
if (currentItem != null) {
holder.txtDescription.setText(currentItem.getDescription());
}
With that change things have been running smooth ever since. I hope this can help someone else as well.
I am working on a sample application by communicate with .net web service.In my application I am getting records from web service into my activity class then i am displaying entire records in ListView by using ArrayAdapter and also i am running a service class at background process for get the latest record from web service when the new records are available from web service then i am saving those records in to SQLite data base.This process is happening at back ground.Here i would like to get the latest data from SQLite DB and append to my ListView.
I have implemented Activity class as follows:
public class GetMsgsScreen extends ListActivity
{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static String[] userName = null;
static String[] usrMessages = null;
private Integer[] imgid = null;
ShoutRepeatService bg;
////////////////////////////////////////////////////
List<Message> resultShoutMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
resultMessage = new ParseXml().convertMessages(new Model().getMessages("0"));
usrMessages = new String[resultMessage.size()];
userName = new String[resultMessage.size()];
imgid = new Integer[resultMessage.size()];
getSharedPreferences("Values", 0).edit().putString("msgid",resultMessage.get(0).getMessageID()).commit();
for(int i=0;i<resultMessage.size();i++)
{
Log.v("GetMsgsScreen", "resultMessage*******>>>>"+resultMessage.get(i).getMessageText());
Log.v("GetMsgsScreen", "resultNames*******>>>>"+resultMessage.get(i).getUserFirstName());
usrMessages[i] = resultMessage.get(i).getMessageText();
userName[i] = resultMessage.get(i).getUserFirstName();
imgid[i] = R.drawable.person;
}
///////////////////////////////////////////////////////
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<userName.length;i++){
try {
rd = new RowData(i,userName[i],usrMessages[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.usrName, data);
setListAdapter(adapter);
bindService(new Intent(GetMsgsScreen.this, RepeatService.class), mConnection, Context.BIND_AUTO_CREATE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getListView().setTextFilterEnabled(true);
}
#Override
protected void onDestroy() {
unbindService(mConnection);
super.onDestroy();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
bg = ((RepeatService.MyBinder) binder).getService();
Toast.makeText(GetMsgsScreen.this, "Connected",
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
bg = null;
}
};
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "You have selected "
+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView name = null;
TextView messages = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
name = holder.gettitle();
name.setText(rowData.mName);
messages = holder.getdetail();
messages.setText(rowData.mMessage);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView names = null;
private TextView messageText = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == names){
names = (TextView) mRow.findViewById(R.id.usrName);
}
return names;
}
public TextView getdetail() {
if(null == messageText){
messageText = (TextView) mRow.findViewById(R.id.msgText);
}
return messageText;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
I have implemented background service class as follows:
public class RepeatService extends Service
{
List<Message> resultMessage;
String[] userNameLatest = null;
String[] usrMessagesLatest = null;
String[] usrMessageID = null;
String msgID = null;
private Timer timer = new Timer();
private static final long UPDATE_INTERVAL = 500;
SQLiteDB db;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
private void pollForUpdates() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("!!!!!!!!!!!!!!!!", "service is calling");
msgID = getSharedPreferences("Values", 0).getString("msgid","");
resultMessage = new ParseXml().convertMessages(new Model().getMessages(msgID));
usrMessagesLatest = new String[resultMessage.size()];
userNameLatest = new String[resultMessage.size()];
usrMessageID = new String[resultMessage.size()];
db = new SQLiteDB();
for(int i=0;i<resultMessage.size();i++)
{
Log.v("RepeatService", "getMessageID------>"+resultMessage.get(i).getMessageID());
Log.v("RepeatService", "getMessageText------>"+resultMessage.get(i).getMessageText());
Log.v("RepeatService", "getUserFirstName------>"+resultMessage.get(i).getUserFirstName());
usrMessagesLatest[i] = resultMessage.get(i).getMessageText();
userNameLatest[i] = resultMessage.get(i).getUserFirstName();
usrMessageID[i] = resultMessage.get(i).getMessageID();
//Save the data into Sqlite db here
db.insertValues(usrMessageID[i], userNameLatest[i], usrMessagesLatest[i], RepeatService.this);
}
}
}, 0, UPDATE_INTERVAL);
Log.v(getClass().getSimpleName(), "Timer started.");
}
public class MyBinder extends Binder {
ShoutRepeatService getService()
{
return ShoutRepeatService.this;
}
}
}
The above class always run at back ground if any new record available from web service then store the record into Sqlite db.
From the above code i can save the data in to Sqlite data base then
How can i show the latest record to my ListView on My Activity class?
please any body help me with code explanation.........
I would probably use a BroadcastReceiver that is notified from the service when something new has been added. It could then update your list. Also look at LocalBroadcastManager since all the communication is in your app.