Categories
discuss

How to remove element from ArrayList without left shifting the rest of elements

When you remove an element from an array list (arrayList.remove(int n)) it automatically shifts all the remaining elements to the left.

I was wondering is it possible for the elements to keep their position. So for example, if element at position 2 gets deleted, I want element at position 3 to remain where it is, not move to position 2. Thanks

Answer

list.set(2, null);

This just replaces the element at index 2 with null, which leads to the desired result.

Categories
discuss

Android – Large file downloads stop – using async/progressdialog

I have a simple code that is supposed to do one task, when the button is clicked download a file, save it to the SD card, and open it. Everything works except during the download, for larger files, the connection drops and the progress bar hangs – almost always at 20%. I have searched and searched and cannot figure out what to do to keep the connection alive and allow the download to complete. Any ideas how to keep the connection alive so the download completes instead of stalling at 20%?

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DownloadTestActivity extends Activity {

   public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
   private Button startBtn;
   private ProgressDialog mProgressDialog;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
           mProgressDialog = new ProgressDialog(DownloadTestActivity.this);
           mProgressDialog.setMessage("Downloading...");
           mProgressDialog.setIndeterminate(false);
           mProgressDialog.setMax(100);
           mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

           startBtn = (Button) findViewById(R.id.startBtn);
           startBtn.setOnClickListener(new OnClickListener() {
                   public void onClick(View v) {
                           startDownload();
                   }
           });
   }

   private void startDownload() {
           DownloadFile downloadFile = new DownloadFile();
           downloadFile
                           .execute("http://www.website.com/file.pdf");

   }

   class DownloadFile extends AsyncTask<String, Integer, String> {

           @Override
           protected void onPreExecute() {
                   super.onPreExecute();
                   mProgressDialog.show();
           }

           @Override
           protected void onProgressUpdate(Integer... progress) {
                   super.onProgressUpdate(progress);
                   mProgressDialog.setProgress(progress[0]);
           }

           @Override
           protected String doInBackground(String... aurl) {
                   try {
                           URL url = new URL(aurl[0]);
                           URLConnection connection = url.openConnection();
                           connection.connect();

                           int fileLength = connection.getContentLength();
                           Log.d("ANDRO_ASYNC", "Lenght of file: " + fileLength);

                           InputStream input = new BufferedInputStream(url.openStream());
                           String path = Environment.getExternalStorageDirectory()
                                           + "/Android/Data/"
                                           + getApplicationContext().getPackageName() + "/files";
                           File file = new File(path);
                           file.mkdirs();
                           File outputFile = new File(file, "test1.doc");
                           OutputStream output = new FileOutputStream(outputFile);

                           byte data[] = new byte[8192];
                           long total = 0;
                           int count;
                           while ((count = input.read(data)) != -1) {
                                   total += count;
                                   publishProgress((int) (total * 100 / fileLength));
                                   output.write(data, 0, count);
                           }

                           output.flush();
                           output.close();
                           input.close();
                           showPdf();

                   } catch (Exception e) {
                   }
                   return null;
           }

           private void showPdf() {
                   // TODO Auto-generated method stub
           if(mProgressDialog != null){
                   mProgressDialog.dismiss();
           }

                   File file = new File(Environment.getExternalStorageDirectory()
                                   + "/Android/Data/"
                                   + getApplicationContext().getPackageName()
                                   + "/files/test1.doc");
                   PackageManager packageManager = getPackageManager();
                   Intent testIntent = new Intent(Intent.ACTION_VIEW);
                   testIntent.setType("application/msword");
                   List list = packageManager.queryIntentActivities(testIntent,
                                   PackageManager.MATCH_DEFAULT_ONLY);
                   Intent intent = new Intent();
                   intent.setAction(Intent.ACTION_VIEW);
                   Uri uri = Uri.fromFile(file);
                   intent.setDataAndType(uri, "application/msword");
                   startActivity(intent);
           }


   }
}

Edit with logcat information:

--------- beginning of /dev/log/system
W/InputManagerService(  199): Window already focused, ignoring focus gain of:     com.android.internal.view.IInputMethodClient$Stub$Proxy@4137b898
--------- beginning of /dev/log/main
D/AndroidRuntime(20673): 
D/AndroidRuntime(20673): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20673): CheckJNI is OFF
D/AndroidRuntime(20673): Calling main entry com.android.commands.pm.Pm
D/AndroidRuntime(20673): Shutting down VM
D/dalvikvm(20673): GC_CONCURRENT freed 101K, 82% free 467K/2560K, paused 1ms+0ms
D/dalvikvm(20673): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20673): NOTE: attach of thread 'Binder Thread #3' failed
D/AndroidRuntime(20687): 
D/AndroidRuntime(20687): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20687): CheckJNI is OFF
D/AndroidRuntime(20687): Calling main entry com.android.commands.am.Am
I/ActivityManager(  199): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.myapp/.Activity} from pid 20687
D/AndroidRuntime(20687): Shutting down VM
D/dalvikvm(20687): GC_CONCURRENT freed 102K, 81% free 489K/2560K, paused 0ms+0ms
D/jdwp    (20687): Got wake-up signal, bailing out of select
D/dalvikvm(20687): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20687): NOTE: attach of thread 'Binder Thread #3' failed
D/dalvikvm(20698): Late-enabling CheckJNI
I/ActivityManager(  199): Start proc com.myapp for activity     com.myapp/.Activity: pid=20698 uid=10102 gids={1015, 3003}
I/dalvikvm(20698): Turning on JNI app bug workarounds for target SDK version 10...
V/PhoneStatusBar(  271): setLightsOn(true)
D/AudioHardware(   98): AudioHardware pcm playback is going to standby.
D/AudioHardware(   98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager(  199): Displayed com.myapp/.Activity: +197ms
W/InputManagerService(  199): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@4199ed28 (uid=10098 pid=20011)
I/ActivityManager(  199): START {cmp=com.myapp/.Choice} from pid 20698
D/AudioHardware(   98): AudioHardware pcm playback is exiting standby.
D/AudioHardware(   98): openPcmOut_l() mPcmOpenCnt: 0
V/PhoneStatusBar(  271): setLightsOn(true)
I/ActivityManager(  199): Displayed com.myapp/.Choice: +93ms
D/ANDRO_ASYNC(20698): Lenght of file: 736768
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
W/NetworkStats(  199): found non-monotonic values; saving to dropbox
D/dalvikvm(  199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm(  199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
D/AudioHardware(   98): AudioHardware pcm playback is going to standby.
D/AudioHardware(   98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager(  199): Force stopping package com.myapp uid=10102
I/ActivityManager(  199): Killing proc 20698:com.myapp/10102: force stop
W/ActivityManager(  199): Force removing ActivityRecord{41eb1ec0 com.myapp/.Choice}: app died, no saved state
I/InputDispatcher(  199): Dropping event because there is no focused window or focused application.
I/ActivityManager(  199):   Force finishing activity ActivityRecord{418450c8 com.myapp/.Activity}
I/InputDispatcher(  199): Dropping event because there is no focused window or focused application.
W/InputDispatcher(  199): channel '417b41f0     com.myapp/com.myapp/.Activity (server)' ~     Consumer closed input channel or an error occurred.  events=0x8
E/InputDispatcher(  199): channel '417b41f0 com.myapp/com.myapp.Activity (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher(  199): Attempted to unregister already unregistered input channel '417b41f0 com.myapp/com.myapp.Activity (server)'
W/WindowManager(  199): Failed looking up window
W/WindowManager(  199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy@41c7ffc8 does not exist
W/WindowManager(  199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager(  199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager(  199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager(  199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager(  199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager(  199): WIN DEATH: null
I/WindowManager(  199): WIN DEATH: Window{4175b280     com.myapp/com.myapp.Choice paused=false}
W/WindowManager(  199): Failed looking up window
W/WindowManager(  199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy@41758028 does not exist
W/WindowManager(  199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager(  199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager(  199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager(  199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager(  199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager(  199): WIN DEATH: null
W/InputManagerService(  199): Got RemoteException sending setActive(false) notification to pid 20698 uid 10102
D/dalvikvm(20011): GC_CONCURRENT freed 460K, 32% free 9468K/13767K, paused 3ms+4ms
D/AudioHardware(   98): AudioHardware pcm playback is exiting standby.
D/AudioHardware(   98): openPcmOut_l() mPcmOpenCnt: 0

Answer

I’ve tried to download your file a few times, looks like download stalls for a few seconds here and there, and it might trigger a timeout in your application. Try to specify timeouts explicitly in range 10-20 seconds.

private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet get = new HttpGet("your url comes here");

protected String[] doInBackground(Void... v) {
    HttpParams httpParameters = new BasicHttpParams();
    // set the timeout in milliseconds until a connection is established
    // the default value is zero, that means the timeout is not used 
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // set the default socket timeout (SO_TIMEOUT) in milliseconds
    // which is the timeout for waiting for data
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    httpclient.setParams(httpParameters);

    try {
        HttpEntity entity = httpclient.execute( get ).getEntity();
        FileOutputStream output = new FileOutputStream(outputFile);
        entity.writeTo(output);
        output.close();
        // return something, maybe?
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return null;
}
Categories
discuss

When a response to $.ajax is 301, can I programmatically get the new URL?

Is there a way to get the URL you are ultimately redirected to when the response to an xhr request is 301?

I have a site that contains numerous legacy URLs from an older version, which return 301 responses to the correct new URL.

For utility purposes, I would like to be able to make a request to an old URL, and be able to retrieve the new one i.e. send request to “/oldpage.aspx?foo=someParam”, get back the new url “/arbitaryNewPageName/someParam”.

I’ve been playing around with this in the firebug console:

    $.ajax({
            url: "/oldpage.aspx?foo=someParam", 
            success: function(response, status, jqxhr){
            //poking around, trying to get the new URL, "/arbitraryNewPage/someParam"
                console.log(jqxhr.getAllResponseHeaders());
                console.log(jqxhr);
            },
            beforeSend: function(jqxhr, settings){
                console.log(jqxhr);
                console.log(settings);
            }
        });

I can see in firebug that when this code runs, it does one GET to “/oldpage.aspx?foo=someParam”, and gets a 301 response, then another GET to “/arbitaryNewPageName/someParam”.

For the first request, I see the redirected URL in the Location value of the response header. Unfortunately, the second request is what is passed to the $.ajax.success function, and it only has the redirected URL in the Referrer value of the request header.

Is there perhaps a way to intercept the response to the first response, or maybe see the request headers for the second request?

Edit: Thanks everyone for the responses. I think I need to give a little background to clarify what exactly I’m looking for.

A business user has asked me to create a list that associates legacy URLs with new URLs. Since I have already implemented a means of redirecting legacy URLs to new URLs on the server, I was hoping to piggy back off that work and create a script that placed requests to the legacy URLs and got the URLs that the requests were redirected to. Something like this:

for (var i = 0; i < arrayOfLegacyUrls.length; i++)
{
    $.ajax({
            url: arrayOfLegacyUrls[i], 
            success: function(response, status, jqxhr){
                var newUrl = "???"; //do magic to get URL that request was redirected to

                writeToFileForBusinessUser(arrayOfLegacyUrls[i], newUrl);
            }
        });
}

The crux of my question is this: Can I get the URL my request was redirected to from the XHR? So far, the answer seems to be “no”.

Answer

I found a way to do this by using the actual XHR object instead of jquery’s ajax method from this answer: https://stackoverflow.com/a/7015798/194099

var r = new XMLHttpRequest();
r.open("GET", "http://mysite.com/legacyUrl.aspx?bla=bla");
r.overrideMimeType("text/xml");
r.onload = function()
{
  alert(r.responseXML.baseURI); //gets the URL the request was redirected to! huzzah!
}
r.send(null);

With this, I was able to place a request to a URL I know will return a 301, and get the URL that the request is being redirected to.

Categories
discuss

iText/BouncyCastle ClassNotFound org.bouncycastle.asn1.DEREncodable and org.bouncycastle.tsp.TimeStampTokenInfo

I’m trying to use iText Java. When you run the example “how to sign” the following error occurs:

Caused by: java.lang.ClassNotFoundException: org.bouncycastle.tsp.TimeStampTokenInfo

According “Getting Started with iText – How to sign a PDF using iText”, I have to use the BouncyCastle.

I downloaded the file: bcprov-jdk15on-147.jar from BouncyCastle download page.
And added to the project: Java Build Path/Libraries/Add External JARs…

I added the following line:

Security.addProvider(new BouncyCastleProvider());

When you run the example the same error occurs.
So I downloaded another file: bcpkix-jdk15on-147.jar entitled “PKIX/CMS/EAC/PKCS/OCSP/TSP/OPENSSL”
And added to the project: Java Build Path/Libraries/Add External JARs…
Now I have two Jars.

When you run the example the following error occurs:

Caused by: java.lang.ClassNotFoundException: org.bouncycastle.asn1.DEREncodable

I tried downloading the file “bcprov-ext-jdk15on-147.jar” but did not solve the problem.

I am using iText 5.2.1 and eclipse on Windows 7 64 bits.

Answer

BouncyCastle libs are undergoing heavy API changes that broke the compatibility with other libs like iText.

Either

  • use a previous version of BouncyCastle libs. Old versions can be found here. However, you’ll have to find the right version of iText that was compatible with this particular version of BC.

  • make your own build of iText (the SVN trunk has been fixed). iText can be build with Maven (there’s a short readme file at the root of the SVN). Please note that it’s at your own risk, there may be bugs in trunk.

  • wait for the next version of iText. From my experience, iText releases come every couple of months, sometime more often, sometimes less. I’m not an iText committer though, so I can’t give you any ETA.

More information can be found in this thread

Categories
discuss

Chrome desktop notification click to focus on content

I am building desktop notification into my a chrome extension that I am working on. The functionality I need required that the user be taken to the tab that caused the notification when they click on the notification window. I can get that working using the chrome.tabs API, but what I can’t manage to figure out is how to bring Chrome to the front when the notification is clicked.

I know window.focus() is disabled in chrome, but this is definitely possible to do since that’s the behavior of the Gmail desktop notifications.

Answer

notification = webkitNotifications.createNotification(...)
notification.onclick = function(){
    window.focus();
    this.cancel();
};
notification.show()

…works as expected, without any additional permissions.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..