Wednesday, August 8, 2012

create nice looking ListView filter on Android

First, you need to create an XML layout that has both an EditText, and a ListView.
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Pretty hint text, and maxLines -->
    <EditText android:id="@+building_list/search_box" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="type to filter"
        android:inputType="text"
        android:maxLines="1"/>

    <!-- Set height to 0, and let the weight param expand it -->
    <!-- Note the use of the default ID! This lets us use a 
         ListActivity still! -->
    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" 
         /> 
</LinearLayout>
This will lay everything out properly, with a nice EditText above the ListView. Next, create a ListActivity as you would normally, but add a setContentView() call in the onCreate() method so we use our recently declared layout. Remember that we ID'ed the ListView specially, with android:id="@android:id/list". This allows the ListActivity to know which ListView we want to use in our declared layout.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.filterable_listview);

        setListAdapter(new ArrayAdapter<String>(this,
                       android.R.layout.simple_list_item_1, 
                       getStringArrayList());
    }
Running the app now should show your previous ListView, with a nice box above. In order to make that box do something, we need to take the input from it, and make that input filter the list. While a lot of people have tried to do this manually, most ListView Adapter classes come with a Filter object that can be used to perform the filtering automagically. We just need to pipe the input from the EditText into the Filter. Turns out that is pretty easy. To run a quick test, add this line to your onCreate() call
adapter.getFilter().filter(s);
Notice that you will need to save your ListAdapter to a variable to make this work - I have saved my ArrayAdapter<String> from earlier into a variable called 'adapter'.
Next step is to get the input from the EditText. This actually takes a bit of thought. You could add an OnKeyListener() to your EditText. However, this listener only receives some key events. For example, if a user enters 'wyw', the predictive text will likely recommend 'eye'. Until the user chooses either 'wyw' or 'eye', your OnKeyListener will not receive a key event. Some may prefer this solution, but I found it frustrating. I wanted every key event, so I had the choice of filtering or not filtering. The solution is a TextWatcher. Simply create and add a TextWatcher to the EditText, and pass the ListAdapter Filter a filter request every time the text changes. Remember to remove the TextWatcher in OnDestroy()! Here is the final solution:
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.filterable_listview);

    filterText = (EditText) findViewById(R.id.search_box);
    filterText.addTextChangedListener(filterTextWatcher);

    setListAdapter(new ArrayAdapter<String>(this,
                   android.R.layout.simple_list_item_1, 
                   getStringArrayList());
}
private TextWatcher filterTextWatcher = new TextWatcher() {

    public void afterTextChanged(Editable s) {
    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        adapter.getFilter().filter(s);
    }
};
@Override
protected void onDestroy() {
    super.onDestroy();
    filterText.removeTextChangedListener(filterTextWatcher);
}

convert Drawable to Bitmap

This piece of code helps.
 
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                           R.drawable.icon_resource);
Edit: Here a version where the image gets downloaded.
String name = c.getString(str_url);
URL url_value = new URL(name);
ImageView profile = (ImageView)v.findViewById(R.id.vdo_icon);
if (profile != null) {
    Bitmap mIcon1 =
        BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
    profile.setImageBitmap(mIcon1);
}
 
This converts a BitmapDrawable to a Bitmap.
Drawable d = ImagesArrayList.get(0);  Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
 

transparent activity android

Add the following style In your res/values/styles.xml file (if you don’t have one, create it.) Here’s a complete file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
  </style>
</resources>
(the value @color/transparent is the color value #00000000 which I put in res/values/color.xml file. You can also use @android:color/transparent in later Android versions)
Then apply the style to your activity, for example:
<activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent">
...</activity>

pick a image from gallery (SD Card) for my app in android

Here's some sample code on how to do that:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case REQ_CODE_PICK_IMAGE:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
        }
    }
}

set HttpResponse timeout for Android in Java

HttpGet httpGet = new HttpGet(url);
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);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().
httpClient.setParams(httpParameters);

check internet access on android

here is the code which will help to check internet available

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

Tutorials and libraries for OpenGL-ES games on Android

Android tutorials:
Other Android OpenGL-ES information:
iPhone OpenGL-ES tutorials (where the OpenGl-ES information is probably useful):
As for libraries which a beginner might use to get a simpler hands-on experience with OpenGL-ES, I have only found Rokon, which is recently started, thus has many holes and bugs. And it's gnuGPL licensed (at the moment) which means it cannot be used, if we wish to sell our games.

1.  INsanityDesign
2.  nehe

Monday, August 6, 2012

Difference between Corona, Phonegap, Titanium



  1. PhoneGap is not just a native wrapper of a web app. Through the PhoneGap javascript APIs, the "web app" has access to the mobile phone functions such as Geolocation, Accelerometer Camera, Contacts, Database, File system, etc. Basically any function that the mobile phone SDK provides can be "bridged" to the javascript world. On the other hand, a normal web app that runs on the mobile web browser does not have access to most of these functions (security being the primary reason). Therefore, a PhoneGap app is more of a mobile app than a web app. You can certainly use PhoneGap to wrap a web app that does not use any PhoneGap APIs at all, but that is not what PhoneGap was created for.
  2. Titanium does NOT compile your html, css or javascript code into "native bits". They are packaged as resources to the executable bundle, much like an embedded image file. When the application runs, these resources are loaded into a UIWebView control and run there (as javascript, not native bits, of course). There is no such thing as a javascript-to-native-code (or to-objective-c) compiler. This is done the same way in PhoneGap as well. From architectural standpoint, these two frameworks are very similar.

     3. Corona SDK is a software development kit created by Walter Luh, co-founder of Corona Labs (formerly known as Ansca Mobile). It allows software programmers to build mobile applications for the iPhone, iPad, and Android devices.
    Corona lets developers use integrated Lua, layered on top of C++/OpenGL, to build graphically rich applications that are also lightweight in size and quick in development time. The SDK does not charge per-app royalty or impose any branding requirement, and has a subscription-based purchase model that allows new features to be rolled out immediately to users.

hide Android Soft Keyboard

hide Android Soft Keyboard

 You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your edit field.

InputMethodManager imm = (InputMethodManager)getSystemService(
      Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).

 Also useful for hiding the soft keyboard is:

getWindow().setSoftInputMode(
      WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
This can be used to suppress the keyboard until the user actually touches the edittext view.


python on android

Python on Android

http://kivy.org/#home
"Open source library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps."
"Kivy is running on Linux, Windows, MacOSX and Android. You can run the same [python] code on all supported platforms."
Kivy Showcase app
https://market.android.com/details?id=org.kivy.showcase&hl=en

There is also the new ASE project, it looks awesome, and has some integration with native Android components. Android Scripting Environment

Difference between px, dp, dip and sp in Android

A dimension value defined in XML. A dimension is specified with a number followed by a unit of measure. For example: 10px, 2in, 5sp. The following units of measure are supported by Android:
dp
Density-independent Pixels - An abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen's dpi. Likewise, when on a lower density screen, the number of pixels used for 1dp is scaled down. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. In other words, it provides consistency for the real-world sizes of your UI elements across different devices.
sp
Scale-independent Pixels - This is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference.
pt
Points - 1/72 of an inch based on the physical size of the screen.
px
Pixels - Corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.
mm
Millimeters - Based on the physical size of the screen.
in
Inches - Based on the physical size of the screen.
Note: A dimension is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine dimension resources with other simple resources in the one XML file, under one <resources> element.

“Debug certificate expired” error in Eclipse Android plugins

Here is the solution for your problem

Delete your debug certificate under ~/.android/debug.keystore on Linux and Mac OS X; the directory is something like %USERPROFILE%/.androidon Windows.
The Eclipse plugin should then generate a new certificate when you next try to build a debug package. You may need to clean and then build to generate the certificate.