Google Maps -> MapView -> creation of a constructor -> RuntimeException

I try to write one application for Google Maps.

Tell me, what is my mistake?

If you write like this, all of the works, the card is loaded.

public class TravelMapActivity extends MapActivity {
  private MapView mapView;

    protected void onCreate(Bundle savedInstanceState) {
        mapView = (MapView)findViewById(R.id.travelMapView);

And if you create a constructor, I get these errors here.

protected void onCreate(Bundle savedInstanceState) {
    mapView = new MapView(this, getResources().getString(R.string.google_maps_api_key));

 java.lang.RuntimeException: Unable to start activity ComponentInfo{de.ai.mi.maptrack/de.ai.mi.maptrack.activities.TravelMapActivity}: java.lang.IllegalStateException: You are only allowed to have a single MapView in a MapActivity

 Caused by: java.lang.IllegalStateException: You are only allowed to
 have a single MapView in a MapActivity



With the v1 google maps android api you only allowed one MapView at a time. You instantiate one MapView in your XML travel_map_activity i guess, so when you try to create another one with

mapView = new MapView(this, getResources().getString(R.string.google_maps_api_key));

you get the Exception. Try remove the MapView from the XML to solve this.

Android BroadcastReceiver: run it on default process or in a new one?

I have an application with two Broadcast Receivers, one of them to receive data and the other one to send it. I've seen that they have an attribute android:process to make them run on the application's default process or in another one. In the examples I found using google, receivers were set to run in the process ":remote".

My question is, what are the advantages and disadvantages of using each option?


Using a different Process than the Default Process of the Application is handy when you want to share ressources with another Application.

Todo so you need to arrange two Applications with the same processname, if your processname begins with an lowerchar a global process is spawned. If it begins with a colon : than the process is private. Keep in mind that to share a process between two apps you need the same userID and the same app certificate.

You also have to load ressources only once and get benefits in memory consumption.

for more information

Android database transactions

I am new to Android programming and am trying to understand the best practices.

I want to do multiple inserts into two different database tables, but as one transaction (as the tables shared a foreign key). I want my function to return a result so that I can display a Toast or something to say that an error occurred, otherwise I want to return the row ID of the first insert.

I believe one way of doing this is sort-of as follows (Disclaimer: psuedo-ish code, probably won't compile!):

Long result = -1;
try {
   // Insert into first table
   ContentValue someValues = new ContentValues();
   someValues.put("dbfield1", 1);
   result = myDatabase.insert(DATABASE_TABLE_1, null, someValues);

   if (-1 != result ) {         
       // Insert into second table
       someValues.put("dbfield2", 2);

       if( myDatabase.insert(DATABASE_TABLE_2, null, someValues) < 0 ) {
           result = -1;

} catch(Exception e) {
    // An error occurred
    result = -1;
} finally {

Is there a simpler/better way of doing this?


You can override bulkInsert inside your ContentProvider your Code looks fine. The Method should return the inserted Rows Value but you can customize that so you return only the first ID.

public int bulkInsert(Uri uri, ContentValues[] values) {
    Log.e("BULK", "Bulk insert started for URI" + uri.toString());
    bulkSqlDB = database.getWritableDatabase();
    int numInserted;

    try {
        for (ContentValues cv : values) {
            insert(uri, cv);
        numInserted = values.length;
    } finally {
        getContext().getContentResolver().notifyChange(uri, null);
    return numInserted;

Jelly Bean android.R.id.content changed?

i recently tested my App on a Jelly Bean device and noticed that my Actionbar Dodging Code doesnt work anymore.

I have a transparent Actionbar with OverlayMode true but want to behave the Actionbar like a solid actionbar in some of my Screens.

To make this working i have borrowed some Code from the Honeycomb Gallery Code

Basicly i check the Acionbar Height and set the topMargin of the android.R.id.content bucket to this value.

  public void setupActionbar() {
    final int sdkVersion = Build.VERSION.SDK_INT;
    int barHeight = getSupportActionBar().getHeight();
      if (sdkVersion < Build.VERSION_CODES.HONEYCOMB) {
        FrameLayout content = (FrameLayout) findViewById(android.R.id.content);
        RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) content.getLayoutParams();

        if (params.topMargin != barHeight) {
          params.topMargin = barHeight;

        if (!getSupportActionBar().isShowing()) {
          params.topMargin = 0;
      } else {
        FrameLayout content = (FrameLayout) findViewById(android.R.id.content);
        LayoutParams params = content.getLayoutParams();
        if (params instanceof RelativeLayout.LayoutParams) {
          android.widget.RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) params;
          if (lp.topMargin != barHeight) {
            lp.topMargin = barHeight;

          if (!getActionBar().isShowing()) {
            lp.topMargin = 0;
        } else if (params instanceof FrameLayout.LayoutParams) {
          FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) params;
          if (lp.topMargin != barHeight) {
            lp.topMargin = barHeight;

          if (!getActionBar().isShowing()) {
            lp.topMargin = 0;


In Jelly Beans this strategy doesnt work anymore for some reason. Did Jelly Bean change the id.content Container perhabs?


Ok answering my own Question here. First i had a typo in my Code:

content.setLayoutParams(params); should read

But the real Problem was that

FrameLayout content = (FrameLayout) findViewById(android.R.id.content);

provide the View of the whole Screen, including the Statusbar. Only on Android 4.1 Jelly Bean

View content = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);

gives the RootContentView that needs to be pushed under the Transparent Actionbar.

Actionbarsherlock switch Actionbar Overlay Mode programmatic

i use Actionbarsherlock for my App and i like to switch the Actionbar Overlay Mode in my Code. I have 2 Fragments (one is a Mapview where i want a translucent Actionbar) the other is a ListFragment where a solid Actionbar is needed.

i tryed

requestWindowFeature((int) Window.FEATURE_ACTION_BAR & ~Window.FEATURE_ACTION_BAR_OVERLAY);

problem with this is that requesting Features only works before content is added.

i using this style to accomplish the transparent Actionbar

<style name="TransparentActionbar" parent="@style/Theme.Sherlock" xmlns:android="http://schemas.android.com/apk/res/android">
    <item name="windowActionBarOverlay">true</item>
    <item name="windowActionModeOverlay">true</item>
    <item name="abBackground">#96000000</item>
    <item name="abDivider">@null</item>

is there a way to set

<item name="windowActionBarOverlay">true</item>
<item name="windowActionModeOverlay">true</item>

to false inside the Activity/Fragment?


Edit: Sadly it doesnt work for Actionbarsherlock and a ListFragment from the Compatibility Package. Top Margin is added to the Bottom Margin for some reason. Left and Right Margin working fine inside the LayoutListener.

Found a solution for this Problem in an Android Developer Example

// Attach a GlobalLayoutListener so that we get a callback when the layout
// has finished drawing. This is necessary so that we can apply top-margin
// to the ListView in order to dodge the ActionBar. Ordinarily, that's not
// necessary, but we've set the ActionBar to "overlay" mode using our theme,
// so the layout does not account for the action bar position on its own.
ViewTreeObserver observer = getListView().getViewTreeObserver();

// Because the fragment doesn't have a reliable callback to notify us when
// the activity's layout is completely drawn, this OnGlobalLayoutListener provides
// the necessary callback so we can add top-margin to the ListView in order to dodge
// the ActionBar. Which is necessary because the ActionBar is in overlay mode, meaning
// that it will ordinarily sit on top of the activity layout as a top layer and
// the ActionBar height can vary. Specifically, when on a small/normal size screen,
// the action bar tabs appear in a second row, making the action bar twice as tall.
ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        int barHeight = getActivity().getActionBar().getHeight();
        ListView listView = getListView();
        FrameLayout.LayoutParams params = (LayoutParams) listView.getLayoutParams();
        // The list view top-margin should always match the action bar height
        if (params.topMargin != barHeight) {
            params.topMargin = barHeight;
        // The action bar doesn't update its height when hidden, so make top-margin zero
        if (!getActivity().getActionBar().isShowing()) {
          params.topMargin = 0;

Get data back from a fragment dialog - best practices?

I'm converting some of my project to use fragments. How do we communicate with a fragment dialog? I want to create a fragment dialog just to get some text input from the user. When the dialog is dismissed, I'd like to pass the entered text back to the "parent" fragment (the one that started it). Example:

public class MyFragment extends Fragment {

    public void onBtnClick() {
        // What's a good way to get data back from this dialog 
        // once it's dismissed?
        DialogFragment dlgFrag = MyFragmentDialog.newInstance();
        dlgFrag.show(getFragmentManager(), "dialog"); 



A great way to pass this kind of Events is a Callback Interface like descripted in the Android Developers Guide

Your Fragment define a Callback Interface like

public class MyFragment extends Fragment {
    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);

Then you check inside your onAttach Method if the Parent implemented the Callback Interface and save the Instance.

public void onAttach(Activity activity) {
    try {
        mListener = (OnArticleSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");

when your Event inside the Fragment happens you simply call the Callback Handler


Hope that helps, further infos here

Debugging Jersey Unmarshalling Error - Bad Request syntactically incorrect

I am building a REST Webservice with the help of Jersey on Glassfish. Now I am struggeling with my custom input Source for my searchQuerys.

If have a search Method:

@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public List<Index> search(SearchQuery searchqry) {

And the Class SearchQuery:

public class SearchQuery implements Serializable {
    private static final long serialVersionUID = 1L;

    public SearchQuery() {

    public SearchQuery(float lat, float lng) {
        this.lat = lat;
        this.lng = lng;

    public float getLat() {
        return lat;

    public void setLat(float lat) {
        this.lat = lat;

    public float getLng() {
        return lng;

    public void setLng(float lng) {
        this.lng = lng;

    private float lat;
    private float lng;

And my call:

curl -v -X POST --data-binary "<SearchQuery><lat>3.3</lat><lng>5.4</lng></SearchQuery>" -H "Content-Type: application/xml" -H "Accept: application/xml" http://localhost:8080/WebApplication1/resources/index/search

I tried a restconsole to send the XML request, but I get the same error:

HTTP Status 400 - Bad Request

type Status report

messageBad Request

des criptionThe request sent by the client was syntactically incorrect (Bad Request).

GlassFish Server Open Source Edition 3.1.2

* Closing connection #0

I am missing something essentially or can somebody give me a hint how to debug the unmarshalling part inside the Application Server?

I followed the guide at http://xebee.xebia.in/2011/12/30/example-of-restful-webservice-with-xml-and-json-using-maven-jaxb-jersey-tomcat-and-curl/ and tested varius combination of Annotations but no sucess :(


FINALLY found the real reason for my problem: SearchQuery is mapped to "searchQuery" inside XML

TESTClass is mapped to tESTClass inside the XML Entity

refresh activity from listadapter onclicklistener in android app

I have an activity with a listview in it. I implemented a custom list adapter based on ArrayAdapter. Some of the items within the list are clickable and some are not. So I implemented the onClickListener within the getView method of the listadapter.

I can refresh the listview just fine by calling the notifyDataSetChanged() method.

What I want to do is refresh the textview within the activity which contains the list whenever an item in the list is clicked. I can't think of a way to do this. Anybody have any suggestions?

This is what the activity contains:

  1. TextView (Title)
  2. TextView (total points) -> I want to update this
  3. ListView (some items in the list are clickable)


Take the reference of the TextView inside your CustomListAdapter, then trigger the update of the total points textview inside your onClickListener.


getView() {
    onClickListener(Event..) {


Is there a way to create a triangular button on Android?

Is there a way I can create a button which is shaped as a triangle? I know I can put a triangle image as background, but this will make the area outside the triangle clickable. Is there a way to sey the button corners X and Y so I could make it triangular?


You can override the OnTouch Event method in a CustomView / CustomButton

Inside you have the MotionEvent were you can check if the Touch was inside your Triangle (with the help of some mathematics :P)

How to get the MIME-type of oddly-named files?

I'm writing a basic file browser that changes the icon used for files displayed depending on the MIME type of the file, but I'm having trouble finding the MIME type of some files, and I'm not sure why, the code I'm using to find the MIME Type is thus:

    private String getFileMimeType(File file)
    Uri fileUri = Uri.fromFile(file);
    String ext = MimeTypeMap.getFileExtensionFromUrl(fileUri.toString());
    return mtm.getMimeTypeFromExtension(ext);

It works for some file, but not for some with more complicated characters in them, which I don't really understand, example below:

enter image description here

The files with tildas are all functional mp3s but all return null for their MIME types, which isn't good for functioning mp3s, so I'm curious if there's any simple workaround for files with special chars in their name.


Its because of the "~" character in your filenames.

Look at the implementation of getFileExtensionFromUrl

 * Returns the file extension or an empty string iff there is no
 * extension.

public static String getFileExtensionFromUrl(String url) {
    if (url != null && url.length() > 0) {
        int query = url.lastIndexOf('?');
        if (query > 0) {
            url = url.substring(0, query);
        int filenamePos = url.lastIndexOf('/');
        String filename =
            0 <= filenamePos ? url.substring(filenamePos + 1) : url;

    // if the filename contains special characters, we don't
    // consider it valid for our matching purposes:
    if (filename.length() > 0 &&
        Pattern.matches("[a-zA-Z_0-9\\.\\-\\(\\)]+", filename)) { // <--
        int dotPos = filename.lastIndexOf('.');
        if (0 <= dotPos) {
            return filename.substring(dotPos + 1);

return "";


a possible solution would be to write your own implemenation of this method with wider matching rule. Hope this helps

What is an Earcon?

I just stumbled upon the method TextToSpeech.addEarcon(String, String) in Android's TTS API. I actually couldn't find more information on the net, so does anyone know what exactly an earcon is?



With an Earcon you can map a Name(Parameter1) to a Soundfile-Path(Parameter2).

I think Earcon is a other form of Icon, like Eye-con => Ear-con => Nose-con and so on :-) TextToSpeech.html#addEarcon(java.lang.String, java.lang.String)

It is possible to display a route between two coords launching googlemaps on the navigator? (programatically)

I know that i can do it with this:

            Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 

But i need to remove the dialog, and forze it to launch navigator ¿how to do it?

I know that i can forze the dialog to open googlemap application with intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");

But i need just the opposite, to launch the navigator.



Intent i = new Intent();

i.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"));
Uri data = Uri.parse("http://www.google.com");

startSubActivity(i, 2); 

Having PHP session issue

Getting following warning messages on page load. I don't understand what is that?

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/heimann/public_html/admin/login.php:9) in /home/heimann/public_html/admin/login.php on line 47

Warning: Cannot modify header information - headers already sent by (output started at /home/heimann/public_html/admin/login.php:9) in /home/heimann/public_html/admin/login.php on line 52

The php code

//line 9 <?php 

$admin = 'http://'. $_SERVER['HTTP_HOST'] . '/admin/';

$db = new MySQLi('localhost', 'heimann_admin', '0579ural', 'heimann_content') or die($db->error);





if($username && $password && $submit=='Giriş'){

    $result=$db->query("SELECT id, username, password FROM users WHERE username='$username' AND password='$password'");









        if($username==$dbusername && $password==$dbpassword){

        //line 47 session_start();


        //line 52 header('location:'.$admin);


        else message("Şifrə səhvdir");

    else {message("Bazada belə login və şifrə kombinasiyası yoxdur");}


else {message("Giriş parametrlərindən biri daxil edilməyib");}

function message($text){
    global $admin;
    echo '<div class="message">'.$text. '</br><a href="'.$admin.'">Geri</a></div>';



you have some output before the session_start, thats forbidden. If you cannot change the output before session_start you can use ob_start(); and ob_flush(); to cache the output.

Screen brightness value in Android

How do you get the current screen brightness of your activity?

Following method works fine for setting the brightness to max by calling setBrightness(100):

private void setBrightness(int brightness) {
    WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
    layoutParams.screenBrightness = brightness/100.0f;

Im trying to achieve the following:

  1. Start the activity and save the current brightness value
  2. Set brightness to max
  3. Reset brightness to the initial value on certain events

Many thanks!



int curBrightnessValue = android.provider.Settings.System.getInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS);

and then

   WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
    layoutParams.screenBrightness = curBrightnessValue/100.0f;

Best method for threading in Android?

I have an animation in which triggers an event. This event fires a lot of computing usage and thus stutters the UI.

What I need to do is keep the thread running smoothly. When the event happens it will pass a string down to the thread, perform calculations (including using the audioRecord class) and return a boolean variable.

I have looked around and it seems AsyncTask may be the best solution, but I wanted to see if any of you had any ideas? Considering performance, Is this the best way to go?




Generally AsyncTask is fine. But if you dont need to acess the UI thread for your background operation you can simply use a new thread.

new Thread(new Runnable() {
    public void run() {
        //do stuff

how can i stop a function in a service?

I have a function::

public void doSleep() {
        new Runnable() { 
            public void run() { doCom(); } 
        }, 10000); 

This is linked with doCom which starts this again. how can I finsh this at the end of the service?


create a boolean flag in your class called sleep = true;

public void doSleep() {
        new Runnable() { 
            public void run() { if(sleep) { doCom(); } } 
        }, 10000); 

and set sleep = false; if you want to stop it.

MediaPlayer 'prepare();' problem

When I use prepare(); on my mediaplayer, a black layout pops up till the mediaplayer is prepared.. I want to change that black screens layout, is that possible?


prepare(); is a blocking operation, if you dont want to block your UI Thread use prepareAsync();. Or use prepare in another Thread

Prevent using a button until it is ready

So I have seen some other posts similar, but not quite answering what I am looking for.

Basically onCreate is loading in the content (being textviews and image) and it also opens up another thread to prepare the media player so that when the button is pressed it plays a specific song. If this activity is opened and the button is pressed quickly it does not play anything (which I am assuming because it hasn't had a chance to prepare). If I open the activity and give it a few moments it works just fine. I do realize that it is not best to run the content being loaded in onCreate, but I have tried to get it to load in other threads and it failed miserably. It is all fine with me what I really want to happen is this.

I need some way to prevent use of the button or let them know it is loading for about 3-5 seconds. So either make the button be faded out and unusable for 3-5 seconds and then it becomes active or a loading screen that is some what transparent that covers the activity for about 3-5 seconds. If you mention using other threads could you please demonstrate it if it isn't asking to much or show me something like a tutorial (other than googles notes). I don't understand threads very well yet (pretty new to them) and the AsyncThread is pretty confusing to me.

If you need code let me know what you would want posted. Thanks and I appreciate any help.


You can set an setOnPreparedListener on your MediaPlayer, in this listener you enable your button and be save that the song can be played. Docs

How to use Camera to take picture in a background Service on Android?

I'm developing a Service, running in background, that uploads succesfully images and data to the web.

Now I want to upload an image taken by the Camera.

Is it possible to use the camera in a background service without preview on Android 2.2?

I found various contrastants answers on web...

How can I do it?


You can take pictures without preview with an dummy view.


SurfaceView view = new SurfaceView(this);
c.takePicture(shutterCallback, rawPictureCallback, jpegPictureCallback);

Android caching database?

I had a database being loaded up at application startup. I made some changes to the DB, deleted the app from the emulator (wipe user data), and deleted it from my phone. Cleaned the project from the menu. However, when I run it, the old DB is still there. I am testing this notion by pulling the file in DDMS and opening it up in SQLite Explorer.

How can I remove this old cache?


The Database is located under /data/data/[apk-package-name]/databases/

You can connect to the shell of the emulator and try to delete the databases inside this path

$ adb -s emulator-5554 shell

How to ensure cache doesnt become to full?

I am working on a project that uses a lot of fetching of text from a website. and downloading 4 images once a week and overrwritting them to the same cache.

What i am worried about is the cache becoming to full of files storing bitmap data. It initially takes up about 1.45mb of cache and continues to grow the more the images are fetched.

So how can i ensure that each time the new images are downloaded the old ones are erased?

Or do i not need to worry about the clean-up of the application's cache?


from the docs:

getCacheDir ()

Returns the absolute path to the application specific cache directory on the filesystem. These files will be ones that get deleted first when the device runs low on storage. There is no guarantee when these files will be deleted. Note: you should not rely on the system deleting these files for you; you should always have a reasonable maximum, such as 1 MB, for the amount of space you consume with cache files, and prune those files when exceeding that space.

its up to you, its a FileHandle you can create erase update move rename the files. I can think of a filecheck like: if file004 exists, remove it, create new file

or if you prefer the softer way, only set the deleteOnExit() flag on files you dont need anymore.

edit: sure, there you go

File cachedir = getCacheDir();
for (File f : cachedir.listFiles()) {

setontouchlistener for x seconds

I'm trying to use setontouchlistener. What I would like to do if I hold an imagebutton for an example 5 seconds, I get alerted... this is how I would do it:

    final ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);

    imageButton1.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            // do something
            return false;

How can I implement something like this with setontouchlistener after x seconds?

Working solution:

imageButton1.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mTouchDownTime = event.getEventTime();
                    Log.v("CustomDebug", "Message: " + mTouchDownTime);

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    long elapsedTime = event.getEventTime() - mTouchDownTime;
                    Log.v("CustomDebug", "Message: " + elapsedTime);

                return false;   


onTouch gets called twice, the first time with a MotionEvent ACTION_DOWN and a second time with the MotionEvent ACTION_UP

so pseudocode:

if Event == ACTION_DOWN 
  saveTime = time();
elseif Event == ACTION_UP and time()-savetime > 5
  doStuff because the guy hold it for 5sec.

TextView with different textSize

Is this possible to set different textSize in one TextView? I know that I can change text style using:

TextView textView = (TextView) findViewById(R.id.textView);
Spannable span = new SpannableString(textView.getText());
span.setSpan(arg0, 1, 10, arg3);

I know the range start...end of text I want to change size. But what can I use as arg0 and arg3?



span.setSpan(new RelativeSizeSpan(0.8f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Facebook disabled my account.

Every time I log into facebook it tells me my account is temporarily unavailable due to security reasons it has been like this for over two weeks I have filled out the "someone hacked my account" and changed my password several times and it still will not let me log in. I have also tried filling in the text that the computer gives me and following that step it tells me that no verification methods are currently available, please come back later. It has been like this for over two weeks.I have been emailing facebook and leaving messages at their facebook headquarters everyday.Can someone please help me?


There are no "asynchronous" effects in the HashMap class. As soon as you put something in there, it's there. You should double- and triple- check to make sure that there are no threading issues.

The only other thing I can think of is that you're making a copy of the HashMap somewhere. The copy obviously won't be affected by you adding stuff into the original, or vice versa.