Android App that plays a sound daily [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How can I have an android app that plays a certain noise or sound at a certain time every day?
So far my code consists of a button that will play the noise upon click.

you have to create service
and in the service you play th song from the asset folder every 10:00 AM for example ..
the service will look like this :
MyService.java
import android.app.Service;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.format.Time;
import android.widget.Switch;
import android.widget.Toast;
import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
private int Annee;
private int Mois;
private int Jour;
private int Heure;
private int Minute;
boolean afficher=true;
private Handler customHandler = new Handler();
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Non implementé");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this,"Service demarré",Toast.LENGTH_LONG).show();
customHandler.postDelayed(updateTimerThread, 3000 );
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
onStop();
Toast.makeText(this,"Service arrété",Toast.LENGTH_LONG).show();
customHandler.removeCallbacks(updateTimerThread);
super.onDestroy();
}
public void onStop(){
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
final Calendar cal = Calendar.getInstance();
Annee = cal.get(Calendar.YEAR);
Mois = cal.get(Calendar.MONTH)%12+1;
Jour = cal.get(Calendar.DAY_OF_MONTH);
Heure=cal.get(Calendar.HOUR_OF_DAY)%24+1;
if(Heure==24)Heure=0;
Minute=cal.get(Calendar.MINUTE);
String min=Integer.toString(Minute);
String heure=Integer.toString(Heure);
String h=heure+":"+min;
java.text.SimpleDateFormat simpleTimeFormat = new java.text.SimpleDateFormat("HH:mm");
String h2 = null;
try {
h2 = simpleTimeFormat.format(simpleTimeFormat.parse(h));
} catch (ParseException e) {
e.printStackTrace();
}
String a, m, j;
j = Integer.toString(Jour);
m = Integer.toString(Mois);
a = Integer.toString(Annee);
String d = j + "/" + m + "/" + a;
java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat("dd/MM/yyyy");
String d2 = null;
try {
d2 = simpleDateFormat.format(simpleDateFormat.parse(d));
} catch (ParseException e) {
e.printStackTrace();
}
if (h2.equals("10:00")) {
if (afficher){
Intent intent =new Intent(getBaseContext(),AlertD.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("Cle",cur.getString(0));
getApplication().startActivity(intent);
afficher=false;}
}}
customHandler.postDelayed(this , 3000 );
};
}
bootCompleted.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Created by Mechalikh on 21/12/2014.
*/
public class BootCompleted extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)){
Intent serviceIntent= new Intent(context,MyService.class);
context.startService(serviceIntent);
}
}
}
alertD.java (the alarm dialog)
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class AlertD extends Activity {
MediaPlayer m;
public static String cle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m=new MediaPlayer();
cle =getIntent().getStringExtra("Cle");
final AlertDialog alertDialog =new AlertDialog.Builder(this).create();
alertDialog.setTitle("Votre rendez-vous");
alertDialog.setMessage("Vous avez un rendez-vous dans UNE HEURE !");
alertDialog.setButton("Arréter", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
m.stop();
AlertD.super.onBackPressed();
}
});
alertDialog.show();
Alarme();
}
private void Alarme() {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("Alarm.mp3");
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
}catch (Exception e){
e.printStackTrace();
}
}
}
for more see this tutorial
http://blog.vogella.com/2011/12/11/automatically-starting-services-in-android-after-booting/

Use alarm manager and schedule a repeating alarm .
Check this demo on repeating alarm schedule :
https://developer.android.com/training/scheduling/alarms.html

Use the Alarm Manager and set an inexact repeating alarm at your time of choice.

Related

Please help i got error on a null object reference. when i click confirm button [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My logcat here
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.barberbooking, PID: 13610
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.barberbooking.Model.Salon.getSalonId()'
on a null object reference
at com.example.barberbooking.Fragments.BookingStep4Fragment.lambda$null$0$BookingStep4Fragment(BookingStep4Fragment.java:260)
at com.example.barberbooking.Fragments.-$$Lambda$BookingStep4Fragment$4Ef790x-NNkmXHs_bv2YFCA2Nyk.onSuccess(Unknown
Source:4)
at com.google.android.gms.tasks.zzn.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
My Bookingstep4fragment
package com.example.barberbooking.Fragments;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.barberbooking.Common.Common;
import com.example.barberbooking.Database.CartDataSource;
import com.example.barberbooking.Database.CartDatabase;
import com.example.barberbooking.Database.CartItem;
import com.example.barberbooking.Database.LocalCartDataSource;
import com.example.barberbooking.Model.BookingInformation;
import com.example.barberbooking.Model.EventBus.ConfirmBookingEvent;
import com.example.barberbooking.Model.FCMResponse;
import com.example.barberbooking.Model.FCMsendData;
import com.example.barberbooking.Model.MyNotification;
import com.example.barberbooking.Model.MyToken;
import com.example.barberbooking.R;
import com.example.barberbooking.Retrofit.IFCMApi;
import com.example.barberbooking.Retrofit.RetrofitClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import dmax.dialog.SpotsDialog;
import io.paperdb.Paper;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
#SuppressWarnings("ALL")
public class BookingStep4Fragment extends Fragment {
CartDataSource cartDataSource;
CompositeDisposable compositeDisposable = new CompositeDisposable();
SimpleDateFormat simpleDateFormat;
Unbinder unbinder;
IFCMApi ifcmApi;
AlertDialog dialog;
#BindView(R.id.txt_booking_barber_text)
TextView txt_booking_barber_text;
#BindView(R.id.txt_booking_time_text)
TextView txt_booking_time_text;
#BindView(R.id.txt_salon_address)
TextView txt_salon_address;
#BindView(R.id.txt_salon_open_hours)
TextView txt_salon_open_hours;
#BindView(R.id.txt_salon_phone)
TextView txt_salon_phone;
#BindView(R.id.txt_salon_website)
TextView txt_salon_website;
#BindView(R.id.txt_salon_name)
TextView txt_salon_name;
#OnClick(R.id.btn_confirm)
void confirmBooking() {
dialog.show();
//DatabaseUtils.getAllCart(CartDatabase.getInstance(getContext()),
//this);
compositeDisposable.add(cartDataSource.getAllItemFromCart(Common.currentUser.getPhoneNumber())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<CartItem>>() {
#Override
public void accept(List<CartItem> cartItems) throws Exception {
String startTime = Common.convertTimeSlotToString(Common.currentTimeSlot);
String[] convertTime = startTime.split("-");
String[] startTimeConvert = convertTime[0].split(":");
int startHourInt = Integer.parseInt(startTimeConvert[0].trim());
int startMinInt = Integer.parseInt(startTimeConvert[1].trim()); // We get 00
Calendar bookingDateWithourHouse = Calendar.getInstance();
bookingDateWithourHouse.setTimeInMillis(Common.currentDate.getTimeInMillis());
bookingDateWithourHouse.set(Calendar.HOUR_OF_DAY, startHourInt);
bookingDateWithourHouse.set(Calendar.MINUTE, startMinInt);
//Create timestamp object and apply to BookingInformation
Timestamp timestamp = new Timestamp(bookingDateWithourHouse.getTime());
final BookingInformation bookingInformation = new BookingInformation();
bookingInformation.setCityBook(Common.city);
bookingInformation.setTimestamp(timestamp);
bookingInformation.setDone(false);
bookingInformation.setBarberId(Common.currentBarber.getBarberId());
bookingInformation.setBarberName(Common.currentBarber.getName());
bookingInformation.setCustomerName(Common.currentUser.getName());
bookingInformation.setCustomerPhone(Common.currentUser.getPhoneNumber());
bookingInformation.setSalonId(Common.currentSalon.getSalonId());
bookingInformation.setSalonAddress(Common.currentSalon.getAddress());
bookingInformation.setSalonName(Common.currentSalon.getName());
bookingInformation.setTime(new StringBuilder(Common.convertTimeSlotToString(Common.currentTimeSlot))
.append(" at ")
.append(simpleDateFormat.format(bookingDateWithourHouse.getTime())).toString());
bookingInformation.setSlot(Long.valueOf(Common.currentTimeSlot));
bookingInformation.setCartItemList(cartItems);
DocumentReference bookingDate = FirebaseFirestore.getInstance()
.collection("AllSalon")
.document(Common.city)
.collection("Branch")
.document(Common.currentSalon.getSalonId())
.collection("Barber")
.document(Common.currentBarber.getBarberId())
.collection(Common.simpleDateFormat.format(Common.currentDate.getTime()))
.document(String.valueOf(Common.currentTimeSlot));
bookingDate.set(bookingInformation)
.addOnSuccessListener((aVoid) -> {
resetStaticData();
getActivity().finish(); activity
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
//DatabaseUtils.clearCart(CartDatabase.getInstance(getContext()));
cartDataSource.clearCart(Common.currentUser.getPhoneNumber())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Integer>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onSuccess(Integer integer) {
addToUserBooking(bookingInformation);
}
#Override
public void onError(Throwable e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}).addOnFailureListener(e -> {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Toast.makeText(getContext(), "" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
}));
}
private void addToUserBooking(BookingInformation bookingInformation) {
final CollectionReference userBooking = FirebaseFirestore.getInstance()
.collection("User")
.document(Common.currentUser.getPhoneNumber())
.collection("Booking");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
Timestamp toDayTimeStamp = new Timestamp(calendar.getTime());
userBooking
.whereGreaterThanOrEqualTo("timestamp", toDayTimeStamp)
.whereEqualTo("done", false)
.limit(1)
.get()
.addOnCompleteListener(task -> {
if (task.getResult().isEmpty()) {
userBooking.document()
.set(bookingInformation)
.addOnSuccessListener(aVoid -> {
MyNotification myNotification = new MyNotification();
myNotification.setUid(UUID.randomUUID().toString());
myNotification.setTitle("New Booking");
myNotification.setContent("You have a new appoiment for customer hair care with " + Common.currentUser.getName());
myNotification.setRead(false); // We will only filter notification with 'read' is false on barber staff app
myNotification.setServerTimestamp(FieldValue.serverTimestamp());
FirebaseFirestore.getInstance()
.collection("AllSalon")
.document(Common.city)
.collection("Branch")
.document(Common.currentSalon.getSalonId())
.collection("Barber")
.document(Common.currentBarber.getBarberId())
.collection("Notifications")
.document(myNotification.getUid())
.set(myNotification)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
//First , get Token base on Barber id
FirebaseFirestore.getInstance()
.collection("Tokens")
.whereEqualTo("userPhone", Common.currentBarber.getUsername())
.limit(1)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful() && task.getResult().size() > 0) {
MyToken myToken = new MyToken();
for (DocumentSnapshot tokenSnapShot : task.getResult())
myToken = tokenSnapShot.toObject(MyToken.class);
FCMsendData sendRequest = new FCMsendData();
Map<String, String> dataSend = new HashMap<>();
dataSend.put(Common.TITLE_KEY, "New Booking");
dataSend.put(Common.CONTENT_KEY, "You have new booking from user "+ Common.currentUser.getName());
sendRequest.setTo(myToken.getToken());
sendRequest.setData(dataSend);
compositeDisposable.add(ifcmApi.sendNotification(sendRequest)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<FCMResponse>() {
#Override
public void accept(FCMResponse fcmResponse) throws Exception {
dialog.dismiss();
addToCalendar(Common.currentDate,
Common.convertTimeSlotToString(Common.currentTimeSlot));
resetStaticData();
getActivity().finish(); //Close Activity
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Log.d("NOTIFICATION_ERROR", throwable.getMessage());
addToCalendar(Common.currentDate,
Common.convertTimeSlotToString(Common.currentTimeSlot));
resetStaticData();
getActivity().finish(); //Close Activity
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}));
}
}
});
}
});
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
if (dialog.isShowing())
dialog.dismiss();
resetStaticData();
getActivity().finish(); // Close activity
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
});
}
private void addToCalendar(Calendar bookingDate, String startDate) {
String startTime = Common.convertTimeSlotToString(Common.currentTimeSlot);
String[] convertTime = startTime.split("-"); //Split ex : 9:00-10:00
//Get start time : get 9:00
String[] startTimeConvert = convertTime[0].split(":");
int startHourInt = Integer.parseInt(startTimeConvert[0].trim()); int startMinInt = Integer.parseInt(startTimeConvert[1].trim());
String[] endTimeConvert = convertTime[1].split(":");
int endHourInt = Integer.parseInt(endTimeConvert[0].trim());
int endMinInt = Integer.parseInt(endTimeConvert[1].trim());
Calendar startEvent = Calendar.getInstance();
startEvent.setTimeInMillis(bookingDate.getTimeInMillis());
startEvent.set(Calendar.HOUR_OF_DAY, startHourInt);
startEvent.set(Calendar.MINUTE, startMinInt);
Calendar endEvent = Calendar.getInstance();
endEvent.setTimeInMillis(bookingDate.getTimeInMillis());
endEvent.set(Calendar.HOUR_OF_DAY, endHourInt); hour
endEvent.set(Calendar.MINUTE, endMinInt);
SimpleDateFormat calendarDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String startEventTime = calendarDateFormat.format(startEvent.getTime());
String endEventTime = calendarDateFormat.format(endEvent.getTime());
addToDeviceCalendar(startEventTime, endEventTime, "Haircut Booking",
new StringBuilder("Haircut from ")
.append(startTime)
.append(" with ")
.append(Common.currentBarber.getName())
.append(" at ")
.append(Common.currentSalon.getName()).toString(),
new StringBuilder("Address: ").append(Common.currentSalon.getAddress()).toString());
}
private void addToDeviceCalendar(String startEventTime, String endEventTime, String title, String description, String location) {
SimpleDateFormat calendarDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
try {
Date start = calendarDateFormat.parse(startEventTime);
Date end = calendarDateFormat.parse(endEventTime);
ContentValues event = new ContentValues();
event.put(CalendarContract.Events.CALENDAR_ID, getCalendar(getContext()));
event.put(CalendarContract.Events.TITLE, title);
event.put(CalendarContract.Events.DESCRIPTION, description);
event.put(CalendarContract.Events.EVENT_LOCATION, location);
event.put(CalendarContract.Events.DTSTART, start.getTime());
event.put(CalendarContract.Events.DTEND, end.getTime());
event.put(CalendarContract.Events.ALL_DAY, 0);
event.put(CalendarContract.Events.HAS_ALARM, 1);
String timeZone = TimeZone.getDefault().getID();
event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);
Uri calendars;
if (Build.VERSION.SDK_INT >= 22)
calendars = Uri.parse("content://com.android.calendar/events");
else
calendars = Uri.parse("content://calendar/events");
Uri uri_save = getActivity().getContentResolver().insert(calendars, event);
Paper.init(getActivity());
Paper.book().write(Common.EVENT_URI_CACHE, uri_save.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
private String getCalendar(Context context) {
String gmailIdCalendar = "";
String projection[] = {"_id", "calendar_displayName"};
Uri calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = context.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()) {
String calName;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
do {
calName = managedCursor.getString(nameCol);
if (calName.contains("#gmail.com")) {
gmailIdCalendar = managedCursor.getString(idCol);
break; // Exit as soon as have io
}
} while (managedCursor.moveToNext());
managedCursor.close();
}
return gmailIdCalendar;
}
private void resetStaticData() {
Common.step = 0;
Common.currentTimeSlot = -1;
Common.currentSalon = null;
Common.currentBarber = null;
Common.currentDate.add(Calendar.DATE, 0);//Current date
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void setDataBooking(ConfirmBookingEvent event) {
if (event.isConfirm()) {
setData();
}
}
private void setData() {
txt_booking_barber_text.setText(Common.currentBarber.getName());
txt_booking_time_text.setText(new StringBuilder(Common.convertTimeSlotToString(Common.currentTimeSlot))
.append(" at ")
.append(simpleDateFormat.format(Common.currentDate.getTime())));
txt_salon_address.setText(Common.currentSalon.getAddress());
txt_salon_website.setText(Common.currentSalon.getWebsite());
txt_salon_name.setText(Common.currentSalon.getName());
txt_salon_open_hours.setText(Common.currentSalon.getOpenHours());
}
static BookingStep4Fragment instance;
public static BookingStep4Fragment getInstance() {
if(instance == null) ;
instance = new BookingStep4Fragment();
return instance;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ifcmApi = RetrofitClient.getInstance().create(IFCMApi.class);
//Apply format for date display on Confirm
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
dialog = new SpotsDialog.Builder().setContext(getContext()).setCancelable(false)
.build();
}
#Override
public void onDestroy() {
compositeDisposable.clear();
super.onDestroy();
{ if (dialog != null) { dialog.dismiss(); dialog = null; }}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View itemView = inflater.inflate(R.layout.fragment_bookingstep_four, container, false);
unbinder = ButterKnife.bind(this, itemView);
cartDataSource = new LocalCartDataSource(CartDatabase.getInstance(getContext()).cartDAO());
return itemView;
}
}
Check those lines
bookingInformation.setSalonId(Common.currentSalon.getSalonId());
.document(Common.currentSalon.getSalonId())
The error is clear
Attempt to invoke virtual method 'java.lang.String com.example.barberbooking.Model.Salon.getSalonId()' on a null object
You are sending salonId null

Countdown in an android notification

I'm trying to make a countdown in a notification for an application: When the application gets a notification, the notification has 20 seconds to disappear. Here is my code, but my application breaks as soon as it gets the notification, I hope somebody can help me, thanks:
package com.taxicell;
import java.util.ArrayList;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
/**
*Falta por descubrir
* #author sergio
*/
public class Notifica {
private Context context;
private String data[];
public timer timer;
public void Nueva(Context con,String dat){
Log.v("app", "nueva notificacion con los datos: "+dat);
context = con;
NotificationManager notificador =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Notification notifica=new Notification(R.drawable.taxicell,"TaxiCell !",System.currentTimeMillis());
Notification notifica=new Notification(R.drawable.taxicell,"TaxiCell !",30000);
notifica.defaults |= Notification.DEFAULT_SOUND;
notifica.defaults |= Notification.DEFAULT_LIGHTS;
notifica.flags |= Notification.FLAG_AUTO_CANCEL;
notifica.defaults |= Notification.DEFAULT_SOUND;
notifica.defaults |= Notification.DEFAULT_VIBRATE;
String mensajin="";
Intent intentoNotifica;
data=dat.split(",");
if(Validacion(dat)){
intentoNotifica=new Intent(context,Mensaje.class);
Bundle datos = new Bundle();
datos.putString("msj",dat );
datos.putInt("tipo", 0);
intentoNotifica.putExtras(datos);
mensajin="Solicitud de Servicio !";
}else{
intentoNotifica=new Intent(context,Mensaje.class);
Bundle datos = new Bundle();
datos.putString("msj",dat);
datos.putInt("tipo", 1);
intentoNotifica.putExtras(datos);
mensajin="Asignación de Saldo !";
}
Log.v("pm", "1");
timer = new timer();
Log.v("pr", "2");
timer.execute("ejecucion");
PendingIntent penIntent = PendingIntent.getActivity(context, 0, intentoNotifica,android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifica.setLatestEventInfo(context,"TaxiCell",mensajin, penIntent);
notificador.notify(1,notifica);
}
....
....
private class timer extends AsyncTask<String, Integer, Integer>{
#Override
protected void onPreExecute() {
Log.v("loop","0");
}
protected Integer doInBackground(String... urls) {
Log.v("loop","1");
int i=10;
while( i > 0) {
if(isCancelled()){break;}
else{
try {Thread.sleep(1000); }
catch (InterruptedException e) {}
publishProgress(i); //Actualizamos los valores
Log.v("loop","2 es: "+i);
i--;
}
}
return i;
}
#Override
protected void onProgressUpdate (Integer... valores) {
}
#Override
protected void onPostExecute(Integer res) {
rechazarServ();
}
}
}

Need to access method for 1 java class by another

I am trying to access a method from a java class by a another java class. I have created the object of the class and import the class into my java class but i am not able to access it my code.
package com.example.musicplayer;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.R.string;
import android.app.ListActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.provider.MediaStore.Audio.Playlists;
import android.test.suitebuilder.TestSuiteBuilder.FailedToCreateTests;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public static final String MEDIA_PATH = new String("/sdcard/");
private List<String> songs = new ArrayList<String>();
public MediaPlayer mp = new MediaPlayer();
private int currentPosition = 0;
public MediaPlayer getmp(){
return mp;
}
public void setmp(MediaPlayer mp){
this.mp = mp;
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
updateSongList();
}
private void updateSongList() {
// TODO Auto-generated method stub
File home = new File(MEDIA_PATH);
if(home.listFiles(new Mp3Filter()).length > 0){
for(File file: home.listFiles(new Mp3Filter())){
songs.add(file.getName());
}
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this, R.layout.song_item, songs);
setListAdapter(songList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
currentPosition = position;
playSong(MEDIA_PATH + songs.get(position));
//Toast.makeText(getApplicationContext(), songs.get(position).toString(), Toast.LENGTH_SHORT).show();
final String songName = songs.get(position).toString();
//final TextView textchange = (TextView) v.findViewById(R.id.current_song_name);
Intent in = new Intent(this, current_song.class);
in.putExtra("song_name", songName);
startActivity(in);
//Toast.makeText(getApplicationContext(), "End of Song List", Toast.LENGTH_SHORT).show();
//textchange.setText(songName);
}
private void playSong(String songPath) {
// TODO Auto-generated method stub
try{
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
auto_nextSong();
}
});
}
catch (Exception e) {
// TODO: handle exception
}
}
public void pause(){
mp.pause();
}
public void stop(){
mp.stop();
}
public void next(){
Toast.makeText(getApplicationContext(), "In Next()", Toast.LENGTH_SHORT).show();
if(currentPosition < songs.size()){
currentPosition = currentPosition + 1;
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
public void prv(){
if(currentPosition > songs.size()){
currentPosition = currentPosition - 1;
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
private void auto_nextSong() {
// TODO Auto-generated method stub
if(++currentPosition >= songs.size()){
currentPosition = 0;
Toast.makeText(getApplicationContext(), "End of Song List", Toast.LENGTH_SHORT).show();
}
else{
playSong(MEDIA_PATH + songs.get(currentPosition));
Toast.makeText(getApplicationContext(), "Next Song", Toast.LENGTH_SHORT).show();
}
}
}
from the above class i am trying to access pause() and stop()
this is my class where i am trying to access
package com.example.musicplayer;
import com.example.musicplayer.MainActivity;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class current_song extends Activity implements OnClickListener{
public MainActivity ma;
protected void onCreate(Bundle icicle, MainActivity ma) {
Bundle extra = getIntent().getExtras();
super.onCreate(icicle);
setContentView(R.layout.songplay_page);
if(extra != null){
String song_name = extra.getString("song_name");
TextView textchange = (TextView)findViewById(R.id.current_song_name);
textchange.setText(song_name);
textchange.setSelected(true);
}
//MainActivity ma = ((MainActivity)getApplicationContext());
//MediaPlayer mp = ma.getmp();
this.ma = ma;
Button btn_pause = (Button)findViewById(R.id.pause_btn);
btn_pause.setOnClickListener(this);
Button btn_next = (Button)findViewById(R.id.next_btn);
btn_next.setOnClickListener(this);
Button btn_prv = (Button)findViewById(R.id.prv_btn);
btn_prv.setOnClickListener(this);
Button btn_stop = (Button)findViewById(R.id.stop_btn);
btn_stop.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "In Onclick ()", Toast.LENGTH_SHORT).show();
switch(v.getId())
{
case R.id.pause_btn:
((MainActivity)ma).pause();
break;
case R.id.next_btn:
//ma.next();
break;
case R.id.prv_btn:
//ma.prv();
break;
case R.id.stop_btn:
((MainActivity)ma).stop();
break;
}
}
}
The concept is that i want to stop, pause the music which is playing. If my logic i wrong please guide me how to do it else please help me how to control my current music in Current music java class.
Please, move all your music playing code into Service. Activities don't work that way.
Consider the following:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
http://developer.android.com/reference/android/app/Service.html
I think You are new to android but no problem: See you can not call the functions of activity from any other class like this (Object.method();)
SO For this type of handling You Should Create a inner Handler class which extends Handler inside your MainActivity. and override onHandle(message msg){} method of it.
And When You start current_song activity pass this handler object in the intent.
And when you want to perform any task from your MainActivity (like stop, pause), pass messages through that handler like object.sendmessage(new msgObject("stop"));
And inside you onHandle() method call your stop or pause methods through diffrentiating command received from the message object.
like if(message's content == stop) MainActivity.this.stop();

Making remote server calls in an Android application

I've made an apache thrift server and I have a service which contains several functions.
I'm trying to figure out what is the best way to make calls to the remote server from my android application.
My problem is that I can't make calls from the MainActivity thread (the main thread) - and I need to use most of the remote functions in my main activity methods.
I tried to make a static class with a static member called "Server" equals to the server object, and I set it in another thread and then I tried to call it in the main thread (the main activity class) - but I had errors because of jumping from one thread to another..
To be more specified I want something like that:
public class MainActivity extends Activity {
private service.Client myService;
#Override
protected void onCreate(Bundle savedInstanceState) {
..
... Some stuff that define myService (In a new thread ofcourse) ...
}
...
private void MyFunc1() {
myService.Method1();
}
private void MyFunc2() {
myService.Method2();
}
private void MyFunc3() {
myService.Method3();
}
}
I've got a library for talking to REST APIs. Feel free to slice, dice, and re-use: https://github.com/nedwidek/Android-Rest-API
The code is BSD or GPL.
Here's how I use what I have (I've trimmed MainActivity a bit, hopefully not too much):
package com.hatterassoftware.voterguide.api;
import java.util.HashMap;
public class GoogleCivicApi {
protected final String baseUrl = "https://www.googleapis.com/civicinfo/us_v1/";
protected String apiKey = "AIzaSyBZIP5uY_fMF35SVVrytpKgHtppBbj8J0I";
public static final String DATE_FORMAT = "yyyy-MM-dd";
protected static HashMap<String, String> headers;
static {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
}
public String createUrl(String uri, HashMap<String, String> params) {
String url = baseUrl + uri + "?key=" + apiKey;
if (params != null) {
for (String hashKey: params.keySet()) {
url += hashKey + "=" + params.get(hashKey) + "&";
}
url = url.substring(0, url.length());
}
return url;
}
}
package com.hatterassoftware.voterguide.api;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hatterassoftware.restapi.GetTask;
import com.hatterassoftware.restapi.HttpReturn;
import com.hatterassoftware.restapi.RestCallback;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.models.Election;
public class ElectionsQuery extends GoogleCivicApi implements RestCallback {
GetTask getTask;
ElectionCallback callback;
final String TAG = "ElectionQuery";
public ElectionsQuery(ElectionCallback callback) {
String url = this.createUrl("elections", null);
this.callback = callback;
Log.d(TAG, "Creating and executing task for: " + url);
getTask = new GetTask(url, this, null, null, null);
getTask.execute();
}
#Override
public void onPostSuccess() {
Log.d(TAG, "onPostSuccess entered");
}
#Override
public void onTaskComplete(HttpReturn httpReturn) {
Log.d(TAG, "onTaskComplete entered");
Log.d(TAG, "httpReturn.status = " + httpReturn.status);
if (httpReturn.content != null) Log.d(TAG, httpReturn.content);
if (httpReturn.restException != null) Log.d(TAG, "Exception in httpReturn", httpReturn.restException);
JsonParser parser = new JsonParser();
JsonElement electionArrayJson = ((JsonObject)parser.parse(httpReturn.content)).get("elections");
Log.d(TAG, electionArrayJson.toString());
Gson gson = new GsonBuilder().setDateFormat(GoogleCivicApi.DATE_FORMAT).create();
Election[] elections = gson.fromJson(electionArrayJson.toString(), Election[].class);
callback.retrievedElection(elections);
}
}
package com.hatterassoftware.voterguide;
import java.util.Calendar;
import java.util.List;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.hatterassoftware.voterguide.api.ElectionsQuery;
import com.hatterassoftware.voterguide.api.VoterInfoQuery;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.callbacks.VoterInfoCallback;
import com.hatterassoftware.voterguide.api.models.Election;
import com.hatterassoftware.voterguide.api.models.VoterInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity implements ElectionCallback, VoterInfoCallback {
private ProgressBar mProgressBar;
public Button submit;
public Spinner state;
public Spinner election;
public EditText address;
public EditText city;
public EditText zip;
private int count=0;
private Object lock = new Object();
private static final String TAG = "MainActivity";
public static final String VOTER_INFO = "com.hatterassoftware.voterguide.VOTER_INFO";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.home_progressBar);
Resources res = getResources();
SharedPreferences mPrefs = getApplicationSharedPreferences();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
try {
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled(Context.LOCATION_SERVICE)) {
gpsButton.setClickable(false);
}
} catch(Exception e) {
Log.d(TAG, e.getMessage(), e);
gpsButton.setClickable(false);
gpsButton.setEnabled(false);
}
submit = (Button) findViewById(R.id.submit);
submit.setClickable(false);
submit.setEnabled(false);
state = (Spinner) findViewById(R.id.state);
election = (Spinner) findViewById(R.id.election);
address = (EditText) findViewById(R.id.streetAdress);
city = (EditText) findViewById(R.id.city);
zip = (EditText) findViewById(R.id.zip);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doSubmit();
}
});
gpsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLocate();
}
});
// Let's check for network connectivity before we get down to business.
if (Utils.isNetworkAvailable(this, true)) {
// Show the disclaimer on first run.
if(mPrefs.getBoolean("firstRun", true)) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setCancelable(false);
alert.setTitle(res.getString(R.string.welcome));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, null);
TextView alertContents = (TextView) layout.findViewById(R.id.custom_dialog_text);
alertContents.setMovementMethod(LinkMovementMethod.getInstance());
alertContents.setText(Html.fromHtml(res.getString(R.string.welcome_dialog_text)));
alert.setView(alertContents);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences mPrefs = getApplicationSharedPreferences();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("firstRun", false);
editor.commit();
dialog.dismiss();
retrieveElections();
}
});
alert.show();
} else {
retrieveElections();
}
}
}
#Override
public void onResume() {
super.onResume();
// Let's check for network connectivity before we get down to business.
Utils.isNetworkAvailable(this, true);
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))) {
Toast.makeText(this, "GPS is not available", 2).show();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
gpsButton.setClickable(false);
}
}
public SharedPreferences getApplicationSharedPreferences() {
Context mContext = this.getApplicationContext();
return mContext.getSharedPreferences("com.hatterassoftware.voterguide", MODE_PRIVATE);
}
private void showSpinner() {
synchronized(lock) {
count++;
mProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideSpinner() {
synchronized(lock) {
count--;
if(count < 0) { // Somehow we're trying to hide it more times than we've shown it.
count=0;
}
if (count == 0) {
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
public void retrieveElections() {
Log.d(TAG, "Retrieving the elections");
showSpinner();
ElectionsQuery query = new ElectionsQuery(this);
}
#Override
public void retrievedElection(Election... elections) {
Log.d(TAG, "Retrieved the elections");
hideSpinner();
for (int i=0; i<elections.length; i++) {
Log.d(TAG, elections[i].toString());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, elections);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) this.findViewById(R.id.election);
spinner.setAdapter(arrayAdapter);
}
}

Problems with drawing on osm

I'm developing a little applicattion for androd to display
gps location witha bitmap. I used some example codes with google mmaps, but i haveto make it with maps forge. unfortunatelly i havent found any example codes or anything about how to write this drawing operation Colud anybody hel me?
My code is:
package hu.uniobuda.nik.k44hvx;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.mapsforge.android.maps.GeoPoint;
import org.mapsforge.android.maps.ItemizedOverlay;
import org.mapsforge.android.maps.MapActivity;
import org.mapsforge.android.maps.MapController;
import org.mapsforge.android.maps.MapView;
import org.mapsforge.android.maps.MapViewMode;
import org.mapsforge.android.maps.Overlay;
import org.mapsforge.android.maps.OverlayItem;
import org.mapsforge.android.maps.Projection;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Geocoder;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
import android.widget.Toast;
public class Night_WatchActivity extends MapActivity {
MapView mapview;
public MapController mc;
private LocationManager locman;
private LocationListener loclis;
List<Overlay> mapOverlays;
static Drawable pointDefaultMarker;
MapOverlay pointsOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mapview = new MapView(this);
mapview.setClickable(true);
mapview.setBuiltInZoomControls(true);
mapview.setMapViewMode(MapViewMode.MAPNIK_TILE_DOWNLOAD);
// mapview.setMapViewMode(MapViewMode.CANVAS_RENDERER);
//mapview.setMapFile("/sdcard/budapest.map");
mc = mapview.getController();
mc.setCenter(new GeoPoint(47.499619,19.046406));
mc.setZoom(17);
setContentView(mapview);
locman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// loclis = new GPSLocationListener();
if(pointDefaultMarker==null){pointDefaultMarker = getResources().getDrawable(R.drawable.kepont);}
mapOverlays = mapview.getOverlays();
pointsOverlay = new MapOverlay(pointDefaultMarker);
mapOverlays.add(pointsOverlay);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loclis);
}
#Override
protected void onResume() {
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 10, loclis);
super.onResume();
}
#Override
protected void onPause() {
locman.removeUpdates(loclis);
super.onPause();
}
private class GPSLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if(location!=null){
GeoPoint gp = new GeoPoint(
(int)(location.getLatitude()*1E6),
(int)(location.getLongitude()*1E6));
OverlayItem item = new OverlayItem(gp,null,null);
pointsOverlay.justOneOverlay(item);
mc.setZoom(16);
mc.setCenter(gp);
mapview.invalidate();
String address = PointToLocation(gp);
Toast.makeText(getBaseContext(),
address,
Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public String PointToLocation(GeoPoint hely){
String s ="";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> adresses = gcd.getFromLocation(
hely.getLatitudeE6() / 1E6,
hely.getLongitudeE6()/1E6 , 1);
if(adresses.size()>0){
for(int i = 0; i < adresses.get(0).getMaxAddressLineIndex(); i++){
s += adresses.get(0).getAddressLine(i) + " ";
}
}
}catch(IOException exception){ exception.printStackTrace();}
return s;
}
}
class MapOverlay extends ItemizedOverlay<OverlayItem>{
private GeoPoint toDraw;
public GeoPoint getToDraw() {
return toDraw;
}
public void setToDraw(GeoPoint toDraw) {
this.toDraw = toDraw;
}
Paint p = new Paint();
private ArrayList<OverlayItem> overlays = new ArrayList<OverlayItem>();
private boolean drawLines = false;
public MapOverlay(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
populate();
}
public void addOverlay(OverlayItem overlay){
overlays.add(overlay);
populate();
}
public void justOneOverlay(OverlayItem newOverlay){
overlays.clear();
addOverlay(newOverlay);
}
#Override
protected OverlayItem createItem(int i) {
return overlays.get(i);
}
#Override
public int size() {
return overlays.size();
}
public boolean isDrawLines() {
return drawLines;
}
public void setDrawLines(boolean drawLines) {
this.drawLines = drawLines;
}
#Override
protected void drawOverlayBitmap(Canvas canvas, Point drawPosition,
Projection projection, byte drawZoomLevel) {
Point ScreenPoint = new Point();
mapview.getProjection().toPixels(toDraw, ScreenPoint);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.kepont);
canvas.drawBitmap(bmp,ScreenPoint.x,ScreenPoint.y-24, null);
}
}
}

Categories