Pages

Wednesday 18 December 2013

Android upload multiple files to server using http


Add following file to your project. there is one demo function which upload file like (audio/video song) to server. you can pass other params also. like song name , artist etc. set your api's url to "AudioVideoBaseURL" variable


public class Soap {
 
 

 public static String AudioVideoBaseURL = "http://abcd.com";

 

 public static String getSoapResponseForVideoAudio(String postFixOfUrl,
   List nameValuePairs,
   List filenameValuePairs) {
  String xmlString = null;
  HttpClient httpClient = new DefaultHttpClient();
  HttpContext localContext = new BasicHttpContext();
  HttpPost httpPost = new HttpPost(AudioVideoBaseURL + postFixOfUrl);

  try {
   MultipartEntity entity = new MultipartEntity();

   for (int index = 0; index < filenameValuePairs.size(); index++) {
    File myFile = new File(filenameValuePairs.get(index).getValue());
    FileBody fileBody = new FileBody(myFile);
    entity.addPart(filenameValuePairs.get(index).getName(),
      fileBody);
   }

   for (int index = 0; index < nameValuePairs.size(); index++) {

    entity.addPart(nameValuePairs.get(index).getName(),
      new StringBody(nameValuePairs.get(index).getValue(),
        Charset.forName("UTF-8")));

   }

   httpPost.setEntity(entity);

   HttpResponse response = httpClient.execute(httpPost, localContext);
   HttpEntity r_entity = response.getEntity();
   xmlString = EntityUtils.toString(r_entity);

  } catch (IOException e) {
   e.printStackTrace();
  }
  return xmlString.toString();
 }


 public static String apiUploadSong(int userId, int songId,
   String songTitle, String songArtist, String isVideo, String fileData)
   throws ClientProtocolException, IOException {

  ArrayList alNameValuePairsFile = new ArrayList();
  NameValuePair nameValuePairsFile = new BasicNameValuePair("fileData",
    fileData);
  alNameValuePairsFile.add(nameValuePairsFile);

  ArrayList alNameValuePairs = new ArrayList();

  NameValuePair nameValuePairs = new BasicNameValuePair("userId", ""
    + userId);
  alNameValuePairs.add(nameValuePairs);
  nameValuePairs = new BasicNameValuePair("songId", ""+songId);
  alNameValuePairs.add(nameValuePairs);
  nameValuePairs = new BasicNameValuePair("songTitle", songTitle);
  alNameValuePairs.add(nameValuePairs);
  nameValuePairs = new BasicNameValuePair("songArtist", songArtist);
  alNameValuePairs.add(nameValuePairs);
  nameValuePairs = new BasicNameValuePair("isVideo", isVideo);
  alNameValuePairs.add(nameValuePairs);

  String result = Soap.getSoapResponseForVideoAudio(
    "?action=save_video_audio", alNameValuePairs,
    alNameValuePairsFile);
  Log.e("SOAP", "save_video_audio : " + result);

  return result;
 }
}


now just add following jar file to your libs folder
apache-mime4j-0.6.jar
httpmime-4.0.1.jar

Monday 16 September 2013

Android notification using notification builder

To work following code for android version before 3.0, You need to add android support library.
Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);

Sunday 15 September 2013

android string to date or date to string format


public class DateFormatClass {
    public static void main(String[] args) {

        String mytime="Jan 17, 2012";
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "MMM dd, yyyy");
        Date myDate = null;
        try {
            myDate = dateFormat.parse(mytime);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
        String finalDate = timeFormat.format(myDate);

        System.out.println(finalDate);
    }
}

Thursday 22 August 2013

Android how to check earphone plugged in or not

Pls check following code to check earphone status

need to register broadcast receiver in activity


private BroadcastReceiver earPhoneStateReceiver = new BroadcastReceiver() {

  @Override
  public void onReceive(Context context, Intent intent) {
   if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {

    int state = intent.getIntExtra("state", -1);
    switch (state) {
    case 0:
     
     Log.d(TAG, "Headset is unplugged");
     break;
    case 1:
     
     Log.d(TAG, "Headset is plugged");
     break;
    default:
     
     Log.d(TAG, "I have no idea what the headset state is");
    }
   }
  }
 };


in On create of activity need to register above receiver
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.detail);


  // register receiver for ear phone
  IntentFilter receiverFilter = new IntentFilter(
    Intent.ACTION_HEADSET_PLUG);

  registerReceiver(earPhoneStateReceiver, receiverFilter);
  // end register receiver for ear phone

}

Tuesday 13 August 2013

Android how to mix 2 wav audio?

Basic steps to mix 2 wav files.
  • just take byte[] (or amplitude array is also good) and from both file..
  • calculate average of every byte and prepare new array
  • make wave header and set new file's header
  • then write byte array to new file
  • then try to play using MediaPlayer (MediaPlayer will give great result when play sound then audio track)
Click here to download demo.
Following are condition in above demo.You can change them as per requirement.

Low Song format must have
we have to upload song in WAV format with following values.

song formats in demo are 
1.  Format 1 param : 
     Freq : 11.025 kHz,
     bit per sample :  8 Bit,
     channel mode :  Mono

2.  Format 2 param : 
     Freq : 44100 kHz,
     bit per sample :  8 Bit,
     channel mode :  Mono


How to convert mp3 to wav with different options :
These can be done using Free software. 
Software Download url : http://www.koyotesoft.com/audio-software/free-mp3-wma-converter.html

Friday 19 July 2013

Android - Convert String to valid URL

Just copy-paste below code and call the function with your string url as param.
private URL ConvertToUrl(String urlStr) {
 try {
  URL url = new URL(urlStr);
  URI uri = new URI(url.getProtocol(), url.getUserInfo(),
    url.getHost(), url.getPort(), url.getPath(),
    url.getQuery(), url.getRef());
  url = uri.toURL();
  return url;
 } catch (Exception e) {
  e.printStackTrace();
 }
 return null;
}

Monday 8 July 2013

Android unregister receiver error when choosing image using intent

To solve error like following

Activity com.android.internal.app.ChooserActivity has leaked IntentReceiver com.android.internal.app.ResolverActivity$1@417ffc78 that was originally registered here. Are you missing a call to unregisterReceiver()?
01-07 02:42:48.242: E/ActivityThread(11280): android.app.IntentReceiverLeaked: Activity com.android.internal.app.ChooserActivity has leaked IntentReceiver com.android.internal.app.ResolverActivity$1@417ffc78 that was originally registered here. Are you missing a call to unregisterReceiver()?
01-07 02:42:48.242: E/ActivityThread(11280):    at android.app.LoadedApk$ReceiverDispatcher.(LoadedApk.java:763)
To solve above error make sure your activity is not "singletask". please check your manifist. if activity is "singletask" then remove it and try.

Friday 10 May 2013

Android Cover flow working with 2.2+

Following is complete code of cover flow.
As i show this cover flow is not working with phone like s3, nexus 4 etc.
Following  is example of cover flow example working with all phones

Download cover flow from Following url
https://code.google.com/p/android-coverflow/

or Download zip

just replace coverflow.java with following

CoverFlow


import android.content.Context;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;
import android.widget.ImageView;

public class CoverFlow extends Gallery {

 /**
  * Graphics Camera used for transforming the matrix of ImageViews
  */
 private Camera mCamera = new Camera();

 /**
  * The maximum angle the Child ImageView will be rotated by
  */
 private int mMaxRotationAngle = 60;

 /**
  * The maximum zoom on the centre Child
  */
 private int mMaxZoom = -120;

 /**
  * The Centre of the Coverflow
  */
 private int mCoveflowCenter;

 public CoverFlow(Context context) {
  super(context);
  this.setStaticTransformationsEnabled(true);
 }

 public CoverFlow(Context context, AttributeSet attrs) {
  super(context, attrs);
  this.setStaticTransformationsEnabled(true);
 }

 public CoverFlow(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  this.setStaticTransformationsEnabled(true);
 }

 /**
  * Get the max rotational angle of the image
  * 
  * @return the mMaxRotationAngle
  */
 public int getMaxRotationAngle() {
  return mMaxRotationAngle;
 }

 /**
  * Set the max rotational angle of each image
  * 
  * @param maxRotationAngle
  *            the mMaxRotationAngle to set
  */
 public void setMaxRotationAngle(int maxRotationAngle) {
  mMaxRotationAngle = maxRotationAngle;
 }

 /**
  * Get the Max zoom of the centre image
  * 
  * @return the mMaxZoom
  */
 public int getMaxZoom() {
  return mMaxZoom;
 }

 /**
  * Set the max zoom of the centre image
  * 
  * @param maxZoom
  *            the mMaxZoom to set
  */
 public void setMaxZoom(int maxZoom) {
  mMaxZoom = maxZoom;
 }

 /**
  * Get the Centre of the Coverflow
  * 
  * @return The centre of this Coverflow.
  */
 private int getCenterOfCoverflow() {
  return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
    + getPaddingLeft();
 }

 /**
  * Get the Centre of the View
  * 
  * @return The centre of the given view.
  */
 private static int getCenterOfView(View view) {

   Log.i("visual postion",
   "left : "+view.getLeft()+" , right : "+view.getRight()+ " , width : "+(view.getLeft()+view.getRight()+view.getWidth()));
  return view.getLeft() + view.getWidth() / 2;
 }
 
 private int offsetChildrenLeftAndRight() {
     int offset = 0;
     for (int i = getChildCount() - 1; i >= 0; i--) {

         getChildAt(i).offsetLeftAndRight(offset);

         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
             getChildAt(i).invalidate();
     }
     return offset;
 }

 /**
  * {@inheritDoc}
  * 
  * @see #setStaticTransformationsEnabled(boolean)
  */
 @Override
 protected boolean getChildStaticTransformation(View child, Transformation t) {

  mCoveflowCenter = getCenterOfCoverflow();
  final int childCenter = getCenterOfView(child) + offsetChildrenLeftAndRight();
  final int childWidth = child.getWidth();

  int rotationAngle = 0;

  t.clear();
  t.setTransformationType(Transformation.TYPE_MATRIX);
//  FacyLog.writeToLog("mCoveflowCenter : "+mCoveflowCenter+" , childCenter:"+childCenter+" , difference : "+(mCoveflowCenter - childCenter)+" , ");
  if ((mCoveflowCenter - childCenter) < 45
    && (mCoveflowCenter - childCenter) > -45) {
   transformImageBitmap((ImageView) child, t, 0);
   Log.i("rotation angel", "rotation angel : 0");
//   FacyLog.writeToLog("rotation angel : 0");
  } else {
   rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
   if (Math.abs(rotationAngle) > mMaxRotationAngle) {
    rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle
      : mMaxRotationAngle;
   }
   transformImageBitmap((ImageView) child, t, rotationAngle);
   Log.i("rotation angel", "rotation angel : "
     + rotationAngle);
//   FacyLog.writeToLog("rotation angel : "+rotationAngle);
  }
//  FacyLog.writeToLog("\n");

  return true;
 }

 /**
  * This is called during layout when the size of this view has changed. If
  * you were just added to the view hierarchy, you're called with the old
  * values of 0.
  * 
  * @param w
  *            Current width of this view.
  * @param h
  *            Current height of this view.
  * @param oldw
  *            Old width of this view.
  * @param oldh
  *            Old height of this view.
  */
 @Override
 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  mCoveflowCenter = getCenterOfCoverflow();
  super.onSizeChanged(w, h, oldw, oldh);
 }

 /**
  * Transform the Image Bitmap by the Angle passed
  * 
  * @param imageView
  *            ImageView the ImageView whose bitmap we want to rotate
  * @param t
  *            transformation
  * @param rotationAngle
  *            the Angle by which to rotate the Bitmap
  */
 private void transformImageBitmap(ImageView child, Transformation t,
   int rotationAngle) {
  mCamera.save();
  final Matrix imageMatrix = t.getMatrix();
  ;
  final int imageHeight = child.getLayoutParams().height;
  ;
  final int imageWidth = child.getLayoutParams().width;
  final int rotation = Math.abs(rotationAngle);

  mCamera.translate(0.0f, 0.0f, 100.0f);

  // As the angle of the view gets less, zoom in
  if (rotation < mMaxRotationAngle) {
   float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
   mCamera.translate(0.0f, 0.0f, zoomAmount);
  }

  mCamera.rotateY(rotationAngle);
  mCamera.getMatrix(imageMatrix);
  imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
  imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
  mCamera.restore();
 }
}

Friday 12 April 2013

Android - Hide android keyboard

Just put the below code and call the function whenever u want to hide the keyboard!
private void hideKeyboard(View currentFocusView) {
 if (currentFocusView instanceof EditText) {
  InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(currentFocusView.getWindowToken(), 0);
 }
}

Tuesday 9 April 2013

Android remember fragment to back stack

Use following code to set current fragment to backstack and load new fragment

PdfFragment newFragment = new PdfFragment();

  Bundle args = new Bundle();
  args.putString("name", sub_category.name);
  args.putString("catId", String.valueOf(sub_category.id));
  args.putString("pdf_from", "sub_category");

  newFragment.setArguments(args);

  FragmentTransaction transaction = getSupportFragmentManager()
    .beginTransaction();

  // Replace whatever is in the fragment_container view with this
  // fragment,
  // and add the transaction to the back stack so the user can
  // navigate back
  transaction.setCustomAnimations(R.anim.left_to_right,
    R.anim.right_to_left);
  transaction.replace(R.id.fragment_container, newFragment);

// use following code to set current fragment to back stack and load new fragment
  transaction.addToBackStack(null);

  // Commit the transaction
  transaction.commit();

Monday 8 April 2013

Android How to handle back pressed event?

Following code redirect user to home screen rather then finish activity


@Override
public void onBackPressed() {
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

Thursday 4 April 2013

Android how to open pdf in webview

You Need to use google doc viewer service.

please check following code

WebView mWebView = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true);  
String url = "http://docs.google.com/viewer?embedded=true&url="+"http://sitename.com/abc.pdf";
mWebview.loadUrl(url); 

Friday 29 March 2013

Android switch fragment with animation


Following is simple code to animate fragment when switching between fragment

CategoryFragment newFragment = new CategoryFragment();

   Bundle args = new Bundle();
   newFragment.setArguments(args);

   FragmentTransaction transaction = getSupportFragmentManager()
     .beginTransaction();

   // Replace whatever is in the fragment_container view with this
   // fragment,
   // and add the transaction to the back stack so the user can
   // navigate back
   transaction.setCustomAnimations(R.anim.left_to_right,
     R.anim.right_to_left);
   transaction.replace(R.id.fragment_container, newFragment);
   transaction.addToBackStack(null);

   // Commit the transaction
   transaction.commit();

Put Following xml to res/anim folder
left_to_right.xml



    




left_to_right.xml



    



Android load fragment from backstack

For example my current fragment is catetegory fragment . It was loaded from option Fragment. now click on button i want to load option Fragment from backstack then following code may help.

btnBack.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    getActivity().getSupportFragmentManager().popBackStack();
    getActivity().getSupportFragmentManager().beginTransaction()
      .remove(CategoryFragment.this).commit();
   }
  });

Monday 18 March 2013

Android - Set marker to exact position using custom Overlay in MapView

There is a method in the ItemizedOverlay class called: boundCenterBottom(Drawable), which does the setBounds part. There's also a boundCenter(Drawable) method.

Just replace this code in your custom Itemized Overlay constructor :

public CustomItemizedOverlay(Drawable defaultMarker, MapView mapView) {
       super(boundCenterBottom(defaultMarker), mapView);
}

Thursday 14 March 2013

Android portrait mode video recording orientation proble,

In Android In portrait mode you need to add following to your camera object and recording object before calling prepare function.

check following function.
we assume you create surface object and camera and other required object


protected void startRecording() throws IOException {
  
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
   Log.i(TAG, ">=GINGERBREAD");
   openFrontCamera();
  }

  if (mCamera == null) {
   Log.i(TAG, "CAMERA NULL");
   mCamera = Camera.open();
  }
  
  int camera_oriantation = 90; // for portrait mode
  
  mCamera.setDisplayOrientation(camera_oriantation);

  Date date = new Date();
  filename = "rec" + date.toString().replace(" ", "_").replace(":", "_")
    + ".mp4";

  File dir = new File(General.MediaPath);
  if (!dir.exists()) {
   dir.mkdirs();
  }
  // create empty file it must use
  File file = new File(General.MediaPath, filename);

  mrec = new MediaRecorder();

  mCamera.lock();
  mCamera.unlock();

  // Please maintain sequence of following code.

  // If you change sequence it will not work.
  mrec.setCamera(mCamera);
  mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
  mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
  mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
  mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
  mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

  mrec.setOrientationHint(camera_oriantation);
  
  mrec.setPreviewDisplay(surfaceHolder.getSurface());
  mrec.setOutputFile(General.MediaPath + File.separator + filename);
  mrec.prepare();
  mrec.start();

 }

Android Generate the authentic hash key for Facebook

This is the Code of Generate the Actual Hash key of your Computer.
No Need to  use command prompt ,keytool , keystore.
Just paste this bellow code in your activity and Look at inside you Log.
There is one Log of  "Generated Hash Key".
Just Get it and use it simple...

Here is a quick code snippet :

private void generateHashKey() {
 try {
   PackageInfo info = getPackageManager().getPackageInfo(
     "taranor.taxicustomer.app", PackageManager.GET_SIGNATURES);
   for (Signature signature : info.signatures) {
    MessageDigest md = MessageDigest.getInstance("SHA");
    md.update(signature.toByteArray());
    Log.d("Generated Hash Key", Base64.encodeBytes(md.digest()));
   }
  } catch (NameNotFoundException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
 }
Only one thing you need is the Base64.java to get this code is working.
I used the Following Link to get Base64.java.

Saturday 9 March 2013

Android - Button's different state effects using single image



Create an XML file for button selector :
buton_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/my_button" android:state_pressed="false"/>

    <item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>

</selector>
Here my_button is an image in drawable folder and button_pressed is an XML file in drawable.
button_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/my_button" />
    </item>
    <item>
        <color android:color="#60000000" />
        <!--
        <shape>
            <gradient
                android:endColor="#ff0000"
                android:startColor="#00ff00" />            
            <corners android:radius="3dp" />
        </shape>
        -->
    </item>
</layer-list>
Now set button's background as buton_selector.
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"        
        android:background="@drawable/button_selector"        
        android:text="my botton" />

Note : We can also use shape,gradient,stroke (See commented part of button_pressed.xml) for rounded button backgrounds!

Thursday 7 March 2013

Android - How to generate Google Map API Key

RUN COMMAND PROMPT AS ADMINISTRATOR.

1.Locate your debug.keystore file
"C:\Users\QTM-19\.android\debug.keystore"

2.Locate keytool.exe in Java\bin folder
"C:\Program Files\Java\jre7\bin"

3.Generate MD5 key using this command in cmd :
C:\Program Files\Java\jre7\bin>keytool -v -list -alias androiddebugkey -keystore C:\Users\QTM-19\.android\debug.keystore -storepass android -keypass android
(remove "-v" if Java version < 7)

Certificate fingerprints:
          MD5:  AB:42:12:2A:80:FF:BE:DD:C3:57:38:80:87:CC:39:B3
          SHA1: 31:4D:1A:58:FF:01:14:79:75:E8:D0:1B:1D:1C:61:CF:7E:71:0D:62
          SHA256: AF:87:67:02:5D:EB:3D:03:80:9C:26:5E:C2:E7:96:67:19:17:66:26:A5:
89:7B:AA:8C:D2:E7:F0:27:42:E0:23
          Signature algorithm name: SHA256withRSA
        Version: 3



4.Get a key for the Google Maps Android API v1:
https://developers.google.com/maps/documentation/android/v1/maps-api-signup

5.To register for a Google Maps Android API v1 Key, follow these steps:
-->If you don't have a Google account, use the link on the page to set one up.
-->Paste the MD5 key
-->Click "Generate API Key"


Generated key:0kVayCORItzMtF85IkONrJY0ECuVYdTcAuUE4HQ


6.Add API KEY to your application's MapView objects:
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="EXAMPLE_MAPS_API_KEY_STRING" />

 7.Add <uses-library android:name="com.google.android.maps library" :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.package.name">
...
<application android:name="MyApplication" >
<uses-library android:name="com.google.android.maps" />
...
</application>

8.Sign your application with the certificate that corresponds to the Maps API Key referenced in your MapView elements.

==>FOR MORE INFO VISIT:
https://developers.google.com/maps/documentation/android/v1/mapkey

==>How to regenerate debug.keystore? Visit Here :
http://stackoverflow.com/questions/2194808/debug-certificate-expired-error-in-eclipse-android-plugins/2196397#2196397

Monday 25 February 2013

EditView in ListView row: focus lost when soft keyboard shows


You need to change in your AndroidManifest.xml
Add android:windowSoftInputMode="adjustPan" in the activity holding the listview. This will solve your problem.
    <activity android:name=".MyActivity"
              android:label="@string/app_name"
              android:windowSoftInputMode="adjustPan">

Thursday 7 February 2013

Android how to create custom spinner

following is demo with spinner with image. and also different color for selected item .

Main spinner layout



    



spinner item layout



    

    


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

  String[] str = new String[5];
  str[0] = "first";
  str[1] = "second";
  str[2] = "third";
  str[3] = "forth";
  str[4] = "fifth";
  Spinner spinner = (Spinner) findViewById(R.id.ddSample);

  // Apply the adapter to the spinner
  spinner.setAdapter(new BGSpinnerAdapter(this, str,getResources().getColor(R.color.unknown),getResources().getColor(R.color.red)));
 }

 
}

Spinner Adapter

public class BGSpinnerAdapter implements SpinnerAdapter {
 private String[] arrItem;
 private int count;
 private Context mContext;
 private int selectedColor;
 private int itemColor;

 public BGSpinnerAdapter(Context mContext, String[] arrItem) {
  this.mContext = mContext;
  this.arrItem = new String[arrItem.length];
  this.arrItem = arrItem;
  count = arrItem.length;
  this.selectedColor = mContext.getResources().getColor(
    android.R.color.black);
  this.itemColor = mContext.getResources().getColor(R.color.red);
 }

 public BGSpinnerAdapter(Context mContext, String[] arrItem,
   int selectedColor, int itemColor) {
  this.mContext = mContext;
  this.arrItem = new String[arrItem.length];
  this.arrItem = arrItem;
  count = arrItem.length;
  this.selectedColor = selectedColor;
  this.itemColor = itemColor;
 }

 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  return count;
 }

 @Override
 public Object getItem(int position) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public long getItemId(int position) {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public int getItemViewType(int position) {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  if (position < getCount()) {
   LayoutInflater inflater = (LayoutInflater) mContext
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View rowView = inflater.inflate(R.layout.bg_spinner_item, parent,
     false);
   TextView txtSpinnerItem = (TextView) rowView
     .findViewById(R.id.txtSpinnerItem);
   txtSpinnerItem.setTextColor(selectedColor);
   txtSpinnerItem.setText(arrItem[position]);
   return rowView;
  }
  return null;
 }

 @Override
 public int getViewTypeCount() {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public boolean hasStableIds() {
  // TODO Auto-generated method stub
  return false;
 }

 @Override
 public boolean isEmpty() {
  // TODO Auto-generated method stub
  return false;
 }

 @Override
 public void registerDataSetObserver(DataSetObserver observer) {
  // TODO Auto-generated method stub

 }

 @Override
 public void unregisterDataSetObserver(DataSetObserver observer) {
  // TODO Auto-generated method stub

 }

 @Override
 public View getDropDownView(int position, View convertView, ViewGroup parent) {
  if (position < getCount()) {
   LayoutInflater inflater = (LayoutInflater) mContext
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View rowView = inflater.inflate(R.layout.bg_spinner_item, parent,
     false);
   TextView txtSpinnerItem = (TextView) rowView
     .findViewById(R.id.txtSpinnerItem);
   txtSpinnerItem.setTextColor(itemColor);
   txtSpinnerItem.setText(arrItem[position]);
   return rowView;
  }

  return null;
 }

}

android margin not working in frame layout in android 2.2

Use android:layout_gravity="top" with child views of frame layout. 

Tuesday 5 February 2013

android sliding menu like facebook

Please check following demo project .

https://github.com/gitgrimbo/android-sliding-menu-demo

Wednesday 30 January 2013

Android - Make ImageView's transparent area not clickable


ImageView :
ImageView imgView= (ImageView) findViewById(R.id.color_blue);
imgView.setDrawingCacheEnabled(true);
imgView.setOnTouchListener(changeColorListener); 


OnTouchListener:

private final OnTouchListener changeColorListener = new OnTouchListener() {

  @Override
  public boolean onTouch(final View v, MotionEvent event) {

   Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
   int color = 0;
   try {
    color = bmp.getPixel((int) event.getX(), (int) event.getY());
   } catch (Exception e) {
    // e.printStackTrace();
   }
   if (color == Color.TRANSPARENT)
    return false;
   else {

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
     //do something here
     break;
    case MotionEvent.ACTION_OUTSIDE:
     break;
    case MotionEvent.ACTION_CANCEL:
     break;
    case MotionEvent.ACTION_MOVE:
     break;
    case MotionEvent.ACTION_SCROLL:
     break;
    case MotionEvent.ACTION_UP:
     //do something here
     break;
    default:
     break;
    }
    return true;

   }
  }
 };

Friday 25 January 2013

Android rate your app functionality

use below code to launch rating page on google play.


mContext.startActivity(new Intent(
                                        Intent.ACTION_VIEW, Uri
                                                .parse("market://details?id="
                                                        + APP_PACKAGE_NAME)));

Thursday 24 January 2013

android twitter login implementation

below is code to login twitter.

requirement:
lib need to use : using twitter 4j 
make twitter app at dev consolve of twitter

 private void parseUrl(String url) {
  try {
   if (url == null)
    return;
   if (url.startsWith(General.TWITTER_CALLBACK_URL)) {
    url += "&";

    String oauth_verifier = com.qtm.sign2learn.utils.Util.extractPattern(url,
      "oauth_verifier=(.*?)&");

    AccessToken accessToken = twitter.getOAuthAccessToken(
      requestToken, oauth_verifier);

    twitter.setOAuthAccessToken(accessToken);

    User user = twitter.verifyCredentials();

    String name = user.getName();

    String miniImage = user.getMiniProfileImageURL();
    String bigImage = user.getBiggerProfileImageURL();

    String fbUid = String.valueOf(user.getId());

    Editor edit = prefs.edit();
    edit.putString(General.pref_KEY_OAUTH_TOKEN,
      accessToken.getToken());
    edit.putString(General.pref_KEY_OAUTH_SECRET,
      accessToken.getTokenSecret());
    edit.putString(General.pref_TWITTER_ACCESS_TOKEN,
      accessToken.getToken());
//    edit.putString(General.pref_fb_uid, fbUid);
//    edit.putInt(General.pref_acctype, 2);
    prefs.getBoolean(General.pref_KEY_TWITTER_LOGIN, true);
    edit.commit();
    
    if (progressDialog != null && progressDialog.isShowing()) {
     progressDialog.dismiss();
    }
    loginDialog.dismiss();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 private class TwitterWebViewClient extends WebViewClient {
  @Override
  public void onPageStarted(WebView view, String url, Bitmap favicon) {
   super.onPageStarted(view, url, favicon);
   parseUrl(url);

   progressDialog.show();

  }

  @Override
  public void onPageFinished(WebView view, String url) {
   super.onPageFinished(view, url);
   progressDialog.dismiss();
  }
 }

 public void loginToTwitter(View v) {

  TwitterFactory factory = new TwitterFactory();

  twitter = factory.getInstance();
  twitter.setOAuthConsumer(General.TWITTER_CONSUMER_KEY,
    General.TWITTER_CONSUMER_SECRET);
  try {
   requestToken = twitter
     .getOAuthRequestToken(General.TWITTER_CALLBACK_URL);

   loginDialog = new Dialog(this,
     android.R.style.Theme_Translucent_NoTitleBar);

   loginDialog.setContentView(R.layout.webview_popup);

   Button btnClose = (Button) loginDialog.findViewById(R.id.btnClose);

   btnClose.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
     // TODO Auto-generated method stub
     loginDialog.dismiss();
    }
   });

   WebView webview = (WebView) loginDialog
     .findViewById(R.id.webViewVKLogin);
   webview.getSettings().setJavaScriptEnabled(true);
   webview.clearCache(true);

   webview.setWebViewClient(new TwitterWebViewClient());

   // otherwise CookieManager will fall with
   // java.lang.IllegalStateException:
   // CookieSyncManager::createInstance()
   // needs to be called before CookieSyncManager::getInstance()
   CookieSyncManager.createInstance(this);

   CookieManager cookieManager = CookieManager.getInstance();
   cookieManager.removeAllCookie();

   webview.loadUrl(requestToken.getAuthenticationURL());

   loginDialog.show();

   // this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
   // .parse(requestToken.getAuthenticationURL())));
  } catch (TwitterException e) {
   e.printStackTrace();
  }

 }

In general.java put below variables
 // Twitter oauth urls and details
 public static final String TWITTER_CALLBACK_URL = "url here";
 public static final String TWITTER_CONSUMER_KEY = "key here";
 public static final String TWITTER_CONSUMER_SECRET = "secreat here";

 public static final String URL_TWITTER_AUTH = "auth_url";
 public static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
 public static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
 
 public static final String PREFERENCE_NAME = "twitter_oauth";
 public static final String pref_KEY_OAUTH_TOKEN = "sing2learn_oauth_token";
 public static final String pref_KEY_OAUTH_SECRET = "sing2learn_oauth_token_secret";
 public static final String pref_KEY_TWITTER_LOGIN = "sing2learn_isTwitterLogedIn";
 public static final String pref_TWITTER_ACCESS_TOKEN = "sing2learn_twitter_token";
 



android facebook login implementation

use below code for facebook login.

----- FOR NEW SDK-----

https://developers.facebook.com/docs/android/getting-started/facebook-sdk-for-android/

-----FOR OLD SDK------
you need to use facebook sdk. you can download from developer.facebook.com


private void facebookLogin() {

  facebook = new Facebook(General.FB_APPID);// ((GlobalVars)getApplicationContext()).facebook;

  String access_token = prefs.getString(General.PREFS_FB_token, null);
  Long expires = prefs.getLong(General.PREFS_FB_expires, 0);
  Log.d("MyTag", "token:" + access_token);
  if (access_token != null) {
   facebook.setAccessToken(access_token);
  }
  if (expires != 0) {
   facebook.setAccessExpires(expires);
  }
  /*
   * Only call authorize if the access_token has expired.
   */

  if (!facebook.isSessionValid()) {
   final Editor edit = prefs.edit();
   Log.d("MyTag", "In Authorize");
   facebook.authorize(this,
     new String[] { "publish_stream", "email" },
      new DialogListener() {
      public void onComplete(Bundle values) {
       Log.d("fb login complete",
         "fb login complete");
       Log.d("MyTag",
         "face token: " + facebook.getAccessToken());
       edit.putString(General.PREFS_FB_token,
         facebook.getAccessToken());
       
       edit.putLong(General.PREFS_FB_expires,
         facebook.getAccessExpires());
       edit.commit();
       Toast.makeText(SettingsActivity.this, "login success", Toast.LENGTH_LONG).show();
      }

      public void onFacebookError(FacebookError e) {
       Toast.makeText(getApplicationContext(),
         "onFacebookError", Toast.LENGTH_SHORT)
         .show();
      }

      public void onError(DialogError e) {
       Toast.makeText(getApplicationContext(), "onError",
         Toast.LENGTH_SHORT).show();
      }

      public void onCancel() {

      }
     });
  } else {
   Toast.makeText(this, "login success", Toast.LENGTH_LONG).show();
  }
 }

android play audio/video intent

Audio play intent


Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath),
"audio/*");
startActivity(intent);

video play intent


Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath),
"video/*");
startActivity(intent);

Android choose audio/video or open image using intent

user following code to play audio and video using intent.

Image

Intent intent = new Intent();

intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivity(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);



Aduio


Intent intent = new Intent();

intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivity(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);


Video

Intent intent = new Intent();

intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivity(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);


Friday 11 January 2013

GOOGLE ANDROID C2DM TUTORIAL (ANDROID PUSH NOTIFICATIONS)


Overview of the manifest changes:

Permission to receive C2DM messages
Access to the internet
Restrict access to your C2DM messages so no other app can see them
Declare a Receiver, that we’ll create later, that will let us receive the C2DM events
Make sure that the minSdkVersion is set so that only 2.2 and higher can access your app

<manifest package="com.example.myapp" ...>

   <!-- Only this application can receive the messages and registration result -->
   <permission android:name="com.example.myapp.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
   <uses-permission android:name="com.example.myapp.permission.C2D_MESSAGE" />

   <!-- This app has permission to register and receive message -->
   <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

   <!-- Send the registration id to the server -->
   <uses-permission android:name="android.permission.INTERNET" />

   <application...>
      <!-- Only C2DM servers can send messages for the app. If permission is not set -
any other app can generate it -->
      <receiver android:name=".MyC2dmReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
          <!-- Receive the actual message -->
          <intent-filter>
              <action android:name="com.google.android.c2dm.intent.RECEIVE" />
              <category android:name="com.example.myapp" />
          </intent-filter>
          <!-- Receive the registration id -->
          <intent-filter>
              <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
              <category android:name="com.example.myapp" />
          </intent-filter>
      </receiver>
      ...
   </application>
   ...
</manifest>


----------------------------------------------


Send the Registration call

Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");

registrationIntent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0));

registrationIntent.putExtra("sender", "test@gmail.com"); // google email id for registration

context.startService(registrationIntent);


--------------------------------------------------

receiver for registration and receiving messagess


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.rain.skullcandy.R;
import com.rain.skullcandy.activities.FavoriteLocations;
import com.rain.skullcandy.model.SkullCandyModel;

public class MyC2dmReceiver extends BroadcastReceiver {
private static String KEY = "c2dmPref";
private static String REGISTRATION_KEY = "registrationKey";

private Context context;
@Override
public void onReceive(Context context, Intent intent) {
   this.context = context;
if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
       handleRegistration(context, intent);
   } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
       handleMessage(context, intent);
   }
}

private void handleRegistration(Context context, Intent intent) {
   String registration = intent.getStringExtra("registration_id");
   if (intent.getStringExtra("error") != null) {
       // Registration failed, should try again later.
   Log.d("c2dm", "registration failed");
   String error = intent.getStringExtra("error");
   if(error == "SERVICE_NOT_AVAILABLE"){
   Log.d("c2dm", "SERVICE_NOT_AVAILABLE");
   }else if(error == "ACCOUNT_MISSING"){
   Log.d("c2dm", "ACCOUNT_MISSING");
   }else if(error == "AUTHENTICATION_FAILED"){
   Log.d("c2dm", "AUTHENTICATION_FAILED");
   }else if(error == "TOO_MANY_REGISTRATIONS"){
   Log.d("c2dm", "TOO_MANY_REGISTRATIONS");
   }else if(error == "INVALID_SENDER"){
   Log.d("c2dm", "INVALID_SENDER");
   }else if(error == "PHONE_REGISTRATION_ERROR"){
   Log.d("c2dm", "PHONE_REGISTRATION_ERROR");
   }
   } else if (intent.getStringExtra("unregistered") != null) {
       // unregistration done, new messages from the authorized sender will be rejected
   Log.d("c2dm", "unregistered");

   } else if (registration != null) {
   Log.d("c2dm", registration);
   Editor editor =
                context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
            editor.putString(REGISTRATION_KEY, registration);
    editor.commit();
      // Send the registration ID to the 3rd party site that is sending the messages.
      // This should be done in a separate thread.
      // When done, remember that all registration is done.
   }
}

private void handleMessage(Context context, Intent intent)
{
//Do whatever you want with the message
}
}


Play YouTube video in WebView without launching new Intent


EDIT : Now you can use YouTube Android Player API to play YouTube video in app.


The API offers these benefits :
  • High-quality video playback supported on Android 2.2 (Froyo) or newer
  • Easy integration with your Android application (no WebView required)
  • Fullscreen and orientation change support
  • Integration with the Android YouTube app using a standard set of YouTube Intents
  • And more ..
For further information on this, please Click Here or Here

ORIGINAL POST


Here's the code to play YouTube videos in WebView using video url.
Video plays in appliction itself, not launching new Intent.

XML code file:

activity_video.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".VideoActivity" >

    <Button
        android:id="@+id/btnPlay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top"
        android:layout_margin="5dp" />

    <WebView
        android:id="@+id/videoView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" />

</LinearLayout>


Java Code File:

VideoActivity.java

public class VideoActivity extends Activity {
public static final int USER_MOBILE = 0;
public static final int USER_DESKTOP = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
final WebView video = (WebView) findViewById(R.id.videoView);
Button btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setText("Play Video");

btnPlay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
video.getSettings().setJavaScriptEnabled(true);
video.getSettings().setPluginState(WebSettings.PluginState.ON);
video.getSettings().setUserAgent(USER_MOBILE);
video.setWebChromeClient(new WebChromeClient() {
});

//youtube video url
////http://www.youtube.com/watch?v=WM5HccvYYQg

 final String mimeType = "text/html";
final String encoding = "UTF-8";
String html = getHTML("WM5HccvYYQg");
video.loadDataWithBaseURL("", html, mimeType, encoding, "");
}
});
}


public String getHTML(String videoId) {

String html =
"<iframe class=\"youtube-player\" "
+ "style=\"border: 0; width: 100%; height: 95%;"
+ "padding:0px; margin:0px\" "
+ "id=\"ytplayer\" type=\"text/html\" "
+ "src=\"http://www.youtube.com/embed/" + videoId
+ "?fs=0\" frameborder=\"0\" " + "allowfullscreen autobuffer "
+ "controls onclick=\"this.play()\">\n" + "</iframe>\n";

/**
 * <iframe id="ytplayer" type="text/html" width="640" height="360"
 * src="https://www.youtube.com/embed/WM5HccvYYQg" frameborder="0"
 * allowfullscreen>
 **/

return html;
}

}
Manifest.xml file:
Add the line android:hardwareAccelerated="true" in <appliction> tag

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
<application
        android:hardwareAccelerated="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
...
...
</application>
</manifest>

android video recording


Here is complete example of how to record video in android device.
(Note: test project in real device not in emulator)

1.  Video View Activity
  
    
import java.io.File;
import java.io.IOException;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.Menu;
import android.view.SurfaceView;
import android.widget.Toast;

public class VideoViewActivity extends Activity implements Callback {

    @Override
    protected void onDestroy() {
        stopRecording();
        super.onDestroy();
    }

    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public MediaRecorder mrec = new MediaRecorder();   
    private Camera mCamera;


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

        surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        mCamera = Camera.open();
      
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
              
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {

        menu.add(0, 0, 0, "Start");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if(item.getTitle().equals("Start"))
        {
            try {
              
                startRecording();
                item.setTitle("Stop");

            } catch (Exception e) {

                String message = e.getMessage();
                Log.i(null, "Problem " + message);
                mrec.release();
            }

        }
        else if(item.getTitle().equals("Stop"))
        {
            mrec.stop();
            mrec.release();
            mrec = null;
            item.setTitle("Start");
        }

        return super.onOptionsItemSelected(item);
    }

    protected void startRecording() throws IOException
    {
        if(mCamera==null)
            mCamera = Camera.open();
      
         String filename;
         String path;
      
         path= Environment.getExternalStorageDirectory().getAbsolutePath().toString();
        
         Date date=new Date();
         filename="/rec"+date.toString().replace(" ", "_").replace(":", "_")+".mp4";
        
         //create empty file it must use
         File file=new File(path,filename);
        
        mrec = new MediaRecorder();

        mCamera.lock();
        mCamera.unlock();

        // Please maintain sequence of following code.

        // If you change sequence it will not work.
        mrec.setCamera(mCamera);   
        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mrec.setAudioSource(MediaRecorder.AudioSource.MIC);   
        mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setOutputFile(path+filename);
        mrec.prepare();
        mrec.start();

      
    }

    protected void stopRecording() {

        if(mrec!=null)
        {
            mrec.stop();
            mrec.release();
            mCamera.release();
            mCamera.lock();
        }
    }

    private void releaseMediaRecorder() {

        if (mrec != null) {
            mrec.reset(); // clear recorder configuration
            mrec.release(); // release the recorder object
        }
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release(); // release the camera for other applications
            mCamera = null;
        }

    }

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

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {     

        if (mCamera != null) {
            Parameters params = mCamera.getParameters();
            mCamera.setParameters(params);
            Log.i("Surface", "Created");
        }
        else {
            Toast.makeText(getApplicationContext(), "Camera not available!",
                    Toast.LENGTH_LONG).show();

            finish();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();     

    }
}



2. main.xml file

    
         <SurfaceView android:id="@+id/surface_camera"     xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:layout_weight="1"
        >
    </SurfaceView>





3.  Get following permission in AndroidManifest.xml

      <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


android unicode text to readable text

you need to use appropriate unicode font to do that.
for example if you want to print hindi then you have to use any hindi font file

suppose hindi font file is "hindi.ttf"
then to print hindi unicode into textview you have to set hindi font like following

txtLyricsEnglish = (TextView) findViewById(R.id.txtLyricsEnglish);
Typeface font = Typeface.createFromAsset(getAssets(),
    "hindi.ttf");
txtLyricsEnglish.setTypeface(font);


Wednesday 9 January 2013

how to generate facebook key hashes


Android KEY HASH  for Facebook :

Download openSSl from :
http://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_WIN32.zip

Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.

Detect debug.keystore file path.

Detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Intel\.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary | "C:\OpenSSL\bin\openssl" base64

so facebook "key hash" for this pc is like JdiLgmuFZfHkh79Ejcy2OKGlzkQ=

Tuesday 8 January 2013

android project export "Conversion to Dalvik format failed with error 1" on external JAR

Go to Project » Properties » Java Build Path » Libraries and remove all except the "Android X.Y" (in my case Android 1.5). click OK. Go to Project » Clean » Clean projects selected below » select your project and click OK. That should work.

It is also possible that you have a JAR file located somewhere in your project folders (I had copied the Admob JAR file into my src folder) and THEN added it as a Java Path Library. It does not show up under the Package Explorer, so you don't notice it, but it does get counted twice, causing the dreaded Dalvik error 1.

Another possible reason could be package name conflicts. Suppose you have a package com.abc.xyz and a class named A.java inside this package, and another library project (which is added to the dependency of this project) which contains the same com.abc.xyz.A.java, then you will be getting the exact same error. This means, you have multiple references to the same file A.java and can't properly build it.

Tuesday 1 January 2013

in java is HashMap() sorted on keys by default?

Use LinkedHashMap if you want to store your data in the order in which keys are inserted into the Map. 
HashMap doesn't guarantee any order.

android listview list item with checkbox not able to click list item

please set check box 's android:focusable="false"
or if other element like edit text  etc