I need to analyze the result of a PlanningEntity to calculate the time between two production order allocations - optaplanner

I am developing a system for sequencing production orders for a food industry.
I need to analyze the setup time of the equipment between two production orders when changing the product produced in the equipment.
I'm trying to use shadow variable, but I need to analyze the result of the optaplanner's solver. For this I am using the list of allocations (PlanningEntity) that I get from the ScoreDirector of the afterEntityAdded method.
Is this procedure correct?
'Shadow Variable Code
private static final Logger logger = LoggerFactory.getLogger(SetupVariableListener.class);
#Override
public void beforeEntityAdded(ScoreDirector scoreDirector, Alocacao entity) {
// Do nothing
}
#Override
public void afterEntityAdded(ScoreDirector scoreDirector, Alocacao entity) {
updateAllocation(scoreDirector, entity);
}
#Override
public void beforeVariableChanged(ScoreDirector scoreDirector, Alocacao entity) {
// Do nothing
}
#Override
public void afterVariableChanged(ScoreDirector scoreDirector, Alocacao entity) {
updateAllocation(scoreDirector, entity);
}
#Override
public void beforeEntityRemoved(ScoreDirector scoreDirector, Alocacao entity) {
// Do nothing
}
#Override
public void afterEntityRemoved(ScoreDirector scoreDirector, Alocacao entity) {
// Do nothing
}
protected void updateAllocation(ScoreDirector scoreDirector, Alocacao originalAllocation) {
boolean updated = false;
int tempo = 0;
int tempoPausa = 0;
Hashtable<Setup, Integer> st = new Hashtable<>();
Agenda agenda = (Agenda) scoreDirector.getWorkingSolution();
if (originalAllocation.getProcessoProducao().getSequenciaProducao() == 1) {
List<Alocacao> alocacoes = agenda.getAlocacoesOrdens().stream().filter(g -> g.getProcessoProducao().getSequenciaProducao() == 1 && g.getEquipamento().equals(originalAllocation.getEquipamento())).sorted((a1, b1) -> {
return new CompareToBuilder()
.append(a1.getProcessoProducao().getOrdemProducao().getNrOrdemProducao(), b1.getProcessoProducao().getOrdemProducao().getNrOrdemProducao())
.append(a1.getProcessoProducao().getOrdemProducao().getSequenciaDivisao(), b1.getProcessoProducao().getOrdemProducao().getSequenciaDivisao())
.append(a1.getProcessoProducao().getSequenciaProducao(), b1.getProcessoProducao().getSequenciaProducao())
.toComparison();
}).collect(Collectors.toList());
int posicaoOrigem = alocacoes.indexOf(originalAllocation);
if ((posicaoOrigem + 1) < alocacoes.size()) {
SeqItem itemOrigem = originalAllocation.getProcessoProducao().getOrdemProducao().getItem();
SeqItem itemDestino = alocacoes.get(posicaoOrigem + 1).getProcessoProducao().getOrdemProducao().getItem();
Setup s = new Setup(itemOrigem, itemDestino, 0);
tempo = agenda.getListaSetup().get(s);
st.put(s, tempo);
SeqPeriodo seqOrigem = originalAllocation.getPeriodoInicial();
SeqPeriodo seqDestino = alocacoes.get(posicaoOrigem + 1).getPeriodoInicial();
if (seqOrigem != null && seqDestino != null) {
tempoPausa = seqDestino.getPeriodoIndex() - seqOrigem.getPeriodoIndex();
}
//tempo = agenda.getListaSetup().stream().filter(g -> g.getItemOrigem().equals(s.getItemOrigem())).filter(g -> g.getItemDestino().equals(s.getItemDestino())).collect(Collectors.toList()).get(0).getTempo();
}
}
originalAllocation.setTempoSetup(tempo);
originalAllocation.setDiferencaProximaProducao(tempoPausa);
originalAllocation.setSetupSelecionado(st);
}

Related

How to load Different adapters on same listview on Button Click-[Android]?

My requirement is to load different adapters on same listview using buttons to switch between adapters.
I've tried this
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
ImageButton fo,fl,ci,ani;
ListView l;
String flo[],foo[],cit[],an[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String flo[] = {"Rose","Lily","SunFlower","Lotus","Tulips"};
String foo[] = {"Maggie","Manchurian","Pizza","Burger","French Fries"};
String cit[] = {"New York","Los Angeles","Las Vegas","Texas","Manhattan"};
String an[] = {"Lion","Tiger","Penguins","Panda","Elephant"};
fo = (ImageButton)findViewById(R.id.imageButton2);
fl = (ImageButton)findViewById(R.id.imageButton);
ci = (ImageButton)findViewById(R.id.imageButton3);
ani = (ImageButton)findViewById(R.id.imageButton4);
l =(ListView)findViewById(R.id.listView);
fo.setOnClickListener(this);
fl.setOnClickListener(this);
ci.setOnClickListener(this);
ani.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.imageButton2)
{
food f = new food(this,foo);
l.setAdapter(f);
}
}
}
And I'm getting the following Error:
FATAL EXCEPTION: main
Process: com.example.nike.assignmentadapter, PID: 2565
java.lang.NullPointerException: Attempt to get length of null array
at com.example.nike.assignmentadapter.food.getCount(food.java:41)
at android.widget.ListView.setAdapter(ListView.java:487)
at com.example.nike.assignmentadapter.MainActivity.onClick(MainActivity.java:74)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Food class
public class food extends BaseAdapter implements View.OnClickListener {
String s[];
Context c;
Button li;
Button sh ;
int a[] = {R.drawable.fl1,R.drawable.fl2,R.drawable.fl3,R.drawable.fl4,R.drawable.fl5};
public food(Context context, String[] xperia) {
s = xperia;
c = context;
}
#Override
public int getCount() {
return s.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return s.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater ln = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = ln.inflate(R.layout.food, null);
TextView t= (TextView)v.findViewById(R.id.textView4);
ImageView i = (ImageView)v.findViewById(R.id.imageView4);
li = (Button)v.findViewById(R.id.like4);
sh = (Button)v.findViewById(R.id.share4);
String s1=s[position];
t.setText(s1);
i.setImageResource(a[position]);
li.setOnClickListener(this);
sh.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.like4)
{
AlertDialog.Builder builder= new AlertDialog.Builder(c);
builder.setTitle("Thanks Note");
builder.setMessage("Thank you for Liking ");
builder.setIcon(R.drawable.foo_t);
builder.setPositiveButton("To Share", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
Uri webpage = Uri.parse("http://www.sonymobile.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
c.startActivity(webIntent);
}
});
builder.show();
}
else
{
AlertDialog.Builder builder= new AlertDialog.Builder(c);
builder.setTitle("Thanks Note");
builder.setMessage("Thank you for Sharing on Your Facebook");
builder.setIcon(R.drawable.foo_t);
builder.setPositiveButton("To Facebook", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
Uri webpage = Uri.parse("https://www.facebook.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
c.startActivity(webIntent);
}
});
builder.show();
}
}
}
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton fo,fl,ci,ani;
ListView l;
String flo[],foo[],cit[],an[];
// these are your global variables available to access
// in any part of the coding. Currently they have no
// data assigned to them in other words they are null
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// here we have assigned data to the global variables declared
// outside of the OnCreate function and available to the onClick
// call.
// Using String flo[] = {John, Doe} means you are creating
// new local versions of the String arrays that are not available
// globally. Instead of assigning the data to the variables
// available globally, and to the onClick call, the data is given
// to the local variables only accessible in the OnCreate function
// function and available until OnCreate finishes.
flo = new String[]{"Rose","Lily","SunFlower","Lotus","Tulips"};
foo = new String[]{"Maggie","Manchurian","Pizza","Burger","French Fries"};
cit = new String[]{"New York","Los Angeles","Las Vegas","Texas","Manhattan"};
an = new String[]{"Lion","Tiger","Penguins","Panda","Elephant"};
fo = (ImageButton)findViewById(R.id.imageButton1);
l =(ListView)findViewById(R.id.listView1);
fo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.imageButton1)
{
System.out.println("foo: " + foo);
food f = new food(this,foo);
l.setAdapter(f);
}
}
#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);
}
}

Search view with firebase ui database android

Am a beginner in android.I have been trying to implement searchview for my firebaseDatabaseRecyclerAdapter. I have not been able to find the right logic to place in my onQueryTextChange method.
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(Users.class, R.layout.users_view, UsersViewHolder.class,query){
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
final String nameText = model.getNames();
final String statusText = model.getStatus();
final String phoneText = model.getPhone();
final String uidText = model.getUser_id();
final String emailText = model.getEmail();
viewHolder.setName(nameText);
viewHolder.setStatus(statusText);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, UserDataActivity.class);
intent.putExtra("name", nameText);
intent.putExtra("email", emailText);
intent.putExtra("phone", phoneText);
intent.putExtra("user_id", uidText);
intent.putExtra("status", statusText);
startActivity(intent);
}
});
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
List<Users> filteredList = filter(postList, newText);
updateList(filteredList);
return true;
}
private List<Users> filter (List<Users> pi, String query){
query = query.toLowerCase();
final List<Users> filteredList = new ArrayList<>();
for(Users users: pi){
final String text = users.getNames().toLowerCase();
if(text.contains(query)){
filteredList.add(users);
}
}
return filteredList;
}
public void updateList(List<Users> newList){
postList = new ArrayList<>();
postList.addAll(newList);
firebaseRecyclerAdapter.notifyDataSetChanged();
}
}

total item count from firebase recycler adapter in to textview

I need to get group member count from firebase recycleradapter but I don't know how to do that. As I am new in android please help to fix it.
My code is working fine to retrieve all the groups from DB but I am unable to get member count from the individual group and show them in each group.
Member count in each group:
public class JoinGroup extends AppCompatActivity {
RecyclerView mGrouplist;
LinearLayoutManager mLayoutManager;
DatabaseReference mDatabase;
String groupRef,username;
String sub_push_Key;
String userId;
String groupname,groupphoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_join_group);
mGrouplist = findViewById(R.id.grouplist);
mGrouplist.setHasFixedSize(true);
// mpostlist.setLayoutManager(new LinearLayoutManager(PostList.this));
mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setReverseLayout(false);
mLayoutManager.setStackFromEnd(false);
// Now set the layout manager and the adapter to the RecyclerView
mGrouplist.setLayoutManager(mLayoutManager);
mDatabase = FirebaseDatabase.getInstance().getReference().child("AllGroups");
userId=FirebaseAuth.getInstance().getCurrentUser().getUid();
}
#Override
public void onStart() {
super.onStart();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Groups..");
progressDialog.setMessage("Please wait..");
progressDialog.setCancelable(false);
progressDialog.show();
How can I use getItemCount method here:
final FirebaseRecyclerAdapter<GroupModel, JoinGroup.PostViewFolder> PSVF = new FirebaseRecyclerAdapter<GroupModel,JoinGroup.PostViewFolder>(
GroupModel.class,
R.layout.joingrouplayout,
JoinGroup.PostViewFolder.class,
mDatabase)
{
#Override
protected void populateViewHolder(final JoinGroup.PostViewFolder viewHolder, final GroupModel model, final int position) {
viewHolder.setGroupname(model.getGroupname());
viewHolder.setImageurl(getApplicationContext(),model.getImageurl());
progressDialog.cancel();
final String groupKey = getRef(position).getKey();
viewHolder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
groupRef = groupKey;
groupname=model.getGroupname();
groupphoto=model.getImageurl();
// Toast.makeText(JoinGroup.this,"MEMBER " +String.valueOf(count),Toast.LENGTH_LONG).show();
joinGroup();
}
});
}
};
mGrouplist.setAdapter(PSVF);
}
public static class PostViewFolder extends RecyclerView.ViewHolder {
View mview;
public PostViewFolder(View itemView) {
super(itemView);
mview = itemView;
}
public void setGroupname(String groupname) {
TextView namegroup = (TextView) mview.findViewById(R.id.groupname);
namegroup.setText(groupname);
}
public void setImageurl(Context ctx, String imageurl) {
ImageView groupimage = mview.findViewById(R.id.groupimage);
Glide.with(ctx)
.load(imageurl)
.into(groupimage);
}
}

FirebaseRecyclerAdapter with dynamic query from fragment callback

I have an activity that displays a list in a RecyclerView using a FirebaseRecyclerAdapter. The query needs to be dynamic - I need to tack a date onto the end of it. So I set up a DatePicker DialogFragment. The dialogfragment has an interface that gets implemented in the activity for it to receive the date back from the DatePicker. The date comes back ok. Trouble is, when I reattach a new adapter to the RecyclerView, the adapter code never runs. From walking through it with a debugger, the date is returned to the activity, then the code finishes in the fragment and the adapter is never reattached. So I'm left with a blank screen instead of a list of data.
Activity:
public class DailyScheduleActivity extends AppCompatActivity implements
HourlyTaskDialogFragment.HourlyTaskDialogListener,
DatePickerFragment.OnFragmentInteractionListener {
private DatabaseReference mDatabase;
private RecyclerView mProtocolRv;
private String protocolKey;
private LocalDate chosenDate;
private ProtocolRecyclerViewAdapter mProtocolAdapter;
private String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_schedule);
if (chosenDate == null) {
chosenDate = new LocalDate();
}
protocolKey = "daily/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + "_";
path = protocolKey + chosenDate;
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child(path);
FirebaseRecyclerOptions<Hour> options =
new FirebaseRecyclerOptions.Builder<Hour>()
.setQuery(query, Hour.class)
.build();
mProtocolRv = findViewById(R.id.rv_protocol);
mProtocolRv.setHasFixedSize(false);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mProtocolRv.setLayoutManager(mLayoutManager);
mProtocolAdapter = new ProtocolRecyclerViewAdapter(this, mDatabase, path, options);
mProtocolRv.setAdapter(mProtocolAdapter);
}
//####################################################################
//#### This is what runs after the date has been chosen. When this is
//#### finished, the dialogfragment finishes running. When control
//#### returns to the activity, the adapter never loads the data.
//####################################################################
#Override
public void onFragmentInteraction(String date) {
chosenDate = new LocalDate(date);
path = protocolKey + chosenDate;
Query query = mDatabase.child(path);
FirebaseRecyclerOptions<Hour> options =
new FirebaseRecyclerOptions.Builder<Hour>()
.setQuery(query, Hour.class)
.build();
final FirebaseRecyclerAdapter oldAdapter = (FirebaseRecyclerAdapter) mProtocolRv.getAdapter();
mProtocolAdapter = new ProtocolRecyclerViewAdapter(this, mDatabase, path, options);
mProtocolRv.setAdapter(mProtocolAdapter);
mProtocolAdapter.notifyDataSetChanged();
if (oldAdapter != null) {
//oldAdapter.cleanup(); - This can't run here because cleanup is not public so not sure what to do with it!
}
}
public static class ProtocolRecyclerViewAdapter extends FirebaseRecyclerAdapter<Hour, ProtocolRecyclerViewAdapter.HourHolder> {
private final DailyScheduleActivity mParentActivity;
private DatabaseReference mDb;
private String protocolUserDateKey;
ProtocolNonMalignant mProtocol = new ProtocolNonMalignant();
ProtocolRecyclerViewAdapter(DailyScheduleActivity parent, DatabaseReference db, String path, FirebaseRecyclerOptions<Hour> options) {
super(options);
mParentActivity = parent;
mDb = db;
protocolUserDateKey = path;
}
#Override
public void onDataChanged() {
super.onDataChanged();
}
#NonNull
#Override
public HourHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_protocol_row, parent, false);
return new HourHolder(view);
}
#Override
public void onBindViewHolder(final #NonNull HourHolder holder, final int position, final Hour currentHour) {
holder.mHourCheckBox.setText(currentHour.toString() + protocolUserDateKey);
}
class HourHolder extends RecyclerView.ViewHolder {
final IndeterminateCheckBox mHourCheckBox;
final ImageView mOpenTasks;
final TextView mHour;
HourHolder(View view) {
super(view);
mHourCheckBox = (IndeterminateCheckBox) view.findViewById(R.id.cb_hour_all);
mOpenTasks = (ImageView) view.findViewById(R.id.open_tasks);
mHour = (TextView) view.findViewById(R.id.hour);
}
}
}
#Override
protected void onStart() {
super.onStart();
mProtocolAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mProtocolAdapter.stopListening();
}
}
Datepicker DialogFragment:
public class DatePickerFragment extends DialogFragment {
private OnFragmentInteractionListener mListener;
private String chosenDate;
public DatePickerFragment() {}
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), dateSetListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener dateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int month, int day) {
chosenDate = view.getYear() + "-" + (view.getMonth()+1) + "-" + view.getDayOfMonth();
if (mListener != null) {
mListener.onFragmentInteraction(chosenDate);
}
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_date_picker, container, false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String date);
}
}

show GPS location on google map

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 calss:
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);

Resources