Note that there are some explanatory texts on larger screens.

plurals
  1. POFileObserver service combined with UploadToImgur AsyncTask: service stops working after a while (NullPointer), Imgur doesn't return proper response
    primarykey
    data
    text
    <p>This is my first Android app, so please do go easy on me. The idea is to detect whenever user puts a photo in /mnt/sdcard and upload that to Imgur and then copy the link to system clipboard.</p> <h2>Classes in use</h2> <p>I have three classes working in my app. <code>ObserveNewImages</code> uses <code>FileObserver</code> to detect new photos in the previously stated path.</p> <p><strong>ObserveImages.java</strong> </p> <pre><code>public class ObserveNewImages extends Service { final String pathToObserve = android.os.Environment.getExternalStorageDirectory().toString(); // stores "/mnt/sdcard" final String upload_to = "https://api.imgur.com/3/upload.json"; final String API_key = "API_KEY_GOES_HERE"; public static final String TAG = "Awais"; String link; //full path to where the image is stored Intent upload; @Override public void onCreate(){ upload = new Intent(this, Imgur.class); //just initializing an intent for use later. Nothing special. super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "In onStartCommand"); FileObserver observer = new FileObserver(pathToObserve){ //As soon as we detect a new file in pathToObserve //, I fire up the service for uploading image to Imgur. @Override public void onEvent(int event, String file){ if (event == FileObserver.CREATE){ Log.d(TAG, "file address: " + pathToObserve + "/" + file); link = pathToObserve + "/" + file; upload.putExtra("path",link); startService(upload); } } }; observer.startWatching(); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } } </code></pre> <p>Moving on to <code>Imgur.java</code> which includes two classes <code>Imgur.class</code> and a <code>ImgurTask</code> which extends <code>AsyncTask</code> so that networking tasks take place on separate thread.</p> <p><strong>Imgur.java</strong></p> <pre><code>public class Imgur extends Service{ String path; @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { path = intent.getStringExtra("path"); new ImgurTask().execute(path); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } class ImgurTask extends AsyncTask&lt;String, Void, String&gt;{ final String upload_to = "https://api.imgur.com/3/upload.json"; final String API_key = "API_KEY_GOES_HERE"; public static final String TAG = "Awais"; String link; @Override protected String doInBackground(String... params) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(upload_to); httpPost.setHeader("Authorization", "Client-ID " + API_key); try { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("image", new FileBody(new File(params[0]))); entity.addPart("key", new StringBody(API_key)); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); String response_string = EntityUtils.toString(response.getEntity()); Log.d(TAG, "Response from Imgur: " + response_string); JSONObject json = new JSONObject(response_string); //Parsing JSON manually since I couldn't get it work using JSONObject's built-in class functions String json_str = json.toString(); Integer indexlink = json_str.indexOf("link"); Integer colonlink = json_str.indexOf(":", indexlink); Integer secondbracket = json_str.indexOf("}", colonlink); link = json_str.substring(colonlink+2, secondbracket-1); link = link.replace("\\",""); return link; }catch (Exception e){ e.printStackTrace(); } return "error"; } @Override protected void onPostExecute(String result) { if (result != "error"){ //copying link to clipboard ClipboardManager clipboard = (ClipboardManager)getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Imgur link", result); clipboard.setPrimaryClip(clip); Toast.makeText(getApplicationContext(), "Link is ready to paste: " + result, Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(), "Error: Are you connected to the Internet?", Toast.LENGTH_SHORT).show(); } super.onPostExecute(result); } } } </code></pre> <p><strong>MainActivity.java</strong></p> <p>This is only used to fire up the <code>ObserveImages</code> service.</p> <pre><code>public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //start service Intent start_observing = new Intent(this, ObserveImages.class); startService(start_observing); Toast.makeText(getApplicationContext(), "Automatic Image Uploader is now running!", Toast.LENGTH_SHORT).show(); finish(); } } </code></pre> <h2>The Problems</h2> <p>There are three problems:</p> <ul> <li><p>The services just stop working after a while. Nothing shows up the logs (which I have removed from the code here) to indicate that the app is running. To get things running again, I have to launch from app icon again. </p></li> <li><p>After a few uploads (sometimes 4-5, sometimes up to 10), Imgur's servers send a 405 Not Allowed response. Leave the app for a minute and come back again, and the servers will send back correct response.</p></li> <li><p>The app crashes after a while. FileObserver class throws a Null Pointer Exception.</p></li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload