RSS

Creating a “Card” UI in Android

Image

Create

res/drawable/layer_card_background.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <item>
      <shape android:shape="rectangle">
         <solid android:color="#CABBBBBB"/>
         <corners android:radius="2dp" />
      </shape>
   </item>

   <item
      android:left="0dp"
      android:right="0dp"
      android:top="0dp"
      android:bottom="2dp">
      <shape android:shape="rectangle">
         <solid android:color="@android:color/white"/>
         <corners android:radius="2dp" />
      </shape>
   </item>
</layer-list>

res/layout/hello_card.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:background="#E0EEEE">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:gravity="center"
      android:layout_margin="15dp"
      android:padding="15dp"
      android:background="@drawable/layer_card_background"
      android:text="Hello Card!\nThis is an example of a card..."/>
</LinearLayout>
 
Leave a comment

Posted by on July 7, 2015 in Android Source Code

 

Find start and end date of week from input date in java

// set the date e.g. 12 June 2015
Calendar cal = Calendar.getInstance();
cal.set(2015, 6 – 1, 12);

// “calculate” the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK, first.getFirstDayOfWeek() – first.get(Calendar.DAY_OF_WEEK));

// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);

// print the result
SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd”);
System.out.println(df.format(first.getTime()) + ” -> ” +
df.format(last.getTime()));

OUTPUT:
2015-06-08 -> 2015-06-14

 
Leave a comment

Posted by on June 6, 2015 in Android Source Code

 

Find system time format in android

String clockType = android.provider.Settings.System.getString(context.getContentResolver(), android.provider.Settings.System.TIME_12_24);

It will return “12” or “24” as per device setting.

 
Leave a comment

Posted by on April 15, 2015 in Android Source Code

 

ListView inside ScrollView is not scrolling on Android

Sometimes we face issue of ListView height if we put ListView inside ScrollView. One more issue comes with this is we are unable to scroll the page. ListView inside ScrollView is a bad practice but there is one solution for it.
Create class as shown below and just use that as a Listview and start binding data to it.

package com.example.logactivity;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import android.widget.ListView;

public class NestedListView extends ListView implements OnTouchListener, OnScrollListener {

    private int listViewTouchAction;
    private static final int MAXIMUM_LIST_ITEMS_VIEWABLE = 99;

    public NestedListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        listViewTouchAction = -1;
        setOnScrollListener(this);
        setOnTouchListener(this);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        if (getAdapter() != null && getAdapter().getCount() > MAXIMUM_LIST_ITEMS_VIEWABLE) {
            if (listViewTouchAction == MotionEvent.ACTION_MOVE) {
                scrollBy(0, -1);
            }
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int newHeight = 0;
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode != MeasureSpec.EXACTLY) {
            ListAdapter listAdapter = getAdapter();
            if (listAdapter != null && !listAdapter.isEmpty()) {
                int listPosition = 0;
                for (listPosition = 0; listPosition < listAdapter.getCount()
                        && listPosition < MAXIMUM_LIST_ITEMS_VIEWABLE; listPosition++) {
                    View listItem = listAdapter.getView(listPosition, null, this);
                    //now it will not throw a NPE if listItem is a ViewGroup instance
                    if (listItem instanceof ViewGroup) {
                        listItem.setLayoutParams(new LayoutParams(
                                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                    }
                    listItem.measure(widthMeasureSpec, heightMeasureSpec);
                    newHeight += listItem.getMeasuredHeight();
                }
                newHeight += getDividerHeight() * listPosition;
            }
            if ((heightMode == MeasureSpec.AT_MOST) && (newHeight > heightSize)) {
                if (newHeight > heightSize) {
                    newHeight = heightSize;
                }
            }
        } else {
            newHeight = getMeasuredHeight();
        }
        setMeasuredDimension(getMeasuredWidth(), newHeight);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (getAdapter() != null && getAdapter().getCount() > MAXIMUM_LIST_ITEMS_VIEWABLE) {
            if (listViewTouchAction == MotionEvent.ACTION_MOVE) {
                scrollBy(0, 1);
            }
        }
        return false;
    }
}

Your ListView inside your layout should be:

<com.example.logactivity.NestedListView
                android:id="@+id/listView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="5dp"
                android:layout_marginTop="5dp"
                android:divider="@android:color/transparent"
                android:scrollbars="none" >
</com.example.logactivity.NestedListView>
 
Leave a comment

Posted by on March 24, 2015 in Android Source Code

 

How to handle “App Not Installed.” issue in Android

The workaround for above issue is:
After Uninstalling App You may found that App Name in Apps List of Downloaded Tab.
Step 1: Go to Settings
Step 2: Apps
Step 3: At bottom of list you found YourApp with “NOT INSTALLED” Tag
Step 4: Open
Step 5: Click on OptionMenu and Select “Uninstall for all Users”

It will work for sure.
Or else if you are getting message in Logcat like “Installation error: INSTALL_FAILED_DUPLICATE_PERMISSION” you can follow steps above.

 
Leave a comment

Posted by on February 19, 2015 in Android Source Code

 

BroadcastReceiver receives multiple identical messages for one event – Android

Receiving multiple broadcast is a device specific problem. Some phones just send one broadcast while other send 2 or 3. But there is a work around:

Assuming you get the disconnect message when the wifi is disconnected, I would guess the first one is the correct one and the other 2 are just echoes for some reason.

To know that the message has been called, you could have a static boolean that gets toggled between connect and disconnect and only call your sub-routines when you receive a connection and the boolean is true. Something like:

public class ConnectionChangeReceiver extends BroadcastReceiver {
    private static boolean firstConnect = true;

    @Override
    public void onReceive(Context context, Intent intent) {
        final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null) {
            if(firstConnect) { 
                // do subroutines here
                firstConnect = false;
            }
        }
        else {
            firstConnect= true;
        }
    }
}
 
Leave a comment

Posted by on February 7, 2015 in Android Source Code

 

Cannot perform this operation because the connection pool has been closed – Android

Problem
If you try another operation after closing the database, it will give you that exception.Because db.close(); releases a reference to the object, closing the object if the last reference was released. Solution
Keep a single SQLiteOpenHelper instance(Singleton) in a static context. Do lazy initialization, and synchronize that method. Such as

public class DatabaseHelper
{
    private static DatabaseHelper instance;

    public static synchronized DatabaseHelper getInstance(Context context)
    {
        if (instance == null)
            instance = new DatabaseHelper(context);

        return instance;
    }
//Other stuff... 
}

And you don’t have to close it? When the app shuts down, it’ll let go of the file reference, if its even holding on to it.
i.e. You should not close the DB since it will be used again in the next call. So Just remove

db.close();
 
Leave a comment

Posted by on January 13, 2015 in Android Source Code

 
 
Follow

Get every new post delivered to your Inbox.