Thursday, May 31, 2012

Changing Tab with Horizontal Swipe Gesture

This tutorial describes the code I used to change activities with a swipe or fling gesture. This is an update to my scrolling tab article.

Lets say you want right and left "swipes" or "flings" to be able to flip through the tabs, like pages in a book.

In my project, I am using tabs that have separate activities to fill the content views.

As far as I can tell, the gesture can be detected two ways: place the gesture listener in each activity or from just this one to control them all. I placed code that handles swipes in the main activity page, the one that contains the set up for the tab host, and also sets the content for all the tabs.



Here is what you add to the main java file:

public class GestureScrollTabActivity extends TabActivity implements OnClickListener {

static TabHost mTabHost;
Intent intent;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    [...]

    // Gesture detection
    gestureDetector = new GestureDetector(new MyGestureDetector());
    gestureListener = new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
        }
    };
    mTabHost.setOnClickListener(GestureScrollTabActivity.this);
    mTabHost.setOnTouchListener(gestureListener);

} // end onCreate

[...]

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
            return false;
            // right to left swipe
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                int i = mTabHost.getCurrentTab();
                mTabHost.setCurrentTab(i+1);
                Toast.makeText(GestureScrollTabActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                int i = mTabHost.getCurrentTab();
                mTabHost.setCurrentTab(i-1);
                Toast.makeText(GestureScrollTabActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            // nothing
        }
    return false;
    }
}

@Override
public void onClick(View v) {
    Filter f = (Filter) v.getTag();
    // FilterFullscreenActivity.show(this, input, f);
    // Toast.makeText(GestureScrollTabActivity.this, "onClick", Toast.LENGTH_SHORT).show();
}

}

Resources:
(1) http://stackoverflow.com/questions/937313/android-basic-gesture-detection





Friday, January 20, 2012

Reading a TXT File from the Emulator's "SD Card"

The app that I'm developing has to read a TXT file from an SD card storage and display it in textview.

The process to get your file (any file) onto the emulator's pretend SD card is kind of tricky. First you have to create the SD card. I did this in eclipse by opening the AVD manager, selecting the device you want to create the SD card in and clicking edit.

In the edit screen, find the SD Card section and give your SD card a side. I gave mine 4 GB.

Then you have to move your file onto the SD card. In eclipse, this can be done by running your app and opening the DDMS view. Go to the File Explorer tab. Expand the "mnt" folder. Select the "sdcard" folder. Once selected, select the button in the upper right that has an image on a phone and an arrow. This should read "Push a file onto the device" when you hover over it. Click it. Find the file on your hard drive and push that baby onto the phone. Whew. Now its available to be read by our app.

Back to java. I pulled this code from someone's awesome answer on StackOverflow but forgot to bookmark it. Sorry!


                // Find the directory for the SD Card using the API
// *Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();


// Get the text file
File file = new File(sdcard, "filename.txt");


// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;


while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
// You'll need to add proper error handling here
}
DialogDetails.setText( text );

Friday, January 13, 2012

How to View Your Android App Database: SQLite Database Broswer

I've been using SQLite Database Browser to look through my android database and make changes. Linky link:
http://sourceforge.net/projects/sqlitebrowser/

You can pull your application's database off the emulator as a .sql file and open it up in this browser to see all that fancy sql stuff. 

To get your database off the emulator:

First, you have to have eclipse open and running, and run your application in your emulator of choice. 

Once the app is up and running, go back to eclipse and select Window > Open Perspective > DDMS

Under the Devices tab: Make sure the emulator that is running your app is highlighted/selected. Navigate to the "File Explorer" tab. (If it's not available, select Window > Show View > File Explorer.)

In the File Explorer tab: (1) open the "data" folder, (2) open a second "data" folder, (3) find and open the folder with "your application's name", (4) find and open the "databases" folder, (5) select the file with your application's name

In the upper right of the File Explorer frame, there is a button with an image of a floppy disk with an arrow. Click on the one that says "Pull a file from device" and save your database file somewhere memorable. It might automatically save it to your project's location on your hard drive. 

Now you can view it and play around with it in SQLite Database Browser :)

Keep in mind that you have to upload the new database onto the phone or emulator before the changes can be accessed by your app.


Tuesday, July 5, 2011

Custom Tabs that Scroll Horizontally

So I designed horizontally scrolling tabs that use separate activities to fill the tab content. TI rate this a 1/5 on the fun scale: there are so many different files you have to create and different selection states you have to consider. (Click here for my update to this tutorial: Changing Tab with Horizontal Swipe Gesture)

Faded edges indicate additional content
tabhostlayout.xml - Pretty basic stuff here, if you followed the tab widget tutorial on the android dev site.[1] The only thing to note here is that I surrounded the tab widget with Horizontal Scroll View element to achieve a horizontal scroll for the tabs. (Note: Sorry for the formatting here. I've tried to fix it only to make it much much worse. Blame blogger?)
<TabHost
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@android:id/tabhost"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
<LinearLayout
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent">
<HorizontalScrollView
               android:layout_width="fill_parent"
               android:layout_height="wrap_content">
                <TabWidget
                    android:id="@android:id/tabs"
                   android:layout_width="fill_parent"
                    android:layout_height="wrap_content" />
</HorizontalScrollView>
<FrameLayout
               android:id="@android:id/tabcontent"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:padding="5dp" />
</LinearLayout>
</TabHost>

TabHostActivity.java - This activity must extend TabActivity. You will need to define the following variables and also set the divider drawable BEFORE setting up tabs

TabHost mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
Intent intent; // Reusable Intent for each tab

For each tab you would like to add, use the following code in onCreate:
intent = new Intent().setClass(TabHostActivity.this, PageOne.class);
setupTab(new TextView(this), "Tab One", intent);

After onCreate, you need to add two new classes. "setupTab" creates the tabs and tab content. "createTabView" handles all tab events, like setting the views for selection events and stuff like that.
private void setupTab(final View view, final String tag, final Intent myIntent) {
View tabview = createTabView(mTabHost.getContext(), tag);
TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(myIntent);
mTabHost.addTab(setContent);
}
private static View createTabView(final Context context, final String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}

tabs_bg.xml - In the code above, "createTabView" calls a layout called tabs_bg. Create this file in the layout folder. This layout creates the layout for each tab element. I have only added a single textview but an image view could also be added (but will need some adjustments to the java code not shown above). This is where some of the layout personalization comes in. Text size and style, and padding elements. Note the background and text color call drawable files that handle the color changes for selection events.
<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/tabsLayout"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:background="@drawable/tab_bg_selector"
     android:padding="3dip"
     android:gravity="center"
     android:orientation="vertical">
<TextView
          android:layout_width="wrap_content"
          android:textColor="@drawable/tab_text_selector"
          android:gravity="center"
          android:textSize="12dip"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:id="@+id/tabsText"
          android:text="Title"
          android:padding="10px">
</TextView>
</LinearLayout>

tab_bg_selector.xml - both bg and text selector drawable files require the same four states to be defined: active, pressed, selected (using arrows), and inactive. I don't really know why the text and bg have to be separate files, but when I tried to combine them, it wasn't displaying properly. This code resembles custom button selection.
<selector
     xmlns:android="http://schemas.android.com/apk/res/android">
     <!--  Active tab -->
   
<item
          android:state_selected="true"
          android:state_focused="false"
          android:state_pressed="false">
          <shape
               android:shape="rectangle">
               <gradient
                    android:startColor="#A8A8A8"
                    android:centerColor="#7F7F7F"
                    android:endColor="#696969"
                    android:angle="-90" />
          </shape>
     </item>
   
<!--  Inactive tab -->
   
<item
          android:state_selected="false"
          android:state_focused="false"
          android:state_pressed="false">
          <shape
               android:shape="rectangle">
               <gradient
                    android:startColor="#5C5C5C"
                    android:centerColor="#424242"
                    android:endColor="#222222"
                    android:angle="-90" />
          </shape>
     </item>
<!--  Pressed tab -->
<item
          android:state_pressed="true"
          android:drawable="@android:color/transparent" />
<!--  Selected tab (using d-pad) -->
 <item
          android:state_selected="true"
          android:state_focused="true"
          android:state_pressed="false"
          android:drawable="@android:color/transparent" />
</selector>

tab_text_selector.xml
<selector
     xmlns:android="http://schemas.android.com/apk/res/android">
     <item
          android:state_selected="true"
          android:color="@android:color/white" />
<item
          android:state_focused="true"
          android:color="@android:color/white" />
<item
          android:state_pressed="true"
          android:color="@android:color/white" />
   
<item
          android:color="#f8f8f8" />
</selector>

References:
1) http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
2)http://joshclemm.com/blog/?p=136
For additional help, click here to download a zip containing all the files needed to create the above project.

Friday, July 1, 2011

Solution to "Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE"

Source: http://stackoverflow.com/questions/4709137/solution-android-install-failed-insufficient-storage-error


Getting this error: 

[2011-07-01 10:36:22 - MDatHand] Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
[2011-07-01 10:36:22 - MDatHand] Please check logcat output for more details.
[2011-07-01 10:36:22 - MDatHand] Launch canceled!


I used this solution:


RIGHT CLICK the root of your Android Project
SELECT "Run As" then go to "Run Configurations..." 
LOCATE the "Android Application" node in the tree at the left then SELECT your project
SELECT "Target" tab on the right side of the window look down for the "Additional Emulator Command Line Options" field (sometimes you'll need to make the window larger) 
PASTE "-partition-size 1024" there
CLICK "Apply" and then Run to use your emulator
Like so.



Thursday, June 23, 2011

“Debug certificate expired” Error in Eclipse

When there is no error in the code, but for some reason the project says there is an error and prevents you from running...

When you've torn your hair out trying to delete and re-import your project files to no avail...

When you've "cleaned" and "fixed project properties" so many times your index fingertip is bleeding...

Try looking at your project problems ( Window > Show View > Problems )

You might get something that looks like this:
Debug Certificate Expired...

If the above has happened to you, then I have a fix for you! You can probably solve this problem by deleting the debug certificate file. (Eclipse will then build a new one, and the error will go away.)

Win 7 OS: Go to ( Window > Preferences > Android > Build ) and find out where the debug.keystore file is located on your hard drive. Then using file explorer, find it and destroy it.

Thats it. Import your projects or whatever, do a clean and the error should disappear.

References:
http://stackoverflow.com/questions/2194808/debug-certificate-expired-error-in-eclipse-android-plugins

Wednesday, June 8, 2011

So you need to change the text size of simple_list_item_single_choice...

I feel you.

I tried for a month straight to call the checkedtextview in the android standard layout and resize the text. It never let me. I felt like a idiot. And now that I've figured it out, I know that it is more than just a feeling.

And so I'm posting it here, in the event that I actually forget how to do this later on. Because.. you know... I'm an idiot.

I went and copied the xml from the api demo and pasted it into a new .xml file(step 1). I accessed the text size and adjusted it thusly (step 2). Then I changed the java code to replace the simple_list_item_single_choice with my own custom row layout (step 3). Facepalmed for about two hours (step 4).

my_listitem_singlechoice.xml (i just chaged "textAppearance" attribute but I'm sure you can do other stuff to it too) :


<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:gravity="center_vertical"
    android:checkMark="?android:attr/listChoiceIndicatorSingle"
    android:paddingLeft="6dip"
    android:paddingRight="6dip"
/>



my_java_with_singlechoice.java (this should look somewhat familiar) :


        ListView lv = this.getListView();
MyListAdapter = new ArrayAdapter<String>(this, R.layout.my_listitem_singlechoice, myArrayList);
lv.setAdapter(MyListAdapter );
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);