I am trying to create an instance of AlarmManager with pendingIntent, but I cannot understand where I am going wrong.
My android app implements a customer class (eventHandler) which is Serializable. I have converted the object of my class to a byte array in order to pass it as an extra into my alarm intent. The app starts and works fine, reading the byte array and creating the alarm intent in my object with pendingintent. The problem occurs when I try to start a second activity, get the object of my class (which is serializable) and then convert it to a byte array to be passed as an extra.
The code that is a problem is:
Intent intent = new Intent(getActivity(), EventWeatherActivity.class);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bos);
**out.writeObject(event);**
out.flush();
byte[] data = bos.toByteArray();
intent.putExtra(EXTRA_MESSAGE, data);
out.writeObject(event); - is the line causing the error. But event which belongs to eventHandler (Serializable) did run when the app began, so why is it an issue when I am starting another activity?
The error that I am getting is:
W/System.err: java.io.NotSerializableException: android.app.PendingIntent
2020-03-21 10:26:43.440 7646-7646/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1240)
2020-03-21 10:26:43.440 7646-7646/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1604)
2020-03-21 10:26:43.440 7646-7646/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1565)
2020-03-21 10:26:43.443 7646-7646/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1488)
2020-03-21 10:26:43.443 7646-7646/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1234)
2020-03-21 10:26:43.443 7646-7646/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:354)
2020-03-21 10:26:43.444 7646-7646/com.example.scrollingtext W/System.err: at com.example.scrollingtext.EventFragment$1.onItemClick(EventFragment.java:122)
In my customer class (eventHandler event):
Intent alarmIntent = new Intent(context, NotificationReceiver.class);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(this);
out.flush();
byte[] data = bos.toByteArray();
alarmIntent.putExtra("imw.notification", data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
final int id = (int) System.currentTimeMillis();
pendingIntent = PendingIntent.getBroadcast(context, id, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
I think the problem is that your EventHandler class contains pendingIntent field, which cannot be serialized. You should separate your EventHandler class and describe there only fields you want to serialize. Also please provide the whole listing of your EventHandler class to see what else can cause the problem. Your current listing is not full.
Yes, pendingIntent cannot be serialized, but weirdly when the app initially runs, pendingIntent runs fine within eventHandler and an alarm IS created successfully. The problem comes about when I try to then get a copy of that eventHandler object and convert it into a byte array as above so that I can pass the eventHandler object to my second activity. If I comment out the creation of a pendingIntent and alarm, the app runs fine passing the eventHandler object between activities.
So, as mentioned above I seperated the Alarm creation into a "Notification" class:
public class Notifications implements Serializable {
private PendingIntent pendingIntent;
private int notification_period;
private String notification_interval;
private Activity activity;
private Context context;
private AlarmManager manager;
private eventHandler event;
public Notifications(eventHandler event, int notification_period, String notification_interval, Activity activity, Context context)
{
this.notification_interval = notification_interval;
this.notification_period = notification_period;
this.activity = activity;
this.context = context;
this.event = event;
}
public void setAlarm()
{
manager = (android.app.AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
if(notification_period != -1 && !notification_interval.equals("-1")) {
Intent alarmIntent = new Intent(context, NotificationReceiver.class);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(event);
out.flush();
byte[] data = bos.toByteArray();
alarmIntent.putExtra("imw.notification", data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
final int id = (int) System.currentTimeMillis();
pendingIntent = PendingIntent.getBroadcast(context, id, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if(notification_interval.equals("minute")) {
manager.setRepeating(android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), notification_period*60*1000, pendingIntent);
}
else if(notification_interval.equals("hour")) {
manager.setRepeating(android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() * android.app.AlarmManager.INTERVAL_HOUR * notification_period, android.app.AlarmManager.INTERVAL_HOUR, pendingIntent);
}
else if(notification_interval.equals("day")) {
manager.setRepeating(android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() * android.app.AlarmManager.INTERVAL_DAY * notification_period, android.app.AlarmManager.INTERVAL_DAY, pendingIntent);
}
Log.d("alarm_set", notification_period + " " + notification_interval);
}
else {
if(pendingIntent != null)
{
manager.cancel(pendingIntent);
Log.d("alarm_cancelled", pendingIntent.toString());
}
}
}
}
..and now with the above, in my eventHandler class:
public void processEvent() {
try {
dailyWeather dWeather = new dailyWeather(raw_weather);
hWeather = new hourlyWeather(raw_weather);
tag = event.get("Tag");
start_date = event.get("Start Date");
start_time = event.get("Start Time");
end_time = event.get("End Time");
location = event.get("Location");
lat = event.get("Lat");
lng = event.get("Lng");
notification_period = Integer.parseInt(event.get("Notification Period"));
notification_interval = event.get("Notification Interval");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate fromDate = LocalDate.parse(start_date, formatter);
LocalDateTime localTime_fromTime = LocalDateTime.parse(start_date + " " + start_time, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));
LocalDateTime localTime_toTime = LocalDateTime.parse(start_date + " " + end_time, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));
if (DAYS.between(LocalDate.now(), fromDate) > 7) {
bActive = false;
}
else if(LocalDateTime.now().isAfter(localTime_toTime)) {
Log.d("Expired", "End time");
bActive = false;
bExpired = true;
bContainsHours = true;
}
else {
bActive = true;
weather = dWeather.getWeather(start_date);
if (!start_time.equals("0")) {
bContainsHours = true;
}
if(notification_period != -1 && !notification_interval.equals("")) {
notificationManager = new Notifications(this, notification_period, notification_interval, activity, context);
notificationManager.setAlarm();
}
}
}catch(Exception e)
{
Log.d("Err", "Error appearing here");
e.printStackTrace();
}
}
now the app crashed when I run it from the beginning, complaining that AlarmManager is not serialized.
java.io.NotSerializableException: android.app.AlarmManager
2020-03-22 12:22:50.371 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1240)
2020-03-22 12:22:50.371 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1604)
2020-03-22 12:22:50.372 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1565)
2020-03-22 12:22:50.373 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1488)
2020-03-22 12:22:50.373 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1234)
2020-03-22 12:22:50.373 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1604)
2020-03-22 12:22:50.373 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1565)
2020-03-22 12:22:50.374 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1488)
2020-03-22 12:22:50.374 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1234)
2020-03-22 12:22:50.374 16593-16593/com.example.scrollingtext W/System.err: at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:354)
2020-03-22 12:22:50.374 16593-16593/com.example.scrollingtext W/System.err: at com.example.scrollingtext.Notifications.setAlarm(Notifications.java:47)
2020-03-22 12:22:50.377 16593-16593/com.example.scrollingtext W/System.err: at com.example.scrollingtext.eventHandler.processEvent(eventHandler.java:98)
Related
I am new to android.I want to use my service for fetching the Json data from server.when I open my app then all works fine but when I exit my app or when my device go to sleep then there is a Json exception.how can I make my service run every-time in background. Please guide for solving this error.
error:-
E/agdghdgdgdrgrdgrdg: dgdgd
W/System.err: java.net.UnknownHostException: Unable to resolve host
"podgier-
woman.000webhostapp.com": No address associated with hostname
W/System.err: at
java.net.InetAddress.lookupHostByName(InetAddress.java:457)
W/System.err: at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
W/System.err: at
java.net.InetAddress.getAllByName(InetAddress.java:215)
W/System.err: at
org.apache.http.conn.DefaultClientConnectionOperator.openConnection
(DefaultClientConnectionOperator.java:137)
W/System.err:at org.apache.http.impl.conn.AbstractPoolEntry.open
(AbstractPoolEntry.java:164)
W/Systemerr:at
org.apache.http.impl.conn.AbstractPooledConnAdapter.open
(AbstractPooledConnAdapter.java:119)
W/System.err: at
org.apache.http.impl.client.DefaultRequestDirector.execute
(DefaultRequestDirector.java:360)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:555)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:487)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:465)
W/System.err: at com.grover.jsonp.JSONParser.makeHttpRequest
(JSONParser.java:62)
W/System.err:at com.grover.jsonp.BackgroundService$gro.doInBackground
(BackgroundService.java:50)
W/System.err: at
com.grover.jsonp.BackgroundService$gro.doInBackground
(BackgroundService.java:41)
W/System.err:at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err:at java.util.concurrent.FutureTask.run
(FutureTask.java:237)
W/System.err: at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1112)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor
$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: android.system.GaiException:
android_getaddrinfo
failed: EAI_NODATA (No address associated with hostname)
W/System.err: at libcore.io.Posix.android_getaddrinfo(Native
Method)
W/System.err: at
libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
W/System.err: at
java.net.InetAddress.lookupHostByName(InetAddress.java:438)
W/System.err: ... 18 more
E/Buffer Error: Error converting result java.io.IOException: Attempted
read
on closed stream.
BackgroundService.java
public class BackgroundService extends Service
{
public BackgroundService(){
}
private static String url ="https://podgier-woman.000webhostapp.com/table.php";
JSONParser jParser = new JSONParser();
ArrayList<String> bcv;
class gro extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
java.util.List<NameValuePair> pr = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url, "GET", pr);
bcv = new ArrayList<String>();
try {
JSONArray code = json.getJSONArray("code");
Log.d("list :",code.toString());
for (int i = 0; i < code.length(); i++) {
JSONObject c = code.getJSONObject(i);
bcv.add(c.getString("name"));
// adding each child node to HashMap key => value
// adding contact to contact list
JSONArray p = null;
}
}catch(JSONException e){
}
return null;
}
protected void onPostExecute(String file_url) {
Log.v("sdg","sgfdg"+record.idName);
if(record.idName < bcv.size()){
int xx= bcv.size() - record.idName;
Intent intent = new Intent(BackgroundService.this, record.class);
PendingIntent pIntent = PendingIntent.getActivity(BackgroundService.this, (int) System.currentTimeMillis(),intent, 0);
Log.d("SGsgzxv","dfgzdvv");
Notification n = new Notification.Builder(getApplicationContext())
.setContentTitle("View "+xx+" updated data")
.setContentText("data pending ")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.mipmap.ic_launcher, "call", pIntent)
.addAction(R.mipmap.ic_launcher, "More", pIntent)
.addAction(R.mipmap.ic_launcher, "and more", pIntent)
.build();
Uri so = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
n.sound = so;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0,n);
}
record.idName = bcv.size();
bcv.clear();
}
}
private static final String TAG = "BackgroundService";
private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");
#Override
public void onCreate() {
super.onCreate();
Log.v(TAG, "in onCreate()");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
int counter = intent.getExtras().getInt("counter");
Log.v(TAG, "in onStartCommand(), counter = " + counter +
", startId = " + startId);
new Thread(myThreads, new ServiceWorker(counter), "BackgroundService")
.start();
return START_STICKY;
}
class ServiceWorker implements Runnable
{
private int counter = -1;
public ServiceWorker(int counter) {
this.counter = counter;
}
public void run() {
final String TAG2 = "ServiceWorker:" + Thread.currentThread().getId();
// do background processing here...
try {
Log.e(TAG2, "sleeping for 5 seconds. counter = " + counter);
while(true)
{
Thread.sleep(9000);
Log.e("agdghdgdgdrgrdgrdg","dgdgd");
new gro().execute();
}
} catch (InterruptedException e) {
Log.e(TAG2, "... sleep interrupted");
}
}
}
#Override
public void onDestroy()
{
}
#Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "in onBind()");
return null;
}
}
I don't recommend using a background service for such purposes. I know from experience that we are never sure that such a service will not be destroyed by the system.
To perform tasks (periodic, single) I recommend using Firebase Job Dispatcher. In my opinion, this is a more reliable mechanism when it comes to doing background work.
Here is an example of use, given by me: https://stackoverflow.com/a/44489327/8119117
FileNotFoundException occur when capture the screen and save the screenshot into SDCard after power off the cellular phone, It seems that the server to flash the buffer into disk has disconnected during shutdown, but anyone can help me explain more detail? The output error message is:
02-24 14:03:28.180 27412 27412 D TakeScreenshotService:
#isFloatingBallVisible() ,visible = false
02-24 14:03:29.402 27412 10176 E SaveImageInBackgroundTask: error in
SaveImageInBackgroundData,
exception:java.io.FileNotFoundException:
/storage/emulated/0/Pictures/Screenshots/Screenshot_20170224-140329.jpg:
open failed: ENOTCONN (Transport endpoint is not connected)
02-24 14:03:29.526 27412 27412 D TakeScreenshotService: onUnbind,
isMultiScrenshot:false intent:Intent {
cmp=com.android.systemui/.screenshot.TakeScreenshotService }
The corresponding codes are:
#Override
protected SaveImageInBackgroundData doInBackground(SaveImageInBackgroundData... params) {
Log.d(TAG, "doInBackground:");
if (params.length != 1) return null;
if (isCancelled()) {
params[0].clearImage();
params[0].clearContext();
return null;
}
// By default, AsyncTask sets the worker thread to have background thread priority, so bump
// it back up so that we save a little quicker.
Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Context context = params[0].context;
Bitmap image = params[0].image;
Resources r = context.getResources();
try {
// Create screenshot directory if it doesn't exist
mScreenshotDir.mkdirs();
// media provider uses seconds for DATE_MODIFIED and DATE_ADDED, but milliseconds
// for DATE_TAKEN
long dateSeconds = mImageTime / 1000;
// Save
boolean compressRet = true;
OutputStream out = new FileOutputStream(mImageFilePath);
if(PhoneStatusBar.LEUI_ENABLE) {
compressRet = image.compress(Bitmap.CompressFormat.JPEG, 100, out);
} else {
compressRet = image.compress(Bitmap.CompressFormat.PNG, 100, out);
}
out.flush();
out.close();
if(!compressRet){
//When storage is full screenshot image will compress failed, so we delete the file
File f = new File(mImageFilePath);
if(f.exists()){
f.delete();
Log.d(TAG,"screenshot " + mImageFilePath + " compress failed, so we delete it");
}
params[0].clearImage();
params[0].result = 1;
}else {
// Save the screenshot to the MediaStore
ContentValues values = new ContentValues();
ContentResolver resolver = context.getContentResolver();
values.put(MediaStore.Images.ImageColumns.DATA, mImageFilePath);
values.put(MediaStore.Images.ImageColumns.TITLE, mImageFileName);
values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, mImageFileName);
values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, mImageTime);
values.put(MediaStore.Images.ImageColumns.DATE_ADDED, dateSeconds);
values.put(MediaStore.Images.ImageColumns.DATE_MODIFIED, dateSeconds);
if(PhoneStatusBar.LEUI_ENABLE) {
values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg");
} else {
values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/png");
}
values.put(MediaStore.Images.ImageColumns.WIDTH, mImageWidth);
values.put(MediaStore.Images.ImageColumns.HEIGHT, mImageHeight);
values.put(MediaStore.Images.ImageColumns.SIZE, new File(mImageFilePath).length());
Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// Create a share intent
String subjectDate = DateFormat.getDateTimeInstance().format(new Date(mImageTime));
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
if(PhoneStatusBar.LEUI_ENABLE) {
sharingIntent.setType("image/jpeg");
} else {
sharingIntent.setType("image/png");
}
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mImageFileName);
// Create a share action for the notification
final PendingIntent callback = PendingIntent.getBroadcast(context, 0,
new Intent(context, GlobalScreenshot.TargetChosenReceiver.class)
.putExtra(GlobalScreenshot.CANCEL_ID, mNotificationId),
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Intent chooserIntent = Intent.createChooser(sharingIntent, null,
callback.getIntentSender());
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
mNotificationBuilder.addAction(R.drawable.ic_screenshot_share,
r.getString(com.android.internal.R.string.share),
PendingIntent.getActivity(context, 0, chooserIntent,
PendingIntent.FLAG_CANCEL_CURRENT));
// Create a delete action for the notification
final PendingIntent deleteAction = PendingIntent.getBroadcast(context, 0,
new Intent(context, GlobalScreenshot.DeleteScreenshotReceiver.class)
.putExtra(GlobalScreenshot.CANCEL_ID, mNotificationId)
.putExtra(GlobalScreenshot.SCREENSHOT_URI_ID, uri.toString()),
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
mNotificationBuilder.addAction(R.drawable.ic_screenshot_delete,
r.getString(com.android.internal.R.string.delete), deleteAction);
params[0].imageUri = uri;
params[0].image = null;
params[0].result = 0;
}
} catch (Exception e) {
// IOException/UnsupportedOperationException may be thrown if external storage is not
// mounted
Log.e(TAG, "error in SaveImageInBackgroundData, exception:" + e);
params[0].clearImage();
params[0].result = 1;
}
// Recycle the bitmap data
if (image != null) {
image.recycle();
}
return params[0];
}
I want to upload images to fto using simple FTP. But it always failed to upload to FTP. The error always points to the ftp.connect. I don't know why. So I hope u can help me.
Upload.java
public class ImageUpdate extends AppCompatActivity {
private static final String TAG_ID = "id";
private static final String TAG_PESAN = "message";
private static final String TAG_HASIL = "result";
private static final String TAG_IMAGE_ID = "id_image";
private static final String TAG_IMAGE_NAME= "image_name";
ProgressDialog pDialog;
JSONParser jparser = new JSONParser();
ArrayList<HashMap<String, String>> namelist, idList, imageList;
JSONArray names, names1, names2;
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString = null;
Button submit;
static final String FTP_HOST = "xxxxxxxxxx";
static final String FTP_USER = "xxxxxxxxxxxx";
static final String FTP_PASS = "xxxxxxxxxxx";
String name, vid;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client2;
SessionManagement session;
String nm,addr,pos,tlp,mail,usr,pass,id,image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_update);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
session =new SessionManagement(ImageUpdate.this);
HashMap<String, String> user = session.getUserDetails();
id=user.get(SessionManagement.KEY_ID);
nm=user.get(SessionManagement.KEY_NAME);
addr=user.get(SessionManagement.KEY_ALAMAT);
mail=user.get(SessionManagement.KEY_EMAIL);
tlp=user.get(SessionManagement.KEY_TELP);
usr=user.get(SessionManagement.KEY_USERNAME);
pass=user.get(SessionManagement.KEY_PASS);
submit=(Button) findViewById(R.id.buttonUploadPicture);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (imgDecodableString == null) {
Toast.makeText(ImageUpdate.this, "Choose image first, please", Toast.LENGTH_LONG);
} else {
File f = new File(imgDecodableString);
name = f.getName();
uploadFile(f);
}
}
});
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filename = cursor.getString(columnIndex);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
File f = new File("" + imgDecodableString);
f.getName();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "Pilih Bukti Transaksi",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Failed to Choose", Toast.LENGTH_LONG)
.show();
}
}
public void uploadFile(File fileName) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SimpleFTP ftp=new SimpleFTP();
try {
ftp.connect("xxxxxxx", 21, "xxxxxxxx", "xxxxxxx");
ftp.bin();
ftp.cwd("img/imageProfil/");
ftp.stor(fileName);
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
try {
ftp.disconnect();
Toast.makeText(ImageUpdate.this, "disconnect", Toast.LENGTH_LONG).show();
} catch (Exception e2) {
e2.printStackTrace();
Toast.makeText(ImageUpdate.this, "failed", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client2.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Upload Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.amobi.newlomapodfix/http/host/path")
);
AppIndex.AppIndexApi.start(client2, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Upload Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.amobi.newlomapodfix/http/host/path")
);
AppIndex.AppIndexApi.end(client2, viewAction);
client2.disconnect();
}
}
stackTrace
06-20 22:32:00.692 2845-2845/com.amobi.newlomapodfix W/EGL_emulation: eglSurfaceAttrib not implemented
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: java.io.IOException: SimpleFTP received an unknown response when connecting to the FTP server: 220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at org.jibble.simpleftp.SimpleFTP.connect(SimpleFTP.java:74)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at com.amobi.newlomapodfix.UploadActivity.uploadFile(UploadActivity.java:167)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at com.amobi.newlomapodfix.UploadActivity$1.onClick(UploadActivity.java:100)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.view.View.performClick(View.java:4204)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.view.View$PerformClick.run(View.java:17355)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Handler.handleCallback(Handler.java:725)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Looper.loop(Looper.java:137)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5041)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
06-20 22:32:04.904 2845-2845/com.amobi.newlomapodfix W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
06-20 22:32:04.908 2845-2845/com.amobi.newlomapodfix W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-20 22:32:04.912 2845-2845/com.amobi.newlomapodfix W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-20 22:32:04.912 2845-2845/com.amobi.newlomapodfix W/System.err: at dalvik.system.NativeStart.main(Native Method)
This answer explains a nonconform FTP specification in simple FTP, in fact, the server should start with 220 but this library gets an exception.
(https://stackoverflow.com/a/24386510/6093353).
This tutorial implements an easy FTP upload, try to follow this
http://androidexample.com/FTP_File_Upload_From_Sdcard_to_server/index.php?view=article_discription&aid=98
I am getting a Java null pointer exception Unable to start receiver error. I am making an app which receives the push from the parse.com and I am getting the error for Android 4.0.3 - 4.0.4, and also when I restart the some devices..
My LogCat is
**java.lang.RuntimeException: Unable to start receiver com.omega.omegaplus.main.MyCustomReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2419)
at android.app.ActivityThread.access$1500(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1322)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4987)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.omega.omegaplus.main.MyCustomReceiver.onReceive(MyCustomReceiver.java:30)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2408)
... 10 more**
My broadcast receiver is
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String message = extras != null ? extras.getString("com.parse.Data")
: "";
Log.e("message ", " " + message);
JSONObject jObject;
try {
jObject = new JSONObject(message);
//objectId = jObject.getString("id");
time = jObject.getString("time");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
//gcmMessage.setMsg_id(1);
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
catch (JSONException e) {
e.printStackTrace();
}
}
When I reboot my phone then also it showing same error..., otherwise it is working fine.
I'll have a guess that message has the value of "" or NULL
JSONObject jObject;
try {
if (message != null && !message.equals("") {
jObject = new JSONObject(message);
//objectId = jObject.getString("id");
time = jObject.getString("time");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
//gcmMessage.setMsg_id(1);
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
}
catch (JSONException e) {
e.printStackTrace();
}
The Bluetooth device I am trying to connect has always the same pincode. This should make it possible to pair the device by setting the pin programmatically.
After trying to search how this could be done, I ended up with the code below:
BluetoothDevice device = getDevice();
//To avoid the popup notification:
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device, true);
byte[] pin = ByteBuffer.allocate(4).putInt(1234).array();
//int pinn = 1234;
//Entering pin programmatically:
Method ms = device.getClass().getMethod("setPin", byte[].class);
//Method ms = device.getClass().getMethod("setPasskey", int.class);
ms.invoke(device, pin);
//Bonding the device:
Method mm = device.getClass().getMethod("createBond", (Class[]) null);
mm.invoke(device, (Object[]) null);
cancelPairingUserInput gives me a NoSuchMethodException, which is weird because the method does exist in BluetoothDevice class.
Is looks like Setpin or SetPasskey doesn't do anything. The device just wont pair. It only pairs after manually entering the pin.
So the only line of code that works is:
//Bonding the device:
Method mm = device.getClass().getMethod("createBond", (Class[]) null);
mm.invoke(device, (Object[]) null);
Logcat output:
09-27 12:34:46.408: ERROR/App(11671): cancelPairingUserInput [boolean]
java.lang.NoSuchMethodException: cancelPairingUserInput [boolean]
at java.lang.Class.getConstructorOrMethod(Class.java:460)
at java.lang.Class.getMethod(Class.java:915)
at test.app.bluetooth.model.BluetoothDiscoveryAndPairing.pair(BluetoothDiscoveryAndPairing.java:97)
at test.app.bluetooth.model.BluetoothDiscoveryAndPairing.access$000(BluetoothDiscoveryAndPairing.java:25)
at test.app.bluetooth.model.BluetoothDiscoveryAndPairing$1.onReceive(BluetoothDiscoveryAndPairing.java:79)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:756)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
So what am I doing wrong?
The hidden method cancelPairingUserInput does not exist in your device. Don't use it.
You should register BroadcastReceiver for android.bluetooth.device.action.PAIRING_REQUEST
Call createBond()
Wait for BroadcastReceiver to trigger
In BroadcastReceiver if action is android.bluetooth.device.action.PAIRING_REQUEST
call this method
public void setBluetoothPairingPin(BluetoothDevice device)
{
byte[] pinBytes = convertPinToBytes("0000");
try {
Log.d(TAG, "Try to set the PIN");
Method m = device.getClass().getMethod("setPin", byte[].class);
m.invoke(device, pinBytes);
Log.d(TAG, "Success to add the PIN.");
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
Log.d(TAG, "Success to setPairingConfirmation.");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
It also works on a device with Jelly Bean version (4.1.2) of Android.
this is works for me:
IntentFilter filter2 = new IntentFilter(
"android.bluetooth.device.action.PAIRING_REQUEST");
mActivity.registerReceiver(
pairingRequest, filter2);
private final BroadcastReceiver pairingRequest = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
mBluetoothDevice = needed;
try {
byte[] pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, "1234");
Method m = mBluetoothDevice.getClass().getMethod("setPin", byte[].class);
m.invoke(mBluetoothDevice, pin);
mBluetoothDevice.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(mBluetoothDevice, true);
}
catch(Exception e)
{
e.printStackTrace();
}