Ad

Thursday, July 31, 2014

Download and parse XML in android

HttpClient client=new DefaultHttpClient();
            HttpGet request=new HttpGet(url);
            File xmlfile=new File(Environment.getExternalStorageDirectory()+"/Android/data/com.zacharia.app/", "fxml.xml");
            if(xmlfile.exists()){
                xmlfile.delete();
            }
            try{
                xmlfile=new File(Environment.getExternalStorageDirectory()+"/Android/data/com.zacharia.app/", "fxml.xml");
            HttpResponse response=client.execute(request);
            InputStream content = response.getEntity().getContent();           
            FileOutputStream output = new FileOutputStream(xmlfile);
           
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int len = 0;
            while ((len = content.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            content.close();
            output.close();


       
        try {
           
            InputStream is=    new FileInputStream(xmlfile);
            FamilyHandler handler=new FamilyHandler(context);
            SAXParser parser=SAXParserFactory.newInstance().newSAXParser();
            parser.parse(is, handler);
            return "success";
        } catch (SAXException e) {
            e.printStackTrace();
            // TODO: handle exception
            return "Unknown xml";
        }
        catch (Exception e) {
            e.printStackTrace();
            Log.i("zacharia", "Inside generate xml class exe : "+e);
            return "failed";
        }

Wednesday, July 9, 2014

Eclipse keys

Format code and xml file structure using "ctrl + shift + F" everywhere so that the code remains consistent and easy to understand. Also correct indentation of the implemented code using "ctrl + I".

Monday, June 23, 2014

How to build NDK projects automatically in ECLIPSE

When editing native JNI code in an Android project using the Android NDK you may configure Eclipse to automatically rebuild your project when editing native code, just as it does for java. The below steps shows how to perform the necessary configuration (note that this requires revision 4 or later of the NDK - previous revisions does not contain the necessary ndk-build binary):
Start by right clicking on your android project (named hello-neon in the below screenshots) with JNI resources, and select Properties. In the resulting dialog, choose the Builders entry in the list to the left and press the New...button:

A new dialog will open presenting a list of builder types. Select the Program type and press the OK button:

In the Main tab, fill in the following:
Name:
NDK Builder
Location:
/opt/android-ndk/ndk-build (or wherever your ndk-build binary is). You may use a variable as in ${system_property:user.home}/lib/android-ndk/ndk-build
Working Directory:
${workspace_loc:/hello-neon} (replace hello-neon with your project name. Press the Browse Workspace... button to select it graphically)
The result should look something like the below:

Now continue with the refresh tab. Make sure the two checkboxes Refresh resources upon completion. and Recursively include sub-folders are checked. Choose the Specific resources radio button and press the Specify Resources...button:

Since the ndk-build process will generate files in the lib folder, we want Eclipse to discover changes made there without having to refresh manually. So select the lib folder in the project (create one if necessary) and press theFinish button:

Now skip the Environment tab and go to the final Build Options tab. Make sure the Run the builder: During auto buildscheckbox is checked.

Since the NDK build only needs to happen when editing files in the jni folder, check that folder and press theFinish button.

Now finally press OK in the builder configuration dialog - the new NDK builder should now be up and running. Try editing any file in the jni folder and check that the Console view produces output from the build process:





Source: http://mobilepearls.com/labs/ndk-builder-in-eclipse/

Thursday, June 12, 2014

Get resource id from name in Android

public static int getResId(String variableName, Class<?> c) {

        try {
            Field idField = c.getDeclaredField(variableName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }



getResId(disobj.getName(), R.drawable.class);

Monday, June 9, 2014

Get accounts details in Android


Permission:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Code:
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();

for (Account ac : accounts) {
    String acname = ac.name;
    String actype = ac.type;
    // Take your time to look at all available accounts
    System.out.println("Accounts : " + acname + ", " + actype);
}
Check actype for whatsapp account
if(actype.equals("com.whatsapp")){
    String phoneNumber = ac.name;
}

Tuesday, April 29, 2014

To read the exception

 private String getStackTrace(Exception e) {
       
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
return s; 
    }

To enable all links clickable

Linkify.addLinks(message, Linkify.ALL)

Monday, January 6, 2014

ActionBar Tutorial

Source :here

Enabling Split Action Bars

Split action bar provides a separate bar at the bottom of the screen. This option will be useful when you want to display the action items at the bottom of the screen by leaving some space on the title bar.
To enable split action bar add uiOptions=”splitActionBarWhenNarrow” to all the <activity> tags or to the <application> tag directly in AndroidManifest.xml file. Also we need to add <meta-data> with the value android.support.UI_OPTIONS to support older version below API level 14.
<!-- Location found activity -->
<activity
    android:name="info.androidhive.actionbar.LocationFound"
    android:label="@string/activity_location_found"
    android:parentActivityName="info.androidhive.actionbar.MainActivity" >
    <!-- To support below API Level 14 -->
    <meta-data android:name="android.support.UI_OPTIONS"
           android:value="splitActionBarWhenNarrow" />
</activity>

Wednesday, January 1, 2014

CircleScrollListView

public class CircleScrollListView extends SurfaceView implements
    SurfaceHolder.Callback, OnGestureListener {
private GestureDetector mGestureDetector;
private Thread mThread;
private ArrayList<CircleDrawItem> datas = new ArrayList<CircleDrawItem>();
int[] playerDrawableResourceIds = new int[] { R.drawable.ronaldo,
        R.drawable.zindance, R.drawable.congvinh, R.drawable.huynhduc,
        R.drawable.gerrard, R.drawable.nagatomo, R.drawable.messi,
        R.drawable.minhphuong, R.drawable.neymar, R.drawable.ronaldo_beo,
        R.drawable.ronaldinho, R.drawable.xavi };
public int mCenterX;
public int mCenterY;
public int mRadius;
public double mStartAngleInRadian = Math.PI / 4;
private boolean isStop = false;

public CircleScrollListView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mGestureDetector = new GestureDetector(context, this);
    getHolder().addCallback(this);
    this.setFocusable(true);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    mGestureDetector.onTouchEvent(event);
    return true;
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
}

public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) height
                / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res,
        int resId, int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

private double calculateScrollAngle(float px1, float py1, float px2,
        float py2) {
    double radian1 = Math.atan2(py1, px1);
    double radian2 = Math.atan2(py2, px2);
    double diff = radian2 - radian1;
    return diff;
}

@Override
public void surfaceCreated(SurfaceHolder holder) {

    setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT));

    Global.density = getResources().getDisplayMetrics().density;
    Global.dw = getResources().getDisplayMetrics().widthPixels;
    Global.dh = getResources().getDisplayMetrics().heightPixels;
    Global.dp = Global.density / 1.5f;

    // For circle data
    mCenterX = (int) (Global.dw / 2.0f);
    mCenterY = (int) (Global.dh);
//      mCenterX = (int) (Global.dp * 200);
//      mCenterY = (int) (Global.dh / 2.0f);
    mRadius = (int) (300 * Global.dp);
    mStartAngleInRadian = Math.PI / 4;

    for (int i = 0; i < playerDrawableResourceIds.length; i++) {
        CircleDrawItem circleDrawItem = new CircleDrawItem();
        circleDrawItem.mIconBitmap = decodeSampledBitmapFromResource(
                getResources(), playerDrawableResourceIds[i], 50, 50);
        circleDrawItem.mAngle = mStartAngleInRadian +i * Math.PI / 10;
        datas.add(circleDrawItem);
    }

    mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!isStop) {
                draw();
            }
        }
    });

    mThread.start();
}

protected void draw() {
    Canvas canvas = getHolder().lockCanvas();
    if (canvas == null) {
        return;
    }
    canvas.save();
    canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setAntiAlias(true);

    for (int i = 0; i < datas.size(); i++) {
        canvas.save();
        CircleDrawItem item = datas.get(i);
        double x = mCenterX + Math.cos(item.mAngle) * mRadius;
        double y = mCenterY - Math.sin(item.mAngle) * mRadius;
        canvas.drawBitmap(item.mIconBitmap,
                (int) x - item.mIconBitmap.getWidth() / 2, (int) y
                        - item.mIconBitmap.getHeight() / 2, paint);
        canvas.restore();
    }
    canvas.restore();
    getHolder().unlockCanvasAndPost(canvas);
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    isStop = true;
}

@Override
public boolean onDown(MotionEvent e) {
    return false;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
        float velocityY) {
    return false;
}

@Override
public void onLongPress(MotionEvent e) {

}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
        float distanceY) {
    float tpx = e1.getY();
    float tpy = e2.getX();
    float disx = (int) distanceY;
    float disy = (int) distanceX;
    double scrollAngle = calculateScrollAngle(tpx, tpy, tpx + disx, tpy
            + disy);
    for (int i = 0; i < datas.size(); i++) {
        datas.get(i).mAngle += scrollAngle;
    }
    return true;
}

@Override
public void onShowPress(MotionEvent e) {
}

@Override
public boolean onSingleTapUp(MotionEvent e) {
    return false;
}
}
 
source: http://stackoverflow.com/questions/18822465/how-to-put-an-onclick-event-for-the-item-coming-at-the-center-of-the-canvas-in-a 

Note: not checked

Monday, November 18, 2013

Android Camera Intent

private static int TAKE_PICTURE = 1;    
private Uri imageUri;

public void takePhoto(View view) {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, TAKE_PICTURE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case TAKE_PICTURE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageUri;
            getContentResolver().notifyChange(selectedImage, null);
            ImageView imageView = (ImageView) findViewById(R.id.ImageView);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            try {
                 bitmap = android.provider.MediaStore.Images.Media
                 .getBitmap(cr, selectedImage);

                imageView.setImageBitmap(bitmap);
                Toast.makeText(this, selectedImage.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                        .show();
                Log.e("Camera", e.toString());
            }
        }
    }
}

Android Camera Intent

private static int TAKE_PICTURE = 1;    
private Uri imageUri;

public void takePhoto(View view) {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, TAKE_PICTURE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case TAKE_PICTURE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageUri;
            getContentResolver().notifyChange(selectedImage, null);
            ImageView imageView = (ImageView) findViewById(R.id.ImageView);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            try {
                 bitmap = android.provider.MediaStore.Images.Media
                 .getBitmap(cr, selectedImage);

                imageView.setImageBitmap(bitmap);
                Toast.makeText(this, selectedImage.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                        .show();
                Log.e("Camera", e.toString());
            }
        }
    }
}
 
source : http://stackoverflow.com/questions/2729267/android-camera-intent 

Sunday, November 10, 2013

Monitoring Foreground Activity in Android

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1); 
Log.d("topActivity", "CURRENT Activity ::"
            + taskInfo.get(0).topActivity.getClassName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
componentInfo.getPackageName();
 
You will need the following permission:

<uses-permission android:name="android.permission.GET_TASKS"/>
 
 
source : http://stackoverflow.com/questions/17629053/how-do-android-monitor-usage-applications-work 

Wednesday, October 30, 2013

How to Solve OutOfMemory Error (OOM) in Android ?

    How to Solve OutOfMemory Error (OOM) in Android ?


When you try to decode large files on your Android device (where you have only 16MB memory available) you wil surely get an OutOfMemory exception.

We have found that if you create a temp storage and pass it to BitmapFactory before decoding might help.

So, before using BitmapFactory.decodeFile() create a byte array of 16kb and pass it to temp storage in decoding process.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];

Bitmap bitmapImage = BitmapFactory.decodeFile(path,opt);

Also you might consider passing your own outputstream that streams out to server or other storage to minimize memory consumtion during the process.

PS, do not forget to bitmapImage.recycle() after usage.

Also consider using options.inSampleSize with values other than 1. From SDK: If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. (1 -> decodes full size; 2 -> decodes 1/4th size; 4 -> decode 1/16th size). Because you rarely need to show and have full size bitmap images on your phone. For manipulations smaller sizes are usually enough.


Source: http://eclipseandroid.blogspot.in/2012/02/how-to-solve-outofmemory-error-oom-in.html

Friday, September 27, 2013

Android code to check internet availability

ConnectivityManager cm = 
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

if(cm.getActiveNetworkInfo()!=null && cm.getActiveNetworkInfo().isConnected() &&    cm.getActiveNetworkInfo().isAvailable())
{
return true;
}
else
{
return false;
}

Monday, September 23, 2013

Hide Keyboard in Android

Method 1:

getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


Method 2:


InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Monday, July 29, 2013

How to install an Android Driver in the Window PC?

Step 1:
   Download the drivers from the website..
   For example: You can get asus drivers from here.

Step 2:
  Connect the device to the system.

Step 3:
   Open the device Manager.
      Win7:help
      WinXP:help

Step 4:
  Select the device(in the Other device).

Step 5:
   Select the button "Reinstall Driver".

   Then choose the driver file.  And install..

How to enable DEVELOPER OPTION in NEXUS 7 (Android 4.2.2)

Step 1:
 Open the settings.

Step 2:
  Tap the "About Tablet"/ "About Phone" in the system..

Step 3:
  Repeatedly tap on Build Number (5+ taps) until you got a message:"you are now a developer!"
  

Sunday, July 7, 2013

How to copy sqlite db from Asset Folder in Android ?

 1. Put the dbfile in the asset folder.

2. Create an instance to the dbFile.

File dbfile=new File(parentfolder,dbfile); (we can choose any folder as parent folder)

3. Check whether db is existing or not. if not copy it to the folder.

if (!dbfile.exists()) {
try {
copyDatabase(dbfile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}

private void copyDatabase(File dbFile) throws IOException {
InputStream is = context.getAssets().open(DB_NAME);
OutputStream os = new FileOutputStream(dbFile);
 
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
 
os.flush();
os.close();
is.close();
}