4

Hi and thanks for your help, I have an App which I compile against API 17 in Eclipse.

The App performs some simple internet connections.

Now, when I test on an Emulator with API 17 everything works fine.

If i test it against an Emulator with API 8 the App apparently is not able to perform network connections (adMob dos not show, HttpGet apparently not retrieving anything...) form my App (web browser on Emulator working fine and loading normally).


And adMob as well does not load on Emulators with API 8 or 10 (it does on API 17 Emulators).


Any help very much appreciated !!!

This is my main Activity:

public class QuotesActivity extends Activity implements MyInterface {

private String url2;

public static ArrayList<Stock> lt;
public static ArrayList<Stock> favQ;

public MyAdapter myAdap;

public Intent intent;
public ListView lv;
public FavManager fm;
private AdView adView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.search);
    AdRequest request = new AdRequest();

    // request.addTestDevice(AdRequest.TEST_EMULATOR);
    request.setGender(AdRequest.Gender.MALE);
    boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
    if (tabletSize) {
        // Create the adView
        adView = new AdView(this, AdSize.SMART_BANNER, "a151388079e47d1");
    } else {
        // Create the adView
        adView = new AdView(this, AdSize.BANNER, "a151388079e47d1");
    }

    // Lookup your LinearLayout assuming it's been given
    // the attribute android:id="@+id/mainLayout"
    LinearLayout layout = (LinearLayout) findViewById(R.id.ad);

    // Add the adView to it
    layout.addView(adView);

    // Initiate a generic request to load it with an ad
    adView.loadAd(request);

    lt = new ArrayList<Stock>();
    favQ = new ArrayList<Stock>();
    fm = new FavManager(getApplicationContext());
    favQ.clear();
    favQ.addAll(fm.ritiraFav());
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    lt.clear();
    // ////////////
    try {
        InputStream in = getResources().openRawResource(R.raw.markets3);

        if (in != null) {
            InputStreamReader tmp = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(tmp);
            String str;
            String str1 = null;
            String str2 = null;
            boolean flag = true;
            while ((str = reader.readLine()) != null) {
                if (flag) {
                    str1 = str;
                    flag = false;
                } else {
                    str2 = str;
                    lt.add(new Stock(str1, str2, "0", "0"));
                    flag = true;
                }
            }
            in.close();
        }
    }

    catch (Throwable t) {
        // Log.e("", "Exception: " + t.toString());
    }
    // ///////
    Collections.sort(lt, new Comparator<Stock>() {
        public int compare(Stock s1, Stock s2) {
            return s1.nome.compareToIgnoreCase(s2.nome);
        }
    });
    lv = (ListView) findViewById(android.R.id.list);
    lv.setScrollbarFadingEnabled(false);
    Button favourites = (Button) findViewById(R.id.favoritesbtn);
    favourites.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(QuotesActivity.this,
                    QuotesActivityFavourites.class);
            startActivity(intent);

        }
    });

    Button search = (Button) findViewById(R.id.googsearch);
    search.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Log.e("", "Chiamo onSearchRequested()");
            onSearchRequested();

        }
    });

    myAdap = new MyAdapter(lt, this, this);
    myAdap.l = lt;
    lv.setAdapter(myAdap);

    Button preference = (Button) findViewById(R.id.preferencebutton);
    preference.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(QuotesActivity.this,
                    SettingsActivity.class);
            startActivity(intent);

        }
    });

    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {
            for (Stock item : favQ) {
                if (item.simbolo.equals(lt.get(position).simbolo)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            QuotesActivity.this);
                    builder.setPositiveButton("Yes", new OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                            deleteFromFavorites(lt.get(position));
                        }
                    });
                    builder.setNegativeButton("No", new OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                            // Quotes.layoutSchermo(2);
                        }
                    });
                    builder.setMessage("Stock Already in Portfolio. Delete from it?");
                    builder.setTitle(lt.get(position).nome);

                    AlertDialog dialog = builder.create();
                    builder.show();
                    return;
                }

            }

            AlertDialog.Builder builder = new AlertDialog.Builder(
                    QuotesActivity.this);
            final int pos = position;

            builder.setPositiveButton("Yes", new OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    addToFavorites(lt.get(pos));
                }
            });
            builder.setNegativeButton("No", new OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    // Quotes.layoutSchermo(2);
                }
            });
            builder.setMessage("Add to Portfolio?");
            builder.setTitle(lt.get(position).nome);
            AlertDialog dialog = builder.create();
            builder.show();
            // dialog.show();
        }
    });

}

@Override
public void onResume() {
    super.onResume();
    RelativeLayout focuslayout = (RelativeLayout) findViewById(R.id.RequestFocusLayout);
    focuslayout.requestFocus();
    favQ.clear();
    favQ.addAll(fm.ritiraFav());
}

public void addToFavorites(final Stock toadd) {

    fm.addFav(toadd);
    favQ.clear();
    favQ.addAll(fm.ritiraFav());
    return;
}

public void deleteFromFavorites(Stock todel) {
    fm.removeFav(todel);
    favQ.clear();
    favQ.addAll(fm.ritiraFav());
    return;
}

public void UpdateLine(Integer position) {
    UpdateTask up = new UpdateTask();
    up.execute(position, null, null);
}

public class UpdateTask extends AsyncTask<Integer, Void, Void> {

    @Override
    protected void onProgressUpdate(Void... progress) {
    }

    @Override
    protected void onPostExecute(Void result) {
        myAdap.l = lt;
        myAdap.notifyDataSetChanged();
    }

    @Override
    protected Void doInBackground(Integer... position) {
        DefaultHttpClient client = new DefaultHttpClient();
        String srt = "";
        // ///////////API SEGRETO DI GOOGLE ORIGINARIO
        // String url
        // =getString(R.string.dettaglio1).concat("'"+fav.get(i).simbolo+"'").concat(getString(R.string.dettaglio2));
        // ///////////API ALTERNATIVO
        String url = getString(R.string.urlaternativo).concat(
                lt.get(position[0]).simbolo);

        HttpGet getMethod = new HttpGet(url);
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            srt = client.execute(getMethod, responseHandler);
            int inizio = srt.indexOf("<last data=\"");
            int fine = srt.indexOf("\"/>", inizio + 12);
            lt.get(position[0]).setPrezzo(srt.substring(inizio + 12, fine));

            inizio = srt.indexOf("<perc_change data=\"");
            fine = srt.indexOf("\"/>", inizio + 19);
            lt.get(position[0]).setCambiamento(
                    srt.substring(inizio + 19, fine));

        } catch (Throwable t) {
            // Log.e("ERRORE INTERNET", "ERRORE INTERNET", t);
        }

        return null;
    }
}

@Override
public void onDestroy() {
    if (adView != null) {
        adView.destroy();
    }
    super.onDestroy();
}
}

This is my Manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quotes" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application android:debuggable="true" >
    <activity
        android:name=".QuotesActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:icon="@drawable/ic_launcher"
        android:label="Markets in your pocket !" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <meta-data
            android:name="android.app.default_searchable"
            android:value=".QuotesActivitySearch" />
    </activity>
    <activity
        android:name=".QuotesActivitySearch"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:icon="@drawable/ic_launcher"
        android:label="Markets in your pocket !" >
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />
    </activity>
    <activity
        android:name=".QuotesActivityFavourites"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:icon="@drawable/ic_launcher"
        android:label="Markets in your pocket !" >
    </activity>
    <activity
        android:name=".SettingsActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:label="Settings" >
    </activity>
    <activity
        android:name="com.google.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
</application>

This is my LogCat:

03-15 14:16:05.554: D/dalvikvm(1466): GC_EXPLICIT freed 909K, 43% free 4716K/8135K,    external 1170K/1682K, paused 7ms
03-15 14:16:07.185: E/ActivityThread(1466): Failed to find provider info for    com.google.plus.platform
03-15 14:16:07.185: D/szipinf(1466): Initializing inflate state
03-15 14:16:07.185: D/szipinf(1466): Initializing zlib to inflate
03-15 14:16:07.214: I/Ads(1466): To get test ads on this device, call    adRequest.addTestDevice("6EA1DCF3A944D7B947BC304C7A9E933D");
03-15 14:16:07.268: D/dalvikvm(1466): GC_CONCURRENT freed 395K, 36% free 5315K/8263K,    external 1121K/1603K, paused 1ms+0ms
03-15 14:16:07.290: I/Ads(1466): adRequestUrlHtml: <html><head><script     src="http://media.admob.com/sdk-core-v40.js"></script>   <script>AFMA_getSdkConstants();AFMA_buildAdURL({"preqs":3,"session_id":"1145804483122245265 2","seq_num":"4","slotname":"a151388079e47d1","u_w":320,"msid":"com.marketsinyourpocket","cap":"m,a","js":"afma-sdk-a-    v6.3.0","bas_off":0,"net":"ed","app_name":"1.android.com.marketsinyourpocket","hl":"en","gnt":3,"cust_gender":1,"carrier":"310260","u_audio":1,"u_sd":1.5,"ms":"Qqlgt9Kwv7BZOnio6PfLHi5mVs5ayp77VGIIyJ3Y7sojTNwIZfi0LHn2PZquoJTqpJx8NtOvTzGKWYlbxvU8fOjXkArCoqoQnGrLKZ57CTZOOt2WWrL9k8pyN4P-nBwIvuZDvijR0reHDyhcqwAoMtPdOeUV_cwIe3jk-6BMm_IgvGs8EKWVZESeqrSuExAStQMMsUYcC6p-XkB8KegxEX4FS2Q2CibdMk3CMKoAzfF58Sxp6DvRObm662IVwImzFWGdQ22UVx4ViQqz_ensdg1bXk5jgpyBOpV0jMFHgoEv5SwD5zpoeJfo-a1f0d5GR35f2bDAb3iXucuGB723lA","isu":"6EA1DCF3A944D7B947BC304C7A9E933D","format":"320x50_mb","oar":0,"ad_pos":{"height":0,"visible":0,"y":0,"x":0,"width":0},"u_h":533,"pt":1,"bas_on":0,"ptime":143736});</script></head><body></body></html>
03-15 14:16:07.358: W/webcore(1466): Can't get the viewWidth after the first layout
03-15 14:16:07.448: D/dalvikvm(1466): GC_CONCURRENT freed 338K, 33% free 6141K/9031K,  external 1121K/1603K, paused 1ms+0ms
03-15 14:16:13.494: V/URL I USE(1466): http://www.google.com/ig/api?stock=SHY
03-15 14:16:33.614: E/EXCEPTION I GET(1466): java.net.UnknownHostException: www.google.com

EDIT EDIT EDIT EDIT

Tried even on a API 10 Intel accelerated Emulator, with no better luck See Emulator Configurations

Proxy is set correctly,

data transfer is enabled

...I am a bit desperate!

EDIT EDIT EDIT

Posted the entire Activity

EDIT EDIT EDIT

The app works correctly on a real telephone with API 10 (not on my Emulator with API 10)!!!

The error I catch is

03-15 13:14:43.299: E/Exception(1318): java.net.UnknownHostException: www.google.com

indeed I use a Google REST Service

Thanks for your help!

Lisa Anne
  • 4,482
  • 17
  • 83
  • 157

5 Answers5

3

I'm pretty sure it's a proxy settings issue. Try explicit setting the proxy (obtain the values from Android System).

On a default HttpClient this would be:

HttpClient client = new DefaultHttpClient();

//Get the default settings from APN
  String proxyHost = android.net.Proxy.getDefaultHost();
  int proxyPort = android.net.Proxy.getDefaultPort();
//Set Proxy params of client, if they are not the standard
    if (proxyHost != null && proxyPort > 0) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
HttpGet request = new HttpGet("http://www.google.com");
Johannes Staehlin
  • 3,680
  • 7
  • 36
  • 50
1

Maybe internet is turned off in the emulator? There should be a little 3G icon at the top of it, try clicking F8, it turns it on and off.

Adomas
  • 466
  • 1
  • 8
  • 21
1

Guesses:

  • "Proxy is set correctly" Try it without setting any proxy.
  • try using another cpu instead of the intel atom
ChemicalFlash
  • 101
  • 1
  • 3
  • Thanks! Anyway without Proxy no internet connection at all (I am behind a firewall), tried armeabi CPU as well without success – Lisa Anne Mar 12 '13 at 09:48
  • 1
    found this: http://stackoverflow.com/questions/5801204/android-emulator-no-internet-connectivity probably a problem with the dns? – ChemicalFlash Mar 12 '13 at 16:04
  • "your_path_of_android_sdk\tools\emulator -avd -dns-server 8.8.8.8" NO SUCCESS – Lisa Anne Mar 13 '13 at 10:19
  • "try to go to Settings > Wireless & Networks > Enable Wifi (if you get an error, restart emulator till it works ( its a bug in emulator, we all have this)" NO SUCCESS – Lisa Anne Mar 13 '13 at 10:19
1

Since network access works with the AVD's browser, I'd focus on other potential sources of the problem.

If I were you, I'd simply try to compile against API 8. When you do that, you will be pointed towards any methods and other constructs you use in your code which are not available for API 8. (You haven't provided all code, e.g. there could be something hidden in MyAdapter. Also, you haven't mentioned whether or not your catch log message appears in the LogCat.)

The other aspect which may be worth looking at is that you're not using AsyncTask correctly, and it's going to behave differently on different API versions.

Depending on the API version, when you do not choose the Executor explicitly, your AsyncTasks will either run sequentially or in parallel, resulting in many or few http connections and also resulting in concurrent manipulation of your data structure.

You may manipulate your Adapter only on the main/UI thread. Otherwise, e.g. when the user scrolls through your list, the UI will call your adapter's getView() which may be interrupted by your AsyncTask modifying the very entry which is currently being processed by getView(), resulting in inconsistencies and/or crash.

You have tried to achieve this by manipulating lt asynchronously and calling myAdap.l = lt on the UI thread.

This is a nice idea, but it has two problems. First, on API 8, many AsyncTasks can run in parallel, while on API 17 it will only be one. Qoute:

Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

So on some versions of Android, you would encounter a race condition by which copies of lt would be manipulated in parallel, resulting in data loss upon the assignment. If those were actual copies, that is -- they aren't. By manipulating lt asynchronously while it is already assigned as the underlying data structure of your Adapter, you're breaking the rule of not manipulating UI objects asynchronously.

So you'll need to pass the fetched data from doInBackground to onPostExecute and update your Adapter's data structure there.

The two points I mentioned may not be the final cause of the problem but they could very well contribute to the observed behaviour, need to be addressed anyway and will make it easier to identify any other potentail root cause.

Hope this helps.

Update You may also be using the HttpClient in a wrong way. See for example here. Maybe not all combinations are (correctly) supported for all API levels (there were several bugs in the past). You may also want to read Android’s HTTP Clients.

Community
  • 1
  • 1
class stacker
  • 5,357
  • 2
  • 32
  • 65
  • Thank you very much. I am doing step by step what you suggested. 1) Compiling on API 8 gives no evident errors. – Lisa Anne Mar 15 '13 at 12:22
  • 2) the error I catch in the is the following `03-15 13:14:43.299: E/Exception(1318): java.net.UnknownHostException: www.google.com` (I am using a Google REST Service providing an url pointing to it) – Lisa Anne Mar 15 '13 at 12:26
  • what is really weird is that the App works correctly on a phisical API 10 phone – Lisa Anne Mar 15 '13 at 12:29
  • I get your point regarding manipulating `lt` in the the `doInBackground` and not in `onPostExecute` and indeed is a very correct observation, I'll work on it and let you know, although it might not be the problem with the internet connection itself. THANKS A LOT! – Lisa Anne Mar 15 '13 at 12:52
  • 1
    @pietmau Okay, we can narrow the search a bit. How about logging the resulting effective URL you try to contact, that would be `String url`? Could you `Log.v()` that? – class stacker Mar 15 '13 at 13:04
  • Ok, Thanks, changed the LogCat – Lisa Anne Mar 15 '13 at 13:19
  • 1
    @pietmau Thank you. That's weird. -- And you're sure the AVD has network connectivity, and that its the browser does not retrieve pages from its cache? Because you seem(ed) to have other network related errors in your logcat? – class stacker Mar 15 '13 at 13:32
  • browser works OK and does not retrieve from cache (I did Google searches on it and got results). The other network error that you see in my LogCat is AdMob which is failing to provide ads to my App (on Emulator API 17 all works fine ...) – Lisa Anne Mar 15 '13 at 13:40
  • 1
    @pietmau So we know for sure that it's _your app_ which does not have network access on an AVD which _does_ have network access. -- Have you checked in Settings -> Applications -> (your app) that it really has permission to access internet? To be sure that the correct manifest was included in your APK. – class stacker Mar 15 '13 at 13:46
  • checked, I went to Emulator->Settings->Applications-> Manage Appications -> myapp AND I can see: `Network communication. Full Internet access` – Lisa Anne Mar 15 '13 at 14:09
  • 1
    @pietmau Wait. You're using the HttpClient wrongly. I'm checking this. – class stacker Mar 15 '13 at 14:16
  • 1
    @pietmau I have updated my answer. There's a link to a SO Q+A where the same error message is being treated. You'd have to use a few other calls to try the solution given there. But you don't need the explicit DefaultResponseHandler anyway. – class stacker Mar 15 '13 at 14:25
  • I will definitely have to try use something else than HttpDefaultClient. The point is that my adMob does not get delivered as well..... – Lisa Anne Mar 15 '13 at 14:27
  • 1
    @pietmau So did you try the solution given [here](http://stackoverflow.com/questions/5377941/unknownhostexception-with-apache-httpclient)? – class stacker Mar 15 '13 at 15:25
  • Thanks, I will try it tonight (I am in Europe). Nevertheless adMob does not load as well... I will keep you posted – Lisa Anne Mar 15 '13 at 19:25
1

If you are developing in eclipse, you can try

Window>Preferences>Android>Launch

Default emulator options: -dns-server 8.8.8.8,8.8.4.4

EDIT:

goto: run->run configuration-> android application

then select your project -> target, scroll down options page and paste -dns-server 8.8.8.8,8.8.4.4 to Additional Emulator Command Line Options

Artem Zelinskiy
  • 2,201
  • 16
  • 19