nullpointer exception on web service call - Java for Android App Development

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!

Related

[Q] How to use Timer to restart record video for every preset interval time?

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....
**

app not sending sms

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);
}
}

Adding custom apps to an app switcher panel

I am currently working on an App Switcher with the ability to also add custom apps in the app switcher. So, I already got the recent apps loader built. This is the code for this part of the app:
Code:
public class Corners_RecentApps extends Activity {
private ArrayList<PanelItemDetail> rowItems = null;
private ListView listView;
private ArrayList<String> packageName = null;
private ArrayList<String> className = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
if(rightpanel){
overridePendingTransition(R.anim.left_slide_in_fast, 0);
setContentView(R.layout.right_side_panel);
}
else
{
overridePendingTransition(R.anim.right_slide_in_fast, 0);
setContentView(R.layout.activity_left_side_panel);
}
ImageView imgbtn = (ImageView) findViewById(R.id.transparentbackground);
ImageView panelbg = (ImageView) findViewById(R.id.panelbackground);
listView = (ListView)findViewById(R.id.panelcontents);
packageName = new ArrayList<String>();
className = new ArrayList<String>();
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = am.getRecentTasks(30, 0);
rowItems = new ArrayList<PanelItemDetail>();
PackageManager pacMgr = getPackageManager();
for (ActivityManager.RecentTaskInfo recentTask : tasks) {
try {
rowItems.add(new PanelItemDetail(pacMgr.getApplicationIcon(recentTask.origActivity.getPackageName())));
packageName.add(recentTask.origActivity.getPackageName());
className.add(recentTask.origActivity.getClassName());
Log.d("#@#", "getPackageName = " + recentTask.origActivity.getPackageName());
Log.d("#@#", "getClassName = " + recentTask.origActivity.getClassName());
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
String itembg = myPreference.getString("itembg_list", "");
if(itembg.equals("defaults"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_default, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("dark"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_dark, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("light"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_light, rowItems);
listView.setAdapter(adapter);
}
else
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_none, rowItems);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
try{
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
Intent taskintent = getPackageManager().getLaunchIntentForPackage(packageName.get(postion).toString());
startActivity(taskintent);
if(rightpanel){
overridePendingTransition(R.anim.right_slide_in, R.anim.zoom_out);
}
else
{
overridePendingTransition(R.anim.left_slide_in, R.anim.zoom_out);
}
finish();
}
catch (NullPointerException fail) {
Toast.makeText(getApplicationContext(), "!", Toast.LENGTH_SHORT).show();
}
}
});
SharedPreferences panelbgpref = PreferenceManager.getDefaultSharedPreferences(this);
String panelbgset = panelbgpref.getString("panelbg_list", "");
if(panelbgset.equals("light"))
{
panelbg.setImageResource(R.drawable.panelbg_light);
}
else
{
panelbg.setImageResource(R.drawable.panelbg);
}
imgbtn.setOnClickListener(new View.OnClickListener(){
[user=439709]@override[/user]
public void onClick(View v) {
if(v.getId() ==R.id.transparentbackground){
moveTaskToBack(true);
finish();
}
}
});
}
Now I want to let the users define in the app settings up to 3 own apps that should be shown on every moment.
How should I do that?
Thank you

Loading a new fragment from an OnClick set in asyncTask

I have a fragment, which contains a button that when pressed loads a new fragment. The new fragment runs an async task to populate a listview with data.
I am running into trouble, trying to load a new fragment from the onClick. The problem is I can not get the getFragmentManager();
My async task looks like this:
Code:
public class GetStyleStatisticsJSON extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
android.support.v4.app.Fragment Fragment_one;
public GetStyleStatisticsJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Analyzing Statistics");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourStyleStatistics);
//make array list for beer
final List<StyleInfo> tasteList = new ArrayList<StyleInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String style = jsonArray.getJSONObject(i).getString("style");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
int count = i + 1;
style = count + ". " + style;
//create object
StyleInfo tempTaste = new StyleInfo(style, rate, beerID);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
StyleInfoAdapter adapter1 = new StyleInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
StyleInfo o=(StyleInfo)arg0.getItemAtPosition(arg2);
String bID = o.id;
//todo: add onclick for fragment to load
FragmentManager man= (Activity)c.getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
can not resolve method FragmentManager() is the error I am receiving
Hi,
To be able to call getFragmentManager() or getSupportFragmentManager() you'll need to use FragmentActivity, so what I would do is:
1. Make sure the activity that calls the asycTask is a FragmentActivity.
2. Pass this actvity to the asycTask.
Something like: (asyncTask method)
setActivity(Activity activity)
{
fm = activity.getFragmentManager();
}
mrsegev said:
Hi,
To be able to call getFragmentManager() or getSupportFragmentManager() you'll need to use FragmentActivity, so what I would do is:
1. Make sure the activity that calls the asycTask is a FragmentActivity.
2. Pass this actvity to the asycTask.
Something like: (asyncTask method)
setActivity(Activity activity)
{
fm = activity.getFragmentManager();
}
Click to expand...
Click to collapse
thats the problem, I launch the asyncTask from a fragment....
Oh! So you'll access your activity like this:
getActivity().getFragmentManager();

FC when using interface to launch new fragment form listView

I have an async task that loads a list view of items. I am currently trying to set the onClick to load a new fragment with an "id" that is being retrieved from the list item that is clicked. I have no errors in my code that the Android Studio shows me.
When I run the app and click on the item in the list view I get this FC:
02-13 19:49:56.813 20334-20334/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.ReadJSONResult$1.onItemClick(ReadJSONResult.java:140)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
02-13 19:50:42.112 20864-20870/? E/jdwp﹕ Failed sending reply to debugger: Broken pipe
line 140 in ReadJSONResult is:
listenerBeer.onArticleSelected(idToSend);
That line is part of this whole onClick:
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
All the code for ReadJSONResult is:
public class ReadJSONResult extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public ReadJSONResult(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//code for on click
OnArticleSelectedListener listenerBeer;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
//end code for onClick
@override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Searching Beer Cellar");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(android.R.id.list);
//make array list for beer
final List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
//get long and latt
String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);
//add beer to list
beerList.add(thisBeer);
}
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(c ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
//todo: all the get functions go here
private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get style information
private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get location data
private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get brewery information
//get style information
private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get glass
private String GetBeerGlassFromJSON(int position, JSONObject json ) {
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
BeerSearchAdapter is:
public class BeerSearchAdapter extends ArrayAdapter<BeerData> {
Context context;
int layoutResourceId;
List<BeerData> data = null;
public BeerSearchAdapter(Context context, int layoutResourceId, List<BeerData> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerBreweryNameList);
holder.txtTitle = (TextView)row.findViewById(R.id.beerNameList);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
BeerData beer = data.get(position);
holder.txtTitle.setText(beer.beerName);
holder.txtBrewery.setText(beer.beerBreweryName);
return row;
}
static class beerHolder
{
TextView txtBrewery;
TextView txtTitle;
}
}
My Search.java where the interface comes form is here:
public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {
private ListView lv;
View v;
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
v = inflater.inflate(R.layout.activity_search, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Search");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//todo: code body goes here
// Inflate the layout for this fragment
return v;
}
@override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
Log.d("click", "inside the on create");
//inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
searchView.setIconified(false);
searchView.setOnQueryTextListener(this);
}
public boolean onQueryTextSubmit (String query) {
//toast query
//make json variables to fill
// url to make request
String url = "myURL";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
new ReadJSONResult(getActivity()).execute(jsonUrl);
return false;
}
@override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
@override
public void onArticleSelected(String b){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
//todo: set to beer fragment
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", b);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
Let me know if you need any other code, I am stomped on this and could use a second pair of eyes. Thanks.

Categories

Resources