logo

For those who suffer from no sound after hibernate / sleep with a Intel HD-Audio Soundchip. I have this...

For those who suffer from no sound after hibernate / sleep with a Intel HD-Audio Soundchip.
I have this Setup on an GIGABYTE GA-C1037UN-EU.
Try this script, it will kill all soundapps and remove the intel soundmodule from the linux kernel.
After resuming the PC the script reloads the Module.

place the script in /etc/pm/sleep.d
call it 49_sound_fix

function kill_sound_apps() {
pidsnd=$(lsof | grep /dev/snd | awk '{ print $2 }')
pidmixer=$(lsof | grep /dev/mixer | awk '{ print $2 }')
piddsp=$(lsof | grep /dev/dsp | awk '{ print $2 }')
kill $pidsnd $pidmixer $piddsp
}

case "$1" in
hibernate|suspend)
kill_sound_apps
modprobe -r snd_hda_intel
;;
thaw|resume)
modprobe snd_hda_intel
;;
*)
;;
esac

exit $?

chmod +x /etc/pm/sleep.d/49_sound_fix
[#w]

Setting up a Socks Proxy over SSH on Windows If we wanna open the Tunnel automatically on Startup we...

Setting up a Socks Proxy over SSH on Windows

If we wanna open the Tunnel automatically on Startup we need passwordless ssh login with Private/Public Keys
For this use puttygen.exe from http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

Get plink.exe to
Its a command line interface for putty

First create a new Key pair with Puttygen.exe, add the public key to your servers .ssh/authorized_keys
If the .ssh directory doesnt exist, use ssh example.com and say Yes

Store the private Key on your PC.

With
plink.exe -ssh <proxyIp> -l <user> -i <path/to/privateKey.ppk> -D <localport> -N
we create the Tunnel, -N supresses the login shell

we now could simple put that in a .bat file and run it on startup, but it would spawn a cmd shell that must stay open.

A better solution is a Windows Service,

load the Windows Server 2003 Resource Kit Tools
http://www.microsoft.com/en-us/download/details.aspx?id=17657

Swith into the Tools Directory with a root cmd shell
instsrv.exe <TunnelServiceName> <fullPathTo>srvany.exe

The Service is now installed, we need to configure it.

save that as *.reg file

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\<ServiceName>\Parameters]
"Application"="<pathTo>plink.exe"
"AppParameters"="-ssh <proxyIp> -l <user> -i <path/to/privateKey.ppk> -D <localport> -N"
"AppDirectory"="<pathToPlink.exe>"

Now the Service automatically Starts on Bootup and opens the Tunnel. On Standby or Hibernation though, the Tunnel just collapse.
For this we need to Trigger a Service Restart on relogging. We could also react on the Power event but that covers not all Power Saving Features.

SocketRestarter.xml:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2013-11-01T23:20:18.1334498</Date>
    <Author>##PCName\##USERNAME</Author>
  </RegistrationInfo>
  <Triggers>
    <SessionStateChangeTrigger>
      <Enabled>true</Enabled>
      <StateChange>SessionUnlock</StateChange>
    </SessionStateChangeTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>##PCName\##USERNAME</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\Windows\System32\sc.exe</Command>
      <Arguments>stop ###ServiceName###</Arguments>
    </Exec>
    <Exec>
      <Command>C:\Windows\System32\sc.exe</Command>
      <Arguments>start ###ServiceName###</Arguments>
      <WorkingDirectory>4</WorkingDirectory>
    </Exec>
  </Actions>
</Task>

Now we can use localhost <Port> as Socks5 Proxy, Cool! =)
[#w]

PuTTY Download Page


Displaying the correct Size of a Samba Share with 2 Harddrives

Add this to your Samba Share definition inside /etc/samba/smb.conf

dfree command = /usr/local/bin/dfree.sh
dfree.sh:

#!/bin/bash
HDD1total=`df $1 | tail -1 | awk '{print $(NF-4)}'`
HDD2total=`df /path/to/secondHDD | tail -1 | awk '{print $(NF-4)}'`

HDD1av=`df $1 | tail -1 | awk '{print $(NF-2)}'`
HDD2av=`df /path/to/secondHDD | tail -1 | awk '{print $(NF-2)}'`

echo $((HDD1total + HDD2total)) $((HDD1av + HDD2av))
Samba now uses the custom dfree script to determine the Available and Total space for that Samba share.

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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.travel_map_activity);
        mapView = (MapView)findViewById(R.id.travelMapView);
    }
}

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

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.travel_map_activity);
    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

thanks

androidgoogle-mapsandroid-mapview

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.


New Google Maps API for Android #android   #androiddev A new Google Maps API is available for Android...

New Google Maps API for Android
#android   #androiddev  

A new Google Maps API is available for Android. It brings long awaited features such as vector-based 2D maps, 3D maps and fragments support. Go check it out!

http://android-developers.blogspot.fr/2012/12/new-google-maps-android-api-now-part-of.html

Android Developers Blog: New Google Maps Android API now part of Google Play services


#androiddev #droidcon #polaris #clustering  I've had to hack quite a few things into Google Maps for...

#androiddev #droidcon #polaris #clustering 

I've had to hack quite a few things into Google Maps for various Android projects and I always meant to open source something but never quite got round to it. Now that +Cyril Mottier has produced this fine Polaris project (enjoyed your Droidcon UK project btw!) I thought I'd contribute a cool and often requested maps feature: Clustering.

If you're already using Polaris and want to enable clustering all you have to do is create a Clusterer object and feed it your original Annotations (OverlayItems) and it will give you back a reduced set (replacing overlapping ones with cluster spots) so that you can add them to your PolarisMapView.

You can optionally create a custom ClusterConfig object which tells the clusterer the thresholds for low, medium & high cluster spots) e.g. 

Clusterer clusterer = new Clusterer(mMapView, annotations, new ClusterConfig(4, 8));
    mMapView.setAnnotations(clusterer.getClusters(), R.drawable.map_pin_holed_blue);

If you need it now, then you can take a look at:
https://github.com/damianflannery/Polaris/tree/clustering

with sample apk here:
https://github.com/damianflannery/Polaris/downloads

I already sent a pull request to Cyrill. Hopefully it will be integrated into Polaris proper when he gets some free time :)

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?

androidprocessreceiver

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;
myDatabase.beginTransaction();
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.clear();
       someValues.put("dbfield2", 2);

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

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

Is there a simpler/better way of doing this?

androiddatabasetransactionssqlite3

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;

    bulkSqlDB.beginTransaction();
    try {
        for (ContentValues cv : values) {
            insert(uri, cv);
        }
        bulkSqlDB.setTransactionSuccessful();
        numInserted = values.length;
    } finally {
        getContext().getContentResolver().notifyChange(uri, null);
        bulkSqlDB.endTransaction();
    }
    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;
          content.setLayoutParams(params);
        }

        if (!getSupportActionBar().isShowing()) {
          params.topMargin = 0;
          content.setLayoutParams(params);
        }
      } 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;
            content.setLayoutParams(lp);
          }

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

          if (!getActionBar().isShowing()) {
            lp.topMargin = 0;
            content.setLayoutParams(params);
          }
        }

      }

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

androidandroid-layoutandroid-actionbarandroid-4.2-jelly-bean

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

content.setLayoutParams(params); should read
content.setLayoutParams(lp);

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>
</style>

is there a way to set

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

to false inside the Activity/Fragment?

androidandroid-layoutactionbarsherlock

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();
observer.addOnGlobalLayoutListener(layoutListener);

// 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() {
    @Override
    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;
            listView.setLayoutParams(params);
        }
        // The action bar doesn't update its height when hidden, so make top-margin zero
        if (!getActivity().getActionBar().isShowing()) {
          params.topMargin = 0;
          listView.setLayoutParams(params);
        }
    }
};

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"); 
    }
}

Thanks

android

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.

@Override
public void onAttach(Activity activity) {
    super.onAttach(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

mListener.onArticleSelected(...);

Hope that helps, further infos here


Over the past few Months i tested varius Music Streaming Providers and want to write down a few of my...

Over the past few Months i tested varius Music Streaming Providers and want to write down a few of my impressions.

The first Service i've tested was #Pandora. Pandora itself is a pure Internetradio so you cant search and listen to a specific song. You search for your favorite Artists and create a radiostation that will play only Songs of the same sort of Music Genre. Pandora uses a special algorithm to categorize the Songs, the Project behind is the 'Music Genome Projects'. The Player itself runs Inside the Browser and there is a App for your Mobile Device. A Ad is played after 3-5 Songs each. As a result: The 'algorithm' itself dont work so well for me. Sure it plays only Songs from the same Genre but in comparison to other Streaming Services it generates the weaker result.

The next Service that i have tested was #Spotify. Spotify was one of the first Music Streaming Services and has a quite large Music Libary. Unlike Pandora you can search for a specific Song or Album inside the Spotify Player. The Player itself has the look and feel of Winamp or the Windows Mediaplayer. Songs are played either direct from the Search or with the Radio feature. Radiostations behave the same like the stations inside Pandora but with better Songchoices. I cant describe the 'better' but i've found me listening to a Spotify Radio for Hours not realizing that i listening to a Radio. The Player Programm also support so called Apps that enhance the Player, Examples are Tunewiki (You see the Lyrics with the actual line highlighted, great for Karaoke :P) or Sounddrop were you can Join a Genre Room and hangout with other People that like this sort of Music. You can Vote for the Next Song played or nominate Someone to be the DJ, really cool stuff.
Another thing that gets my Heart is the sleek Control inside the Player. A example: When i listening to a Radio and i want to listen to a specific Song i either can choose to queue that Song up or played direct. When the Song has finished the Radio continuing to play. But when i search for an Album it plays the the next Song when finished the first selected Song. Little features that make me smile :-).
On the Downside: Spotify requires a Facebook Account and has many Social Functions like sharing Playlists, Friendslists, it surfs literally on the Social Media wave. Another big bummer is that Spotify follows the P2P approach. Thats means that your Client will upload Songs that you have in your Cache to other Spotify Users (also if you have a Premium Account!). The Files inside the Cache are encrypted and the Songs are paid but thats a big problem when you want to use Spotify at work or other shared Networks.

Yesterday i've tested #Deezer, it also has a Browser Interface and mobile Support, handling is simmilar to Spotify but the algorithm for choosing new Songs when listening to Radio is also weaker than Spotify. Deezer also require a Facebook Account to register. A cool feature in the Radio Section is that you can dislike some Artists that are simmilar to your choosen Genre.

PS: For all German Users: Spotify will launch tomorrow in DE!

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:

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

And the Class SearchQuery:

@XmlRootElement
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 :(

restglassfishxml-parsingjersey

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

TESTClass is mapped to tESTClass inside the XML Entity


Got problems including the +1 Button on my website. I slowed down the loading times alot, it was slightly...

Got problems including the +1 Button on my website. I slowed down the loading times alot, it was slightly my fault because i have no pagination but i managed to get a good solution.
I load the Buttons explicit and dynamically when the article comes into sight. #JQuery Waypoint is the libary to acomplish that with ease.
Also i added a Google Badge for +Android Developers
What do you think? Its slidely slower on the loadtimes.

Posts - corazza.de


Finally getting my Radius Location #JPA #JPQL Query working! yay I wanted to get all locations ne...

Finally getting my Radius Location #JPA #JPQL Query working! yay

I wanted to get all locations near my current location inside a given Radius.

The key is that you can call SQL Functions inside JPQL with the FUNC function. Also you dont need to join anything and you have to evaluate your distance inside the WHERE not prepairing the distancevalue inside the SELECT.

return em.createQuery(
"SELECT i FROM Index as i"
+ " where "
+ "( 6371 * FUNC('acos', FUNC('cos', FUNC('radians', <yourlat>) ) * FUNC('cos', FUNC('radians',i.location.lat ) ) * "
+ "FUNC('cos',FUNC('radians',i.location.lng ) - FUNC('radians',<yourlng>) ) + FUNC('sin', FUNC('radians',<yourlat>) ) * "
+ "FUNC('sin',FUNC('radians',i.location.lat ) ) ) ) < :radius")
.setParameter("radius", radius)
.getResultList();

the 6371 is the km constant, if you need miles you can set it to 3959

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)

androidlistviewclicktextviewrefresh

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

pseudo

getView() {
    onClickListener(Event..) {
      pointsTextView.setText(..points+1..)
    }

}

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?

androidandroid-layoutandroid-button

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.

androidmime-types

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


Reshared post from Derya Unutmaz Researchers have recently discovered four new chameleon speci...

Researchers have recently discovered four new chameleon species, which rank among the world’s tiniest reptiles. Adults of the smallest species are just over an inch from snout to tail.

The four new species belong to the genus Brookesia, also known as the leaf chameleons, which live in remote rainforests in northern Madagascar. The genus is already known to contain some very small species, with members typically resembling juvenile versions of larger species.

As small as these guys are, a super-tiny dwarf gecko found in the British Virgin Islands might be just a tad more wee.

source: http://www.wired.com/wiredscience/2012/02/tiny-chameleons/


Today i thought about how many Tabs i have opened in my Browser, things started to get messy. I c...

Today i thought about how many Tabs i have opened in my Browser, things started to get messy. I came across this nifty little line of code to count my tabs:
javascript:var w=Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator).getEnumerator('navigator:browser'),t=0;while(w.hasMoreElements())t+=w.getNext().document.getElementById("content").mTabs.length;alert("You have "+t+" tabs open");

oh, and only 1,3GB Ram usage on Firefox 10.0! Not slaggy at all.