Wednesday, 18 December 2013

Resize the ListView Default Row Size in Android

1. I had just made my own layout in R/layout as mylist.xml

<?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:textSize="7pt"    
              android:paddingTop="2dip" 
              android:paddingBottom="2dip"
              android:textColor="@android:color/black"   
              android:gravity="center"/>

2.and then i changed my main.xml to show a listview. like,

<LinearLayout android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <ListView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/my_list"/>
    </LinearLayout>

And at last i have my activity file like

    // all the stuff
    // i cant put my code here,na?:)
   //Its simple. just change layout to ours
    ListView list;
    list = (ListView)findViewById(R.id.my_list);
    ArrayAdapter<CharSequence> list_adapter= ArrayAdapter.createFromResource(
            this, R.array.my_array, R.layout.mylist);
    my_list.setAdapter(list_adapter);

Friday, 29 November 2013

Finish the Activity After AsyncTask Completed in Android

Methode 1:

As AsyncTaskActivity is in separate file than LoginActivity, you cant finish LoginActivity by: Login.this.finish();
Instead you should pass the Activity Reference as parameter in the AsyncTaskActivity Class, like you can define following constructor:

private class AsyncTaskActivity extends AsyncTask<String, Void, String> {
Activity mActivity;
    public AsyncTaskActivity(Activity activity)    {
                 super();
         this.mActivity=activity;
    }
}
and whenever you want to finish the activity call
this.mActivity.finish();

Create AsyncTaskActivity's Object in LoginActivity by 
AsyncTaskActivity asynTask = new AsyncTaskActivity(LoginActivity.this);


Methode 2:

What you can try to do instead of calling context.finish(), why don't you do a callback interface like this:

public interface TaskCallback{
void done();
}

Then you implement this into your Activity

public Hello extends Activity implements TaskCallback{

    .....BUNCH OF ACTIVITY CODE.....

public void onCreate(Bundle savedInstanceState) {

    MyTask mt = new MyTask(this);
    mt.execute();
}

public void done() {
     finish();
}

}

And instead of having Context as a parameter you have TaskCallback

public class MyTask extends AsyncTask<Void, Void, Void> {
private TaskCallback mCallback;

public MyTask(TaskCallback callback) {

    mCallback = callback;

//doinbackground, etc

    protected void onPostExecute() {
    mCallback.done();

}

There you go, it gives you more flexibility to custom each implementation.



Monday, 25 November 2013

Android ListView Item Normal and Pressed Background Change Through xml


Like this:



listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#FFFFFF"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />


</LinearLayout>


list_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selector style for listrow -->
<item 
 android:state_selected="false"
    android:state_pressed="false" 
    android:drawable="@drawable/gradient_bg" />
<item android:state_pressed="true" 
    android:drawable="@drawable/gradient_bg_hover" />
<item android:state_selected="true"
 android:state_pressed="false" 
    android:drawable="@drawable/gradient_bg_hover" />

</selector>

gradient_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <!--  Gradient Bg for listrow -->
  <gradient
      android:startColor="#f1f1f2"
      android:centerColor="#e7e7e8"
      android:endColor="#cfcfcf"
      android:angle="270" />
</shape>

gradient_bg_hover.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <!-- Gradient BgColor for listrow Selected -->
  <gradient
      android:startColor="#18d7e5"
      android:centerColor="#16cedb"
      android:endColor="#09adb9"
      android:angle="270" />

</shape>

Monday, 7 October 2013

Android Google Map V2

Before starting a new project of Google map V2,
we need to go through some pre required steps. These steps involves importing required library, generating SHA1 fingerprint and configuring maps in google console.

1. Downloading Google Play Services
we need to download google play services from SDK manger.

Open Eclipse ⇒ Windows ⇒ Android SDK Manager and check whether you have already downloaded Google Play Services or not under Extras section. If not select play services and install the package.


2. Importing Google Play Services into Eclipse

1. In Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace
2. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib
3. Importantly while importing check Copy projects into workspace option as shown in the below image.


3. Getting the Google Maps API key

1. Same as in maps v1 we need to generate SHA-1 fingerprint using java keytool. Open your terminal and execute the following command to generate SHA-1 fingerprint.

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

For example as par my system:
C:\Program Files\Java\jdk1.6.0_26\bin >keytool.exe -V -list -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator\.android \debug.keystore" -storepass android -keypass android

Consider your jdk-bin path in the first path place and your home user directory in thesecond path. For windows 7 it is like    C:\Users\username\.android\debug.keystore

In the output you can see SHA 1 finger print.


2. Now open Google API Console
3. Select Services on left side and turn on Google Maps Android API v2


4. Now select API Access on left side and on the right side click on Create new Android key…


5. It will popup a window asking the SHA1 and package name. Enter your SHA 1 and your android project package name separated by semicolon ; and click on create.

note down the API key which required later in our project.

4. Creating new Project

After completing required configuration, It’s time to start our project.
1. In Eclipse create a new project by going to File ⇒ New ⇒ Android Application Project and fill required details. I kept my project name as Google Maps V2 and package name asinfo.androidhive.info
2. Now we need to use Google Play Services project as a library to use project. So right click on project and select properties. In the properties window on left side select Android. On the right you can see aAdd button under library section. Click it and select google play services project which we imported previously.








3. Add the Map Key in the manifest file. Open AndroidManifest.xml file and add the following code before tag. Replace the android:value with your map key which you got from google console.

<!-- Goolge Maps API Key -->
<meta-data
     android:name="com.google.android.maps.v2.API_KEY"
     android:value="Your API Key" />

 4. Google maps needs following permissions and features.

ACCESS_NETWORK_STATE – To check network state whether data can be downloaded or not
INTERNET – To check internet connection status
WRITE_EXTERNAL_STORAGE – To write to external storage as google maps store map data in external storage
ACCESS_COARSE_LOCATION – To determine user’s location using WiFi and mobile cell data
ACCESS_FINE_LOCATION – To determine user’s location using GPS
OpenGL ES V2 – Required for Google Maps V2

Finally my AndroidManifest.xml file looks like this (Replace the package name with your project package)

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.prashant.googlemapsv2"
    android:versionCode="1"
    android:versionName="1.0" >
    <permission
        android:name="com.prashant.googlemapsv2".permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.prashant.googlemapsv2".permission.MAPS_RECEIVE" />
    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name="com.prashant.googlemapsv2".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppBaseTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Goolge API Key -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBZMlkOv4sj-M5JO9p6wksdax4TEjDVLgo" />
    </application>
</manifest>

5. New google maps are implemented using MapFragments which is a sub class of Fragmentsclass. Open your main activity layout file activity_main.xml file and add following code. I usedRelativeLayout as a parent element. You can remove it and use MapFragment directly.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

6. Add the following code in your Main Activity java MainActivity.java class.

MainActivity.java
public class MainActivity extends Activity {
    // Google Map
    private GoogleMap googleMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            // Loading map
            initilizeMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
   }

    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();

    }
}


Friday, 30 August 2013

Share With Intents


 MainActivity :

package com.example.shareintent;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        Button sharingButton = (Button)findViewById(R.id.imageButton1);
        sharingButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                shareIt();
            }

            private void shareIt() {
                Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
              
                sharingIntent.setType("text/plain");
                String shareBody = "Here is the share content body";
                sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
                startActivity(Intent.createChooser(sharingIntent, "Share via"));
            }
        });
      
      
    }
}

 Output:


Thursday, 29 August 2013

Capture Active Screen in Android

AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.capturescreen"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.capturescreen.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity :

package com.example.capturescreen;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
 
public class MainActivity extends Activity {
 
Bitmap bmScreen;
 
Dialog screenDialog;
static final int ID_SCREENDIALOG = 1;
 
ImageView bmImage;
Button btnScreenDialog_OK;
TextView TextOut;
 
View screen;
EditText EditTextIn;
 
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     screen = (View)findViewById(R.id.screen);
     Button btnCaptureScreen = (Button)findViewById(R.id.capturescreen);
     EditTextIn = (EditText)findViewById(R.id.textin);
   
     btnCaptureScreen.setOnClickListener(new OnClickListener(){
 
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   screen.setDrawingCacheEnabled(true);
   bmScreen = screen.getDrawingCache();
   showDialog(ID_SCREENDIALOG);
  }});
 }
 
 
@Override
protected Dialog onCreateDialog(int id) {
 // TODO Auto-generated method stub
 
 screenDialog = null;
 switch(id){
 case(ID_SCREENDIALOG):
  screenDialog = new Dialog(this);
  screenDialog.setContentView(R.layout.dialog);
  bmImage = (ImageView)screenDialog.findViewById(R.id.image);
  TextOut = (TextView)screenDialog.findViewById(R.id.textout);
  btnScreenDialog_OK = (Button)screenDialog.findViewById(R.id.okdialogbutton);
  btnScreenDialog_OK.setOnClickListener(btnScreenDialog_OKOnClickListener);
 }
 return screenDialog;
}
 
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
 // TODO Auto-generated method stub
 switch(id){
 case(ID_SCREENDIALOG):
  dialog.setTitle("Captured Screen");
  TextOut.setText(EditTextIn.getText().toString());
  bmImage.setImageBitmap(bmScreen);
  break;
 }
}
 
private Button.OnClickListener btnScreenDialog_OKOnClickListener
 = new Button.OnClickListener(){
 
 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  screenDialog.dismiss();
 }};
}

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@+id/screen">
    <Button
     android:id="@+id/capturescreen"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Capture Screen"/>
    <TextView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Enter some text here which you will see on captured screen"/>
    <EditText
     android:id="@+id/textin"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"/>
</LinearLayout>

dialog.xml :
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="10dip"
android:paddingRight="10dip">
    <TextView
    android:id="@+id/textout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
    <ImageView
    android:id="@+id/image"
    android:layout_width="400px"
    android:layout_height="400px"/>
    <Button
    android:id="@+id/okdialogbutton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="OK"/>
</LinearLayout>

Output Screen :

Error : The connection to adb is down, and a severe error has occured.

Getting Error:

>The connection to adb is down, and a severe error has occured.
>You must restart adb and Eclipse.
>Please ensure that adb is correctly located at 'C:\Android\android-sdk-windows\platform-tools\adb.exe' and can be executed.
>Daemon not running.ADB server didn't ACK


1. Go to the platform-tools directory:(you can find where you have AVD Manager.exe or SDK Manager.exe)
or in some paths given below:
Path 1 : C:\Android\android-sdk-windows\platform-tools>
Path 2 : C:\Program files\Android\android-sdk-windows\platform-tools>
Path 3 : C:\Program files(x86)\Android\android-sdk-windows\platform-tools>













 


2. Now check you have adb.exe present.

3. Now you need to have proper "android-sdk" normally it can never be absent.
    As it will be definitely there so open you terminal ( LINUX / UBUNTU users ) or command    prompt/ cmd ( Windows users ) and go to the above path where you have adb.exe:
cd\
cd C:\Android\android-sdk-windows\platform-tools [ or your adb.exe path ]
Now, use following two command:
adb kill-server
adb start-server
[ you can use this commands when Eclipse closed or open; if it doesn't work when your eclipse is open do it after closing eclipse. ]


NOTE: you can also end or kill process of adb.exe from task manager.

in Windows, just use task manager to kill the process.


 And Restart Eclipse.