Best android questions in October 2011

Android Unknown Command 'crunch'

23 votes

I just installed Eclipse and Android SDK in Mac OS X.

I imported the project to Eclipse and i get the Unknown command 'crunch' error while running the project.

How should I solve this issue.

Please help me

I just update "Android SDK Platform-Tool" to 8 Rev and "Android Asset Packaging Tool" from android sdk manager,

and then it works.

Have a try!

How to create a AVD for android 4.0

19 votes

Android 4.0 is now released. I have just updated my ADT plugin and downloaded the 4.0 SDK. But when I try to create a AVD for android 4.0, eclipse tell me 'Unable to find a 'userdata.img' file for ABI armeabi to copy into the AVD folder'.

I found d:\android-sdk-windows\platforms\android-14 missing 'images' folder which other versions have. This folder may have 'userdata.img' that create a AVD should have.

So, my question is, where should I to get 'userdata.img', and how to create a AVD for android 4.0?

Thank you:)

I just did the same.

If you look in the "Android SDK Manager" in the "Android 4.0 (API 14)" section you'll see a few packages.

One of these is named "ARM EABI v7a System Image"

This is what you need to download in order to create an android 4.0 virtual device.

the android sdk download system

Scala, Android and Eclipse

17 votes

I've started learning Scala, and I... I think I'm in love. I've only coded small test snippets so far, but since I currently working in Android development, what I really want to do is try my hand at writing Android applications in Scala.

I've found articles and questions on the matter, but mostly referring to older versions of the three tools (Android SDK/Scala/Eclipse), so the general question is:

Is anybody coding Android apps in Scala right now, with the latest SDK, Scala 2.9 and Eclipse Indigo? How viable is it?

And, in particular:

  1. How's the interaction/integration between Scala's features and the Android library?

  2. What's the state of the Scala plugin for Eclipse? I've read all the features you'd expect are there, but I'd like to know first-hand stories, specially about the debugger.

  3. How well does the build process (scala to java to dalvik, ant, proguard, etc.) automate?

Thanks!

We are using Scala heavily to test our Android code - you can read a writeup of how we're doing so here. We use Ant or SBT to compile - there's an excellent SBT plugin for Android development.

Having said all of that, I'm not sure that I would recommend Scala for production Android development. In particular Scala 2.9.x is basically unusable as there is no good way to get the libraries to work on Android. You can read about the issue here.

It's a real pity, as Android development would benefit considerably from Scala if we could get it working properly.

Filling the data in an Android bitmap as quickly as possible from C

13 votes

I've managed to get an android.graphics.Bitmap created and I'm successfully filling it via the SetPixels command.

The problem is that I start off with RGBA data. I then create a jintArray. I then call SetIntArray (effectively memcpying the data into the buffer). Then, finally, I call setPixels to actually set the pixels (which presumably causes another copy).

one big issue with doing this is that whether I used R8G8B8A8 or R5G6B5 or A8 I still have to convert my pixel data to R8G8B8A8 data.

Ideally I'd like a way to fill the buffer using only one copy and allow me to do it without doing the pixel format conversion.

Is there any way to directly get at the buffer data contained in a Bitmap? I see there is a function GetDirectBufferAddress in the JNI, but the documentation I can find on it suggests its limited to a java.nio.buffer. Can I directly get at the pixel data using this function? Perhaps by getting the internal buffer used by the Bitmap class?

Is my only way of using this to create a Global Ref'd Java.nio.buffer then each time I want to update, copy my pixel data into it and then use copyPixelsFromBuffer? This still involves 2 copies but can, at least, eliminate the pixel format change. Is this going to be any more efficient than the method I'm already using?

Is there an even better way of doing it?

Btw, I AM aware of the fact I can use the functions in < android/bitmap.h > but I would really like to not lose support for Android 2.1 and Android 2.2 ...

Cheers in advance!

Here comes a dirty yet working solution, working from Android 1.5 up to 4.0. Code is in C++.

                              //decls of some partial classes from Skia library
class SkRefCnt{
public:
   virtual ~SkRefCnt(){}
private:
   mutable int fRefCnt;
};

//----------------------------

class SkPixelRef: public SkRefCnt{
public:
   virtual class Factory getFactory() const;
   virtual void flatten(class SkFlattenableWriteBuffer&) const;
protected:
   virtual void* onLockPixels(class SkColorTable**) = 0;
   virtual void onUnlockPixels() = 0;
public:
   void *GetPixels(){
      SkColorTable *ct;
      return onLockPixels(&ct);
   }
};

jobject java_bitmap;  //your Bitmap object
jclass java_bitmap_class = env.GetObjectClass(java_bitmap);
class SkBitmap;
SkBitmap *sk_bitmap = (SkBitmap*)env.CallIntMethod(java_bitmap, env.GetMethodID(java_bitmap_class, "ni", "()I"));
SkPixelRef *sk_pix_ref;
sk_pix_ref = (SkPixelRef*)((int*)sk_bitmap)[1];
// get pointer to Bitmap's pixel memory, and lenght of single line in bytes
int buffer_pitch = env.CallIntMethod(java_bitmap, env.GetMethodID(java_bitmap_class, "getRowBytes", "()I"));
void *buffer = sk_pix_ref->GetPixels();

Android Dependencies

11 votes

If I create an app that depends on another app or apps (eg: the Facebook and Twitter apps), yet they are not installed, is there a method of checking for those dependencies and installing them at the same time as my own app?

I did this in my application which requires the zxing scanner app to be installed. You will want this inside your onclick or ontouch:

try{
    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    intent.setPackage("com.google.zxing.client.android");
    startActivityForResult(intent, 0);
} catch (Exception e) {
    createAlert("Barcode Scanner not installed!", "This application uses " +
    "the open source barcode scanner by ZXing Team, you need to install " +
    "this before you can use this software!", true);
}

which calls

public void createAlert(String title, String message, Boolean button) {
    // http://androidideasblog.blogspot.com/2010/02/how-to-add-messagebox-in-android.html
    AlertDialog alertDialog;
    alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle(title);
    alertDialog.setMessage(message);
    if ((button == true)) {
        alertDialog.setButton("Download Now",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                Intent browserIntent = new Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("market://search?q=pname:com.google.zxing.client.android"));
                startActivity(browserIntent);
            }
        });
    }
    alertDialog.show();
}

Then after sorting out all that code out I realise you asked for it to be installed at the same time as your app. Not sure if i should post this code, but it may be helpful

How to get scaled Bitmap from ImageView

9 votes

I am having a Activity which has a custom ImageView defined in the XML for Pinch Zoom functionality on an image. Now, my problem is that I want to fetch the scaled Bitmap from the Pinch Zoom functionality. For example if the user peforms zooming on the Image, then I want to store the exact size and the position of the Image as Bitmap.

This is my custom ImageView declared in XML.

<com.cam.view.PinchZoom_ImageView 
  android:id="@+id/gallery_selected_image_view"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:src="@drawable/icon"
  android:scaleType="center"
 />

UPDATE:

I am trying the below code to get the scaled Image, but It returns a Blank Bitmap.

        pinchZoom.setDrawingCacheEnabled(true);
        pinchZoom.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        pinchZoom.layout(0, 0, pinchZoom.getMeasuredWidth(), pinchZoom.getMeasuredHeight());
        pinchZoom.buildDrawingCache(true);
        Bitmap_gallery_Item = Bitmap.createBitmap(pinchZoom.getDrawingCache());
        pinchZoom.setDrawingCacheEnabled(false);

Any help would be appreciated. Thanks

Well, finally I can't believe that it was just a one line code. I finally succeeded using the matrix. The solution is very simple that I was storing the translation and scaling of the Image in a matrix. So, I declared that final matrix as public static and used that matrix to create draw a Bitmap on canvas.

        Canvas comboImage = new Canvas(cs);
        background = Bitmap.createScaledBitmap(background, width, height, true);
        comboImage.drawBitmap(background, 0, 0, null);
        comboImage.drawBitmap(foreground, PinchZoom_ImageView.matrix, null);

As you can see here PinchZoom_ImageView.matrix. It is a matrix that contains my final position of the scaled and translated image which I had declared as public static.

Android Fragment standard transition not animating

9 votes

Im using the v4 android compatibility library to develop a tablet UI using fragments specificaly for Android 2.2 devices and up.

Everything is working as it should, except that I cant get any animations to work, not even the standard animations.

Code:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ABCFragment abcFragment = new ABCFragment();
    ft.replace(R.id.main_frame_layout_fragment_holder,abcFragment);     
    ft.addToBackStack(null);
    ft.commit();

Instead of using a transit animation, the fragment freezes for about a second and the just disapears and the new one appears.

Using ft.setCustomAnimations(android.R.anim.slide_in_left,android.R.anim.slide_out_right); doesnt work either.

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.synergygb.mycustomapp"
android:id="@+id/LinearLayout01" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical"
android:gravity="bottom">
<FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/main_frame_layout_fragment_holder">
</FrameLayout>
<!-- OTHER FIXED UI ELEMENTS-->
</RelativeLayout>

I read that the custom animation were broken in the compatibility library, but no one seems to be having issues with the standard transitions. I've tested this on a 3.2.1 Motorola Xoom, 2.3 Galaxy Tab 7", 2.2 emulator, and even on a HTC G2 with 2.3.4.

What could be wrong here, I dont see anyone else having these issues.

I finally got this to work after much trial and error.

First and foremost, get the lastest ACL, it did fix custom animations, and while this wasnt my exact problem, once those worked I ended up using them instead of standard transitions.

Right now im using:

ft.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out,android.R.anim.fade_in,android.R.anim.fade_out);

The key to making it work on both Android 2.1, 2.2 and 2.3, as well as Android 3.0+ was to do the following:

  • Make sure you are using ONLY API´s available to the lowest API LEVEL you wish to support (in my case 2.1).
  • Compile using Android 3.0.
  • In the manifest file, set android:hardwareAccelerated="true" inside your application tag.

Fragment animations now work on all devices. If you dont set the extra info in the application tag, the animation will ocurr, but in a very very choppy way, making it seem it didnt happen at all.

Hope this helps someone in the future!

As a note, there are some API checking tools so you are sure you arent using any APIs that arent available to you. I prefer to work on 2.1 so the IDE doesnt show anything I cant use, once I have stable code I jump back to compiling on 3.0

Creating a SoftKeyboard with Multiple/Alternate characters per key

9 votes

I've followed the examples on developer.android.com regarding Input Methods and played with the SoftKeyboard sample application. These together give more than enough information regarding the creation of simple keyboard.

What I can't see in the API is the ability to create alternate / multiple characters per key which is available on the standard Keyboard (LatinIME Keyboard).

enter image description here

The above image is the result of a long press on the "a" key. When you long press a key it's possible to populate a popup with alternate characters.

enter image description here

It is also possible to give a popup hint on some keys which will prompt the user to press and hold a key in order to get the popup menu.

So far I haven't found a single source of information on how this is achieved, hopefully someone will be able to give me a head start, until then I'll follow the source code of the inbuilt keyboard and see if I can reverse engineer it.

Edit: Would help if developer.android.com 's link to the LatinIME Keyboard didn't link to a picture of a Sheep :) Actual source code for LatinIME.java.

Edit 2: More as a reference than anything else, this is the sequence I believe a usual longPress action goes through in order to show the popup keyboard in KeyboardView.java:

onTouchEvent()
onModifiedTouchEvent()
mHandkler.handleMessage() with MSG_LONGPRESS
openPopupIfRequired() 
onLongPress()

Edit 3:

I still haven't figured this out - How do you add label suggestions to keys? An answer suggests it isn't built into the API and indeed I haven't found the codeto do this. However the Keyboard on 2.3.4 (API 10) shows this functionality being implemented:

enter image description here

Would very much like to figure out how IT does it but it isn't anywhere in the onDraw() method that I can see - which makes me believe it's being written outside of the KeyboardView element. I can't however find the layout file used to display the KeyboardView element on the inbuilt keyboard - If anyone knows where to find this perhaps that will give me the clue I need.

Edit 4: Moved key Preview question here as it's slightly off topic:

How do you disable / customise the Soft keyboard key preview window?

For each key you wish to have a popup keyboard you should can define popupCharacters and popupKeyboard:

<Key android:keyLabel="("
    android:popupKeyboard="@xml/keyboard_popup_template"
    android:popupCharacters="[{&lt;" />

Which references res/xml/keyboard_popup_template.xml - an XML representation of the keyboard to attached to the <KeyboardView> of the popup:

<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="10%p"
    android:horizontalGap="0px"
    android:verticalGap="0px"
    android:keyHeight="56dp">
</Keyboard>

The layout of the popup is derived from keyboard_popup_keyboard.xml as standard. If you wish to change this however you can add this to the original <KeyboardView>:

<android.inputmethodservice.KeyboardView
    android:id="@+id/keyboard"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="#FF272727"
    android:popupLayout="@layout/keyboard_popup_keyboard" />

The only solution I've been able to knock together to show key previews (Without entirely rewriting the KeyboardView source code) is below:

Wrapping the <KeyboardView> tag with a <FrameLayout> with a height specified by multiplying the keyHeight by the amount of rows. Inside this tag I've simply created a LinearLayout to hold rows, then a LinearLayout for each row containing a TextView with a weight equal to the %p value specified for each <Key>:

<TextView android:text="!" style="@style/Custom.Widget.KeyboardKeyOverlay"  android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="10"/>

And styled:

<style name="NetsupportBlue.Widget.KeyboardKeyOverlay">
    <item name="android:background">@android:color/transparent</item>
    <item name="android:textColor">#FFAAAAAA</item>
    <item name="android:paddingRight">6dp</item>
    <item name="android:paddingTop">4dp</item>
    <item name="android:textSize">10sp</item>
    <item name="android:gravity">right</item>
    <item name="android:textStyle">bold</item>
</style>         

Which produces this:

enter image description here

I won't be happy until I've managed to implement this in the same way as the System Keyboard does!

Android take screen shot programatically

9 votes

First off i am writing a root app so root permissions are no issue. I've searched and searched and found a lot of code that never worked for me here is what i've pieced together so far and sorta works. When i say sorta i mean it makes an image on my /sdcard/test.png however the file is 0 bytes and obviously can't be viewed.

public class ScreenShot extends Activity{

View content;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blank);
    content = findViewById(R.id.blankview);
    getScreen();
}

private void getScreen(){
    Bitmap bitmap = content.getDrawingCache();
    File file = new File("/sdcard/test.png");
    try 
    {
        file.createNewFile();
        FileOutputStream ostream = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, ostream);
        ostream.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}
}

Any help on how i can take a screen shot in android via code would be greatly appreciated thank you!

===EDIT===

The following is everything i'm using the image is made on my sdcard and is no longer 0bytes but the entire thing is black there is nothing on it. I've bound the activity to my search button so when i'm some where on my phone i long press search and it is supposed to take a screen shot but i just get a black image? Everything is set transparent so i'd think it should grab whatever is on the screen but i just keep getting black

Manifest

<activity android:name=".extras.ScreenShot"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    android:noHistory="true" >
    <intent-filter>
        <action android:name="android.intent.action.SEARCH_LONG_PRESS" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    </activity>

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#00000000"
  android:id="@+id/screenRoot">    
</LinearLayout>

Screenshot class

public class ScreenShot extends Activity{

View content;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screenshot);
    content = findViewById(R.id.screenRoot);
    ViewTreeObserver vto = content.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {
        content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        getScreen();
      }
    });
}

private void getScreen(){
    View view = content;
    View v = view.getRootView();
    v.setDrawingCacheEnabled(true);
    Bitmap b = v.getDrawingCache();             
    String extr = Environment.getExternalStorageDirectory().toString();
    File myPath = new File(extr, "test.jpg");
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
    }catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finish();
}
}

Never got the answer I was looking for the code provided did work for screenshoting my own app however what i wanted was to do it with root outside my app. I then realized cm natively had screenshoting so i took a look at the rom and realized there was a binary they just ran in a shell and it captured the screen so i just compiled it myself and ended up using that

Thank you everyone for the help

Does Android lower the download rate when the screen turns off?

8 votes

I observed that I can download a file faster if I use wget with the screen on application, that acquires a screen dim wake lock than doing the same without this application and having the screen turned off.. I downloaded exactly the same file (from my apache web server) and the time is almost two times faster when I used the screen on application. To download the file I use a ported versions of wget.. And here is my question:

Does Android lower the download rate when the screen turns off?

Or due to the fact that the screen on app acquires a wake lock, forces the CPU to be always on, so more CPU cycles are spent for the download process.. I am a little bit confused..

Short answer is yes, Android sometimes does lower the download rate when the screen turns off. According to this Android bug report (starred by 90 users),

It seems that, even with "Wifi Sleep Policy" set to "Never", the wifi on some Android devices will enter Power Save mode (a.k.a. PSP mode) when the screen turns off.

PSP mode apparently causes the wifi device to sleep, but wake up periodically and ask its access point to deliver packets that were addressed to to the device while it was asleep. This necessarily causes additional, "spiky" network latency. This additional latency means that some network-oriented applications experience problems when the screen turns off.

This more or less correlates with the behavior you're describing. This issue affects only some phones, not all, and only some versions of Android. I suggest you visit the bug report above, there is a long discussion of this issue.

How to solve this issue

There is a workaround for Android 2.3 at least: You need to acquire WIFI_MODE_HIGH_PERF lock:

In this Wi-Fi lock mode, Wi-Fi will be kept active as in mode WIFI_MODE_FULL but it operates at high performance with minimum packet loss and low packet latency even when the device screen is off. This mode will consume more power and hence should be used only when there is a need for such an active connection.

CPU clock scaling in Android

Android is based on Linux kernel, and uses CPUFreq Governors to adjust CPU frequency to conserve the battery. Exact policies and frequencies vary from vendor to vendor and are subject to change. There are also utilities that let you adjust these policies, but they all require rooted phone. Usually, Android phones lower CPU frequency and use "powersave" governor when the screen is turned off.

However, I don't think network traffic on a phone is CPU-bound. That is, even when in power-safe mode, network throughput is a bottleneck, not CPU speed.

How to scroll layout which have 3 list view

8 votes

I have one layout. This layout contain 3 list view with the height of wrap_content data in the listview are not fix. When listview have a liitel huge data at that time the data goes to underneath and the data can not able to see,so i want to scroll the view with all three listview how it is possible.

Any one have an idea about this.

This is my view which contain 3 list view, now it's with the less data but when the data will make huge at that time the last listview have a problem to view. I want to scroll the grey colored view...

enter image description here

Use linear layout instead of listview in your xml file. This is your xml file.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:id="@+id/scr" android:layout_height="fill_parent"
    android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:layout_width="fill_parent"
        android:id="@+id/r2" android:orientation="vertical"
        android:layout_height="fill_parent" android:paddingTop="100dip"
        android:paddingBottom="100dip">
        <LinearLayout android:layout_width="fill_parent"
            android:id="@+id/l1" android:orientation="vertical"
            android:layout_height="wrap_content" android:layout_marginTop="10dip"
            android:background="#00B2EE">
        </LinearLayout>
        <LinearLayout android:layout_width="fill_parent"
            android:id="@+id/l2" android:orientation="vertical"
            android:layout_height="wrap_content" android:layout_marginTop="10dip"
            android:background="#00EE76">

        </LinearLayout>
        <LinearLayout android:layout_width="fill_parent"
            android:id="@+id/l3" android:orientation="vertical"
            android:layout_height="wrap_content" android:layout_marginTop="10dip"
            android:background="#7171C6">
        </LinearLayout>
    </LinearLayout>
</ScrollView>

and put another xml which will be inflated by list.

this is your main activity class.

package com.list.add;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class NewlistActivity extends Activity {
    /** Called when the activity is first created. */
    LinearLayout l1,l2,l3;
    ScrollView scrollView;
    ViewGroup contentView;
    List<String> list = new ArrayList<String>();
    List<String> list1 = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        l1 = (LinearLayout) findViewById(R.id.l1);
        l2 = (LinearLayout) findViewById(R.id.l2);
        l3 = (LinearLayout) findViewById(R.id.l3);
        scrollView = (ScrollView) findViewById(R.id.scr);
        contentView = (ViewGroup) findViewById(R.id.r2);
        scrollView.setOnTouchListener(new ScrollPager(scrollView, contentView));
        scrollView.post(new Runnable() {
            public void run() {
                scrollView.scrollTo(0, contentView.getPaddingTop());
            }
        });
        list.add("Parth");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Parth");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Shah");
        list.add("Parth");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Parth");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Chirag");
        list.add("Shah");

        list1.add("Parth");
        list1.add("Parth");
        list1.add("Parth");
        list1.add("Parth");
        list1.add("Parth");
        list1.add("Parth");

        list2.add("Kalpesh");
        list2.add("Kalpesh");
        list2.add("Kalpesh");
        list2.add("Kalpesh");
        list2.add("Kalpesh");
        list2.add("Kalpesh");
        list2.add("Kalpesh");
        System.out.println(list);
        System.out.println(list1);
        System.out.println(list2);
        for (int i=0; i<list.size(); i++) 
        {
        LayoutInflater inflater = getLayoutInflater();
        View vi = inflater.inflate(R.layout.raw, null);
        TextView tv = (TextView) vi.findViewById(R.id.textView1);
        tv.setText(list.get(i));
        l1.addView(vi);
        }
        for (int i=0; i<list1.size(); i++) 
        {
        LayoutInflater inflater = getLayoutInflater();
        View vi = inflater.inflate(R.layout.raw, null);
        TextView tv = (TextView) vi.findViewById(R.id.textView1);
        tv.setText(list1.get(i));
        l2.addView(vi);
        }
        for (int i=0; i<list2.size(); i++) 
        {
        LayoutInflater inflater = getLayoutInflater();
        View vi = inflater.inflate(R.layout.raw, null);
        TextView tv = (TextView) vi.findViewById(R.id.textView1);
        tv.setText(list2.get(i));
        l3.addView(vi);
        }
    }

}

and make one scroller class like this:

public class ScrollPager implements OnTouchListener
public ScrollPager(ScrollView aScrollView, ViewGroup aContentView)
    {
        mScrollView = aScrollView;
        mContentView = aContentView;
        scroller = new Scroller(mScrollView.getContext(), new OvershootInterpolator());
        task = new Runnable()
        {
            public void run()
            {
                scroller.computeScrollOffset();
                mScrollView.scrollTo(0, scroller.getCurrY());

                if (!scroller.isFinished())
                {
                    mScrollView.post(this);
                }
            }
        };
    }
public boolean onTouch(View v, MotionEvent event)
    {
        // Stop scrolling calculation.
        scroller.forceFinished(true);
        // Stop scrolling animation.
        mScrollView.removeCallbacks(task);

        if (event.getAction() == MotionEvent.ACTION_UP)
        {

Android SDK 14 - Can't Create GTV device

8 votes

I'm a Google TV developer, and today, shortly after the android sdk 14 was released, I updated everything, from the android sdk to the eclipse ADT. Since then, I can't create a Google TV virtual device. I came to the point where I completely deleted everything and tried to do a fresh install. Here is what happens:

With a fresh download of the android sdk with only Android 3.1 and the Google TV add-on:

$ android list targets

Available Android targets:
----------
id: 1 or "android-12"
     Name: Android 3.1
     Type: Platform
     API level: 12
     Revision: 3
     Skins: WXGA (default)
     ABIs : armeabi
----------
id: 2 or "Google Inc.:Google TV Addon:12"
     Name: Google TV Addon
     Type: Add-On
     Vendor: Google Inc.
     Revision: 2
     Based on Android 3.1 (API level 12)
     Skins: WXGA, 1080p-overscan, 1080p, 720p (default), 720p-overscan
     ABIs : x86

$ android create avd -n GTV -t 2
Auto-selecting single ABI x86
Exception in thread "main" java.lang.IllegalArgumentException: ABI Type x86 is unknown for target Standard Android platform 3.1
    at com.android.sdklib.internal.avd.AvdManager.getImageRelativePath(AvdManager.java:885)
    at com.android.sdklib.internal.avd.AvdManager.setImagePathProperties(AvdManager.java:1637)
    at com.android.sdklib.internal.avd.AvdManager.createAvd(AvdManager.java:571)
    at com.android.sdkmanager.Main.createAvd(Main.java:1110)
    at com.android.sdkmanager.Main.doAction(Main.java:253)
    at com.android.sdkmanager.Main.run(Main.java:119)
    at com.android.sdkmanager.Main.main(Main.java:102)

Can someone give me a hint on what am I doing wrong?? Or is it a Google problem?

You might try this workaround:

inside of ~/.android/avd/your_avd_name.avd/ create a file 'config.ini'

config.ini should look like:

hw.lcd.density=213
hw.keyboard.charmap=Emulator
skin.name=720.p
skin.path=add-ons/addon-google_tv-google_inc_-12/skins/720p
hw.cpu.arch=x86
abi.type=x86
vm.heapSize=256
hw.ramSize=1024
disk.dataPartition.size=128
image.sysdir.2=platforms/android-12/images/
image.sysdir.1=add-ons/addon-google_tv-google_inc_-12/images/x86/

How do you disable the SoftKeyboard key preview window?

7 votes

When creating your own SoftKeyboard you are given a "key preview" by default.

enter image description here enter image description here

How do you disable this?

Edit:

You can customise the keyPreview layout by changing the <KeyboardView> attribute android:keyPreviewLayout. This is styled by default to look at keyboard_key_preview.xml:

Edit 2: Following my be a red herring:

The source code suggests supplying 0 or not applying the tag android:keyPreviewLayout will result in no key preview appearing:

    ...
    case com.android.internal.R.styleable.KeyboardView_keyPreviewLayout:
        previewLayout = a.getResourceId(attr, 0);
        break; 
    ...
    if (previewLayout != 0) {
        mPreviewText = (TextView) inflate.inflate(previewLayout, null);
        mPreviewTextSizeLarge = (int) mPreviewText.getTextSize();
        mPreviewPopup.setContentView(mPreviewText);
        mPreviewPopup.setBackgroundDrawable(null);
    } else {
        mShowPreview = false;
    }  

I've tried:

  • A styled KeyboardView with no keyPreviewLayout (Strangely though replacing this value changed the style of the preview.)
  • I made a keyPreviewLayout reference an id with a value of 0 (which causes a crash on inflation).

Stumped. :( Any help would be greatly appreciated!

There's a method:

public void setPreviewEnabled(boolean previewEnabled)

But I don't know which version of the API that starts at.

How to override (or hide) style attributes defined in the Android library project?

7 votes

I have a set of similar applications. I extracted common resources and code to the library project and applications just override what they need to. In my library there is the following style defined:

<style name="ListItemText">
    <item name="android:layout_toRightOf">@id/preview_image</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">@dimen/previewTextSize</item>
</style>

As you can see it contains android:layout_toRightOf attribute as this style would be applied to the text in the ListView row which should be displayed to the right of the image in that row.
However in one of my applications I'd like to display the text below the image. How the ListItemText style in that application should be defined to override android:layout_toRightOf attribute value and replace it with android:layout_below?

If I define it as:

<style name="ListItemText">
    <item name="android:layout_below">@id/preview_image</item>
</style>

it displays text to the right and below the image, effectively summing up attributes from both library and application styles XMLs.

p.s.: One possible solution of my issue would be to get rid of android:layout_toRightOf in the styles and move it to the layout xml instead. Then in the target application this layout can be redefined/overridden. But I'm looking for style-based solution, since it could provide more simple and straightforward way of attribute overriding.
(I can also use the inherited style with the parent attribute, but this would again require layout overriding in the application, which I try to avoid).

To disable android:layout_toRightOf, you can set it to @null. If your app defines the ListItemText style as follows, it should work as you want:

<style name="ListItemText">
    <item name="android:layout_toRightOf">@null</item>
    <item name="android:layout_below">@id/preview_image</item>
</style>

How to store a database inside an Arduino?

5 votes

I'm working on project where I use an Arduino with a Bluetooth module and my cellphone Samsung Galaxy S II with Android OS. The idea of the project is to send some commands from my cellphone to the Arduino via Bluetooth. I want to include a database into the Arduino so that when I send login information from my cellphone, the Arduino will check the database and if the login information matches, it retrieves some data from the database and sends it to my cellphone.

How can I store a database inside the Arduino? Should I purchase an external EEPROM or RAM? And how can I deal with that database (adding, deleting and manipulating data)?

My Ardunio is of type UNO, BTW.

Just for simple login you don't need a database, you probably need just a simple table.

Consider first of all that usually EEPROMs allow from 1000 to 100000 write cycles. It means, if you write a single cell more than 100000 you have an high probability that your cell die, you cannot write it anymore.

The question is, how many logins are allowed? It is a all matter of choosing the right data structure and understand what is the amount of required memory.

Knowing the computational power of Arduino: If logins are just 2 .. 50, a simple list would be sufficient. Insertion at the end is O(1), deletion is O(n), lookup is O(n). A linked list however will allow you to reduce the number of writes for deletion to a constant small value.

If logins are more, 50 .. 1000, a sorted array with binary search is enough. Insertion is O(n), deletion is O(n), lookup is O(n log n). However the number of writes is O(n) both for deletion and insertion, and since writing is slow and can burn cells, it depends on the number of updates you want to do.

If logins are 1000 or more a binary tree is good. Insertion is O(n log n), deletion is O(n log n), lookup is O(n log n). The good thing is that for insertion and deletion you just need a small, constant number of writes.

Also an hashtable is good, but they usually use more memory. Insertion is averaged O(1), deletion is averaged O(1), lookup is averaged O(1). Insertion and deletion requires only a small constant number of write operations, less than a binary tree. As I said, this data structure uses more memory, speed comes at a cost.

You don't need a real relational database, but probably if you need too much users, you need an external EEPROM.

Of course, you have to save this data in a flash memory, internal or external, or you'll lose the database when you reset or power down the machine.

We can also say that you don't need to store the username and password, you can just store an hash of the password and username. If the hashed username and password exists, then you can allow login. In this way you can use fixed size memory and less memory. You can use MD5, it is the Android phone that have to send the MD5 hash, that is, 16 bytes, so the Arduino must only check if that MD5 hash exists in the list of users there, for example. And this is easy and fast.