hi guys
i am in the process of implementing this menu but it is not updating the speed of my sensor
my code snipet is
here are my global variables
Code:
private static final int MENU_SLOW = 0;
private static final int MENU_NORMAL = 1;
private static final int MENU_FAST = 2;
private static final int MENU_EXIT = -1;
int ROTATION_SPEED = 3;
private static SensorManager mySensorManager;
private boolean sersorrunning;
private myCompassView myCompassView;
/** Called when the activity is first created.*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myCompassView = (myCompassView)findViewById(R.id.mycompassview);
mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> mySensors = mySensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
if(mySensors.size() > 0){
mySensorManager.registerListener(mySensorEventListener, mySensors.get(0), ROTATION_SPEED);
sersorrunning = true;
Toast.makeText(this, "POINT the Needle to N for NORTH", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "COMPASS not Initilised", Toast.LENGTH_LONG).show();
sersorrunning = false;
finish();
}
}
here is my sensor speed code
Code:
if(mySensors.size() > 0){
mySensorManager.registerListener(mySensorEventListener, mySensors.get(0), ROTATION_SPEED);
sersorrunning = true;
Toast.makeText(this, "POINT the Needle to N for NORTH", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "COMPASS not Initilised", Toast.LENGTH_LONG).show();
sersorrunning = false;
finish();
}
and here is how i am trying to change the variable ROTATION_SPEED
Code:
public boolean onOptionsItemSelected (MenuItem item){
if (item.getItemId() == MENU_SLOW){
ROTATION_SPEED = SensorManager.SENSOR_DELAY_UI;
Toast.makeText(this, "Speed changed to SystemPreffered", Toast.LENGTH_SHORT).show();
}else if (item.getItemId() == MENU_NORMAL){
ROTATION_SPEED = SensorManager.SENSOR_DELAY_NORMAL;
Toast.makeText(this, "Speed changed to NORMAL", Toast.LENGTH_SHORT).show();
}else if (item.getItemId() == MENU_FAST){
ROTATION_SPEED = SensorManager.SENSOR_DELAY_FASTEST;
Toast.makeText(this, "Speed changed to FAST", Toast.LENGTH_SHORT).show();
}else if (item.getItemId() == MENU_EXIT){
android.os.Process.killProcess(android.os.Process.myPid());
Toast.makeText(this, "Exiting application...", Toast.LENGTH_SHORT).show();
}
return false;
}
ANY HELP WILL BE VERY MUCH APPRECIATED
thanks
shiraz
So I see you're setting the variable ROTATION_SPEED, but where are you ever using that to actually set the speed?
here is im changing the variable value
Code:
public boolean onOptionsItemSelected (MenuItem item){
if (item.getItemId() == MENU_SLOW){
ROTATION_SPEED = SensorManager.SENSOR_DELAY_UI;
Toast.makeText(this, "Speed changed to SystemPreffered", Toast.LENGTH_SHORT).show();
}else if (item.getItemId() == MENU_NORMAL){
ROTATION_SPEED = SensorManager.SENSOR_DELAY_NORMAL;
Toast.makeText(this, "Speed changed to NORMAL", Toast.LENGTH_SHORT).show();
}else if (item.getItemId() == MENU_FAST){
ROTATION_SPEED = SensorManager.SENSOR_DELAY_FASTEST;
Toast.makeText(this, "Speed changed to FAST", Toast.LENGTH_SHORT).show();
}else if (item.getItemId() == MENU_EXIT){
android.os.Process.killProcess(android.os.Process.myPid());
Toast.makeText(this, "Exiting application...", Toast.LENGTH_SHORT).show();
}
return false;
}
You're assigning a new value to ROTATION_SPEED, but never telling the sensor service that it's changed. I'm not familiar with the SensorManager class, but I think you have to re-call registerListener with the new value for the changes to be applied.
thanks dude
thats awesom
sorted this out ::
just aded the sensor manager after every new value given to ROTATION_SPEED
cheers
Related
Can someone tell me how can i use something like a timer to start a video recording interval process for a period of time (eg: 5mins) then restarts to record another set of 5min video until the user intervene to stop the process..
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
public static boolean recordingStatus;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
private MediaRecorder mediaRecorder;
private static int encodingStatus;
private static String videoResolution;
private static String fileFormat;
private static boolean audioStatus;
private static int timeInterval;
private static final String TAG = "Exception";
public boolean startRecording(){
try {
encodingStatus = Tab1Activity.encodingPref;
videoResolution = Tab1Activity.videoResPref;
fileFormat = Tab1Activity.fileFormatPref;
audioStatus = Tab2Activity.audioPref;
timeInterval = Tab2Activity.timeIntervalPref;
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.reconnect();
ServiceCamera.unlock();
}
catch(Exception e){
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(timeInterval);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(encodingStatus);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
String[] separatedRes = videoResolution.split("x");
separatedRes[0];
separatedRes[1];
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.reset();
mediaRecorder.release();
recordingStatus = false;
}
}
someone please help...
Thread
you are writing a service, right? typically this service should also implement a thread. inside this thread you could implement your timer feature.
-didi
But the thing is i don't know how to even implement or even write the timer codes into my serviceRecording.java file... Can you help me on this?
i recently did this with a widget. i used an AlarmManager to set repeating alarms that would broadcast an intent that could be caught by a broadcastReciever and then do something... im at work now but when i get home i can try to give you some sample code.
you sure this needs to be a service? a service is something that is doing work but not at the forefront of the ui. its unseen. do you want your recording to be done in the background? i only ask because i did some research on services and found that they cannot be a BroadCastReciever and thus cannot use the AlarmManager that i said would work.
as far as a timer i have not looked into that particular class...
sorry i was no help. but if you decide to use the AlarmManager i could help
Someone recently recommended using these code to implement the sort of interval recording i wanted with this code below but i don't seems to know how to implement these codes into my current code could someone lend me a hand how how can can i implement the appropriate codes into my code to make my code work? Or is there simpler way to achieve "dynamic" (with Preferences) interval recording?
Code:
final ServiceRecording recording = ....
final AtomicBoolean started = new AtomicBoolean(false);
ScheduledExecutorService executor = Executors.newScheduledExecutor(1);
executor.scheduleAtFixedRate(new Runnable() { public void run() { //only stop if we have started if(started.get()) { recording.stop(); } else { started.set(true); } recording.start(); }}, 5, 5, TimeUnit.MINUTES);
My serviceRecording
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
public static boolean recordingStatus;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
{
startRecording();
//new Timer().scheduleAtFixedRate(task, after, interval);
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
private MediaRecorder mediaRecorder;
private static int encodingType;
private static String videoResolution;
private static String fileFormat;
private static boolean audioStatus;
private static int timeInterval;
//timeInterval = Integer.parseInt(Tab2Activity.timeIntervalPref);
private static final String TAG = "Exception";
public boolean startRecording(){
try {
SharedPreferences prefs_tab1 = getSharedPreferences("tab1", Context.MODE_PRIVATE);
SharedPreferences prefs_tab2 = getSharedPreferences("tab2", Context.MODE_PRIVATE);
encodingType = Integer.parseInt(prefs_tab1.getString("EncodingPref", "1"));
//******************************************************************************
String stringRes = CameraTest.resParams;
String[] entriesValues = stringRes.split(",");
String rawResolution = entriesValues[0];
videoResolution = prefs_tab1.getString("ResolutionPref", rawResolution);
//******************************************************************************
fileFormat = prefs_tab1.getString("FileFormatPref", ".mp4");
//******************************************************************************
audioStatus = prefs_tab2.getBoolean("AudioPref", true); //false
//******************************************************************************
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.reconnect();
ServiceCamera.unlock();
}
catch(Exception e){
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
if(!audioStatus)
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
}
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
if(!audioStatus)
{
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
}
mediaRecorder.setVideoEncoder(encodingType);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
String[] separatedRes = videoResolution.split("x");
mediaRecorder.setVideoSize(Integer.parseInt(separatedRes[0]),Integer.parseInt(separatedRes[1]));
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.reset();
mediaRecorder.release();
recordingStatus = false;
}
Any progress on this? I was thinking you coukd have a private inner class in your service class that handles the timing with an AlarmManager
Im on my phone right now but something along these lines...
Private Class MyTimer extends BroadcastReciever {
//Implement onRecieve
Public void onRecieve(Context c, Intent i) {
//if intent matches 5min alarm
//start recording
}
Then in your service you can make a recurring alarm using the AlarmManager class to signal your inner class to start or even stop the recording based on what intent you pass it
When i get home ill right a bit more code as an example
From something awesome
i wrote a bit of code. its incomplete. and you will have to maybe mess with making the AlarmServicer class either static, public, private or something to make it work. basicly your service creates a five minute alarm directed at the AlarmServicer that it catches in the onRecieve() method and then starts your recording again and then creates another alarm directed at itself. you can use some if/then logic to change wether or not the alarm will be created again based on if the user wants it to stop or not. and then to get it going again the service would invoke the setOneTimeAlarm method again.
Code:
public class ServiceRecording extends Service {
// NEW CONSTANT
public static final String FIVE_MIN_ALARM = "FIVE_MIN_ALARM";
public static final int FIVE_MINUTES = 300;
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
//set the first alarm
AlarmServicer.setOneTimeAlarm(AlarmServicer.class, this, ServiceRecording.FIVE_MINUTES , ServiceRecording.FIVE_MIN_ALARM);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { }
public boolean startRecording() {}
public void stopRecording() {}
// NEW CODE
private static class AlarmServicer extends BroadcastReciever {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(ServiceRecording.FIVE_MIN_ALARM)) {
ServiceRecording.startRecording();
//set another five min alarm
setOneTimeAlarm(AlarmServicer.class, this, ServiceRecording.FIVE_MINUTES, ServiceRecording.FIVE_MIN_ALARM;
}
}
private static void setOneTimeAlarm(java.lang.Class<?> cls, Context context, int seconds, String action) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, cls);
intent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (seconds * 1000), pendingIntent);
}
}
}
and i believe that you need to register the inner class as a broadcastreciever in the android manifest.
**
** this most likely wont work....
**
i am trying to send Message at a scheduled time in my app
here is my activty
Code:
case R.id.bSubmitborrowitem:
String b = mDateDisplay.getText().toString();
String c = mTimeDisplay.getText().toString();
String a = b + "-" + c;
String d = tv1.getText().toString();
String e = "hello";
Toast.makeText(getApplicationContext(), a,
Toast.LENGTH_LONG).show();
//*************coding of sms start here***********************//
// TODO Auto-generated method stub
String pick_no;
pick_no=d;
if(d.length()!=0&& e.length()!=0)
{
Intent b_Intent=new Intent();
b_Intent.setAction(MyAlarmService.ACTION);
b_Intent.putExtra("RQS", MyAlarmService.RQS_STOP_SERVICE);
Intent myIntent=new Intent(this,MyAlarmService.class);
myIntent.setAction(Intent.ACTION_SEND);
Bundle bundle=new Bundle();
bundle.putString("sms_number", d);
bundle.putCharSequence("body", e);
bundle.putString("contact_choose", d);
myIntent.putExtras(bundle);
pi=PendingIntent.getService(this, 0, myIntent,1);
pn.add(PendingIntent.getBroadcast(this, 0, b_Intent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK));
pn.add(pi);
AlarmManager alarm_manager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_MONTH, mDay);
calendar.set(Calendar.MONTH, mMonth);
calendar.set(Calendar.YEAR, mYear);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, mminute);
calendar.clear();
alarm_manager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pi);
Toast.makeText(this, "your msg will be sending at "+hour+" hours and "+mminute+" min", Toast.LENGTH_LONG).show();
//*************coding of sms start here***********************//
And here is Service class
Code:
public class MyAlarmService extends Service {
String To,message_body,pick;
NotifyServiceReceiver notifyServiceReceiver;
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;
SmsManager sms;
[user=439709]@override[/user]
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
[user=439709]@override[/user]
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();
notifyServiceReceiver = new NotifyServiceReceiver();
}
[user=439709]@override[/user]
public void onDestroy() {
// TODO Auto-generated method
super.onDestroy();
Toast.makeText(getBaseContext(), "destroy",
Toast.LENGTH_SHORT).show();
}
private void CancelService() {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION);
registerReceiver(notifyServiceReceiver, intentFilter);
Bundle bundle=intent.getExtras();
Toast.makeText(this, "service Started", Toast.LENGTH_LONG).show();
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
[user=439709]@override[/user]
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
registerReceiver(new BroadcastReceiver(){
[user=439709]@override[/user]
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
sms = SmsManager.getDefault();
sms.sendTextMessage(bundle.getString("sms_number"), null,(String) bundle.getCharSequence("body") , sentPI, deliveredPI);
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_launcher, "Notification!",System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Exercise of Notification!";
String notificationText = "Message Notification";
PendingIntent myIntent1 = PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW, People.CONTENT_URI), 0);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context,notificationTitle,notificationText, myIntent1);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
Toast.makeText(this, "your msg will be sending at ", Toast.LENGTH_LONG).show();
return START_STICKY;
}
[user=439709]@override[/user]
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
public class NotifyServiceReceiver extends BroadcastReceiver{
[user=439709]@override[/user]
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int rqs = arg1.getIntExtra("RQS", 0);
if (rqs == RQS_STOP_SERVICE){
stopSelf();
}
}
}
}
everything is fine.. there is no error in code. even the toast come up when i press the submit button..
but it is not sending message .. plzz help
Edit1 app is sending sms now but not on schedule time . it is sending sms instantly
I know this may be a silly question but did you add the proper permissions to your manifest for sending sms?
zalez said:
I know this may be a silly question but did you add the proper permissions to your manifest for sending sms?
Click to expand...
Click to collapse
yes i already added the permission.. check the edit in the main post. it is sending sms but not at schedule time.
This is how I did mine:
MainActivity button click event (or some other event):
Code:
//Now let's set up the alarm
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(MeterMaid.this,
0, intent, 0);
// We want the alarm to go off 30 seconds from now. Calendar.MINUTE
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(SECONDS_OR_MINUTES, (picker.getValue() - REMINDER_OFFSET));
// Schedule the alarm!
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
And my service to receive the alarm:
Code:
public class AlarmReceiver extends BroadcastReceiver
{
private int SIMPLE_NOTFICATION_ID;
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent)
{
NotificationManager manger = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.meter128, "expiration warning", System.currentTimeMillis());
//intent.putExtra("Ringtone", Uri.parse("file:///sdcard/test.mp3"));
intent.putExtra("vibrationPatern", new long[] { 200, 300 });
intent.putExtra("Testtone", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
notification.setLatestEventInfo(context, "Time is up!", "Your time is about to expire!!", contentIntent);
notification.flags = Notification.FLAG_INSISTENT;
notification.sound = (Uri) intent.getParcelableExtra("Testtone"); //Uri.parse("file:///sdcard/test.mp3"); //
notification.vibrate = (long[]) intent.getExtras().get("vibrationPatern");
// The PendingIntent to launch our activity if the user selects this notification
manger.notify(SIMPLE_NOTFICATION_ID, notification);
}
}
Code:
public void sendMessage(View view) {
// Do something in response to button
try
{
final Intent intent = new Intent(this, DisplayMessageActivity.class);
Thread thread = new Thread()
{
[user=439709]@override[/user]
public void run() {
try {
while(true) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// request.addProperty("ArtistId", "-1");
// request.addProperty("StartId", "1");
// request.addProperty("CatId", "1");
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
final HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
Object result = (Object)envelope.getResponse();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
// Toast.makeText(this, result.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception: " + e.getMessage());
}
}
I keep getting it at androidHttpTransport.call(SOAP_ACTION, envelope);
private static final String SOAP_ACTION = "http://tempuri.org/GetCountries";
private static final String METHOD_NAME = "GetCountries";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://168.187.121.70/WSJAWW/service.asmx";
krikor1 said:
Code:
public void sendMessage(View view) {
// Do something in response to button
try
{
final Intent intent = new Intent(this, DisplayMessageActivity.class);
Thread thread = new Thread()
{
[user=439709]@override[/user]
public void run() {
try {
while(true) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// request.addProperty("ArtistId", "-1");
// request.addProperty("StartId", "1");
// request.addProperty("CatId", "1");
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
final HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
Object result = (Object)envelope.getResponse();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
// Toast.makeText(this, result.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception: " + e.getMessage());
}
}
I keep getting it at androidHttpTransport.call(SOAP_ACTION, envelope);
private static final String SOAP_ACTION = "http://tempuri.org/GetCountries";
private static final String METHOD_NAME = "GetCountries";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://168.187.121.70/WSJAWW/service.asmx";
Click to expand...
Click to collapse
Have you declared an edittext in a layout? maybe you need to change the id of this line.
EditText editText = (EditText) findViewById(R.id.edit_message);, or maybe connection parameters are wrong...or you miss something...post the logcat!
i've an ExpandableListView, where i can select different radiobutton choice in a radiobuttongroup. My problem: not all radiobuttons are selected...the behaviour is random.
this is my code
Code:
void prepareMainList(String data)
{
Document doc;
NodeList nl;
newsNotificationData = new ArrayList<Map<String, String>>(); //set this struct in other case
groupData = new ArrayList<Map<String, String>>();
childData = new ArrayList<List<Map<String, String>>>();
if ((data.compareTo("") != 0) && (data != null) )
{
doc = parser.getDomElement(data); // getting DOM element
nl = doc.getElementsByTagName(KEY_GROUP);
categoryList = new HashSet<CategoryClass>();
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++)
{
// creating new HashMap
Map<String, String> curGroupMap = new HashMap<String, String>();
Map<String, String> curNewsMap = new HashMap<String, String>();
Element el = (Element) nl.item(i);
CategoryClass myCat = new CategoryClass();
myCat.id = parser.getValue(el, "id");
myCat.name = parser.getValue(el, KEY_NAME);
myCat.subCategory = new HashSet<TournamentClass>();
// adding each child node to HashMap key => value
curGroupMap.put(CATEGORY, parser.getValue(el, KEY_NAME));
Log.d("test", "category id added: " + myCat.id);
// adding HashList to ArrayList
groupData.add(curGroupMap);
//notification
curNewsMap.put("CID_" + myCat.id, getValueFromCategory(myCat.id));
newsNotificationData.add(curNewsMap);
NodeList ls = el.getElementsByTagName("girone");
//Log.d("test", "getDataFromWebService get children count : " + ls.getLength());
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
for (int j = 0; j < ls.getLength(); j++)
{
Element elc = (Element) ls.item(j);
Map<String, String> curChildMap = new HashMap<String, String>();
TournamentClass myTournament = new TournamentClass();
myTournament.id = elc.getAttribute("id");
myTournament.name = parser.getValue(elc, KEY_CHILD_NAME);
curChildMap.put(TOURNAMENT, parser.getValue(elc, KEY_CHILD_NAME));
children.add(curChildMap);
myCat.subCategory.add(myTournament);
//notification
curNewsMap.put("TID_" + myTournament.id, "-1");
newsNotificationData.get(i).put("TID_" + myTournament.id, getValueFromTournament(myTournament.id));
}
childData.add(children);
categoryList.add(myCat);
//newsNotificationData.add(curNewsMap);
}
}
catList = (ExpandableListView) findViewById(R.id.expandableSettings);
catList.setClickable(true);
catList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Log.d("test", "GROUP PRESSED");
return false;
}
});
// Set up our adapter
mAdapter = new SimpleExpandableListAdapter(
this,
groupData,
R.layout.settings_header,
new String[] { CATEGORY, TOURNAMENT },
new int[] { R.id.settingsCatTitle, android.R.id.text2 },
childData,
R.layout.settings_child,
new String[] { CATEGORY, TOURNAMENT },
new int[] { android.R.id.text1, R.id.settingsSubTitle }
){
@Override
public View getGroupView (final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
//final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
final View v = super.getGroupView(groupPosition, isExpanded, convertView, parent);
//Log.d("test", "get tournament selected");
TextView tv = (TextView)v.findViewById( R.id.settingsCatTitle );
String catSel = tv.getText().toString();
//get objects
String groupName = groupData.get(groupPosition).get("CATEGORY");
final CategoryClass myCat = getCategoryFromName(groupName);
RadioGroup groupNN;
// *** Gestisce l'header della categoria ***
groupNN = (RadioGroup) v.findViewById(R.id.radioGroupNN);
groupNN.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
//Log.d("Header chk", "id" + checkedId);
if(!isDataLoaded) return;
for (int i = 0, l = group.getChildCount(); i < l; i++)
{
RadioButton xRadio = (RadioButton) group.getChildAt(i);
xRadio.setBackgroundResource(R.drawable.setting_gradient_off);
xRadio.setTextColor(R.drawable.settings_gradient_on);
}
//-----change data to send
String notifValue = "0";
//get checked value
switch (checkedId)
{
case R.id.button_News:
notifValue = "0";
break;
case R.id.button_Notif:
notifValue = "1";
break;
case R.id.button_All:
notifValue = "2";
break;
case R.id.button_no:
notifValue = "-1";
break;
default:
break;
}
//set graphics on selected radio button
RadioButton radio = (RadioButton) v.findViewById(checkedId);
if (radio != null)
{
//radio.setTextSize(30);
// Marco Moscatelli 28/11/2013 - imposto il check a true
//radio.setChecked(true);
radio.setBackgroundResource(R.drawable.settings_gradient_on);
radio.setTextColor(Color.LTGRAY);
}
updateNewsNotificationCenter(groupPosition, myCat.id, null, notifValue);
isDataLoaded = false;
//Log.d("test", "------END SET CATEGORY------- ");
}
});
//-----data to send changed
isDataLoaded = false;
//set default schema
//String defaultbtnValue = null;
String defaultbtnValue = newsNotificationData.get(groupPosition).get("CID_" + myCat.id);
//Log.d("test", "check current cat id : "+ myCat.id);
RadioButton defNNRadio = null;
//Log.d("test", "defaultbtnValue : "+ defaultbtnValue);
if (defaultbtnValue == null)defaultbtnValue = "-1";
switch(Integer.parseInt(defaultbtnValue))
{
case 0:
defNNRadio = (RadioButton) v.findViewById(R.id.button_News);
break;
case 1:
defNNRadio = (RadioButton) v.findViewById(R.id.button_Notif);
break;
case 2:
defNNRadio = (RadioButton) v.findViewById(R.id.button_All);
break;
case -1:
defNNRadio = (RadioButton) v.findViewById(R.id.button_no);
break;
default:
break;
}
//set default button
for (int i = 0, l = groupNN.getChildCount(); i < l; i++)
{
RadioButton xRadio = (RadioButton) groupNN.getChildAt(i);
xRadio.setChecked(false);
xRadio.setBackgroundResource(R.drawable.setting_gradient_off);
xRadio.setTextColor(R.drawable.settings_gradient_on);
}
if (defNNRadio != null)
{
defNNRadio.setChecked(true);
defNNRadio.setBackgroundResource(R.drawable.settings_gradient_on);
defNNRadio.setTextColor(Color.LTGRAY);
}
return v;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
Log.d("test", "getChildView");
RadioGroup groupNN;
// *** gestisco i gironi della categoria ***
groupNN = (RadioGroup) v.findViewById(R.id.radioGroupNN_child);
//get objects
String groupName = groupData.get(groupPosition).get("CATEGORY");
final CategoryClass myCat = getCategoryFromName(groupName);
Map<String, String> childName = childData.get(groupPosition).get(childPosition);
final TournamentClass myTournament = getTournamentFromName(groupName, childName.get("TOURNAMENT"));
groupNN.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
//Log.d("Item chk", "id" + checkedId);
if(!isDataLoaded) return;
Log.d("test", "------INIT SET TOURNAMENT------- : " + myTournament.id);
for (int i = 0, l = group.getChildCount(); i < l; i++)
{
RadioButton xRadio = (RadioButton) group.getChildAt(i);
xRadio.setBackgroundResource(R.drawable.setting_gradient_off);
xRadio.setTextColor(color.SettingsTextOffColor);
}
//-----change data to send
String notifValue = "0";
//get checked value
switch (checkedId)
{
case R.id.button_News:
notifValue = "0";
break;
case R.id.button_Notif:
notifValue = "1";
break;
case R.id.button_All:
notifValue = "2";
break;
case R.id.button_no:
notifValue = "-1";
break;
default:
break;
}
//Get Tournament and keep id of it...after save notification mode in a struct and send all on POSTS
RadioButton radio = (RadioButton) v.findViewById(checkedId);
if (radio != null)
{
// Marco Moscatelli 28/11/2013 - Imposto il check a true
//radio.setChecked(true);
//group.check(radio.getId());
// end
radio.setBackgroundResource(R.drawable.settings_gradient_on);
radio.setTextColor(Color.LTGRAY);
}
//prepare data
updateNewsNotificationCenter(groupPosition, myCat.id, myTournament.id, notifValue);
Log.d("test", "------END SET TOURNAMENT------- ");
}
//}
});
//set default schema
String defaultbtnValue = newsNotificationData.get(groupPosition).get("TID_" + myTournament.id);
RadioButton defNNRadio = null;
//Log.d("test", "defaultbtnValue : "+ defaultbtnValue);
if (defaultbtnValue == null)defaultbtnValue = "-1";
switch(Integer.parseInt(defaultbtnValue))
{
case 0:
defNNRadio = (RadioButton) v.findViewById(R.id.button_News);
break;
case 1:
defNNRadio = (RadioButton) v.findViewById(R.id.button_Notif);
break;
case 2:
defNNRadio = (RadioButton) v.findViewById(R.id.button_All);
break;
case -1:
defNNRadio = (RadioButton) v.findViewById(R.id.button_no);
break;
}
for (int i = 0, l = groupNN.getChildCount(); i < l; i++)
{
RadioButton xRadio = (RadioButton) groupNN.getChildAt(i);
xRadio.setChecked(false);
xRadio.setBackgroundResource(R.drawable.setting_gradient_off);
xRadio.setTextColor(color.SettingsTextOffColor);
}
//set default schema
if (defNNRadio != null)
{
defNNRadio.setChecked(true);
defNNRadio.setBackgroundResource(R.drawable.settings_gradient_on);
defNNRadio.setTextColor(Color.LTGRAY);
}
//isDataLoaded = true;
return v;
}
thanks in advance
I have created a questionnaire in the beginning of the app in order to base a user model off the answers chosen. The values of the chosen options are stored as Shared Preferences as shown below. With the data retrieved I am then trying to tag a Google map with certain tags based on the answers chosen. The issue I am encountering is that of reading the stored Shared Preference values across the different activities, from the Question2 Activity, to that of the Map Activity (code below). Any pointers on how to solve the *context* conflict would be greatly appreciated.
Question2 Activity:
Code:
public class Question2 extends Activity{
RadioButton q2a1,q2a2,q2a3;
Button btn2;
public static final String MY_PREF = "MyPreferences";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.activity_question2, null);
return v;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
q2a1 = (RadioButton) findViewById(R.id.q2a1);
q2a2 = (RadioButton) findViewById(R.id.q2a2);
q2a3 = (RadioButton) findViewById(R.id.q2a3);
btn2 = (Button) findViewById(R.id.q2_button);
btn2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
SharedPreferences prefernces = getSharedPreferences(MY_PREF, 0);
SharedPreferences.Editor editor = prefernces.edit();
if (q2a1.isChecked()){
editor.putInt("answer_value2", 1);
editor.commit();
}
if (q2a2.isChecked()){
editor.putInt("answer_value2", 2);
editor.commit();
}
if (q2a3.isChecked()){
editor.putInt("answer_value2", 3);
editor.commit();
}else {
editor.putInt("answer_value2", 0);
editor.commit();
}
editor.commit();
Intent intent = new Intent(getApplicationContext(), Question3.class);
startActivity(intent);
}
});
}
}
Map Activity:
Code:
public class MapActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapLayout)).getMap();
map.setMyLocationEnabled(true);
SharedPreferences preferences = getSharedPreferences(Question2.MY_PREF,MODE_PRIVATE);
int q1answer = preferences.getInt("answer_value", 0);
int q2answer = preferences.getInt("answer_value2", 0);
int q3answer = preferences.getInt("answer_value3", 0);
if(q1answer == 1){
//method
}
if(q1answer == 2){
//method
}
if(q1answer == 3){
//method
}
if(q2answer == 1){
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(HEALTHSHOP).title("Health Shop").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grasy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MINT).title("Mint").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 2){
Toast.makeText(getApplicationContext(), "Your result is " + q2answer, Toast.LENGTH_SHORT).show();
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(JUBILEE).title("Jubilee").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grassy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 3){
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(PASTIZZERIA).title("Pastizerria").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(BURGERKING).title("Burger King").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
if(q3answer == 1){
//implementation
}if(q3answer == 2){
//implementation
}if(q3answer == 3){
//implementation
}if(q3answer == 4){
//implementation
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
Use this
create this class in your package
Code:
public class SharedPrefence{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyPreferences";
// Answers (make variable public to access from outside)
public static final String KEY_ANSWER_TWO = "answer_value2";
//similarly other answers tag can be added(this is the key of preference)
// Constructor
public SharedPrefence(Context context) {
_context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create Answer.
* */
public void createAnswer(int ans) {
// Storing name in pref
editor.putInt(KEY_ANSWER_TWO, ans);
// commit changes
editor.commit();
}
public int getAnswer(String tag,int default) {
return pref.getString(tag, default);
}
}
now create an activity and initialise this class in the starting with the activity context.
next call the create answer method of this class and you are done.
also no need to create sharedprefence in each activity.
and it's even better if you create only one activity and use ViewPager for all questions.you can google for it.
And if this was useful click on thanks below.
:victory::victory::victory::victory: