Monday 16 December 2013

Login with Facebook Account in ANdroid Application


First of all Generate Applcaition in facebook developer account and get applciaiton id from it and besides this geenrate hask key from your pc

For generating Hash Key put following command in terminal

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\NK\.android\debug.keystore" | "D:\AndroidSetUp\openssl-0.9.8k_WIN32\bin\openssl" sha1 -binary | "D:\AndroidSetUp\openssl-0.9.8k_WIN32\bin\openssl" base64

then you have to enter keystore password
Enter keystore password : android
faAfdgdfgADSfdvGfdgfdfdgfgg=
you will finallly get your hask key this key put into developer site make code in your activity

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class AndroidFacebookConnectActivity extends Activity {

// Your Facebook APP ID
private static String APP_ID = "639585436072863"; // Replace with your App ID

// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;

// Buttons
Button btnFbLogin;
Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;

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

btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
mAsyncRunner = new AsyncFacebookRunner(facebook);

/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});

/**
* Getting facebook Profile info
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
getProfileInformation();
}
});

/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
postToWall();
}
});

/**
* Showing Access Tokens
* */
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
showAccessTokens();
}
});

}

/**
* Function to login into facebook
* */
public void loginToFacebook() {

mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);

if (access_token != null) {
facebook.setAccessToken(access_token);

btnFbLogin.setVisibility(View.INVISIBLE);

// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);

// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);

// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);

Log.d("FB Sessions", "" + facebook.isSessionValid());
}

if (expires != 0) {
facebook.setAccessExpires(expires);
}

if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {

@Override
public void onCancel() {
// Function to handle cancel event
}

@Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();

// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);

// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);

// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);

// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
}

@Override
public void onError(DialogError error) {
// Function to handle error

}

@Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors

}

});
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}


/**
* Get Profile information by making request to Facebook Graph API
* */
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);

// getting name of the user
final String name = profile.getString("name");

// getting email of the user
final String email = profile.getString("email");

runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}

});


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

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}

/**
* Function to post to facebook wall
* */
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {

@Override
public void onFacebookError(FacebookError e) {
}

@Override
public void onError(DialogError e) {
}

@Override
public void onComplete(Bundle values) {
}

@Override
public void onCancel() {
}
});

}

/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();

Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}

/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {

@Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);

// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
}

});

}
}

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}


Google Plus Intigration in Android Application


follow this step
https://developers.google.com/+/mobile/android/sign-in

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.plus.PlusClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class SignInActivity extends Activity implements OnClickListener,
        PlusClient.ConnectionCallbacks, PlusClient.OnConnectionFailedListener,
        PlusClient.OnAccessRevokedListener {

    private static final int DIALOG_GET_GOOGLE_PLAY_SERVICES = 1;

    private static final int REQUEST_CODE_SIGN_IN = 1;
    private static final int REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES = 2;

    private TextView mSignInStatus;
    private PlusClient mPlusClient;
    private SignInButton mSignInButton;
    private View mSignOutButton;
    private View mRevokeAccessButton;
    private ConnectionResult mConnectionResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_in_activity);

        mPlusClient = new PlusClient.Builder(this, this, this)
                .setActions(MomentUtil.ACTIONS)
                .build();

        mSignInStatus = (TextView) findViewById(R.id.sign_in_status);
        mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
        mSignInButton.setOnClickListener(this);
        mSignOutButton = findViewById(R.id.sign_out_button);
        mSignOutButton.setOnClickListener(this);
        mRevokeAccessButton = findViewById(R.id.revoke_access_button);
        mRevokeAccessButton.setOnClickListener(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        mPlusClient.connect();
    }

    @Override
    public void onStop() {
        mPlusClient.disconnect();
        super.onStop();
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()) {
            case R.id.sign_in_button:
                int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
                if (available != ConnectionResult.SUCCESS) {
                    showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES);
                    return;
                }

                try {
                    mSignInStatus.setText(getString(R.string.signing_in_status));
                    mConnectionResult.startResolutionForResult(this, REQUEST_CODE_SIGN_IN);
                } catch (IntentSender.SendIntentException e) {
                    // Fetch a new result to start.
                    mPlusClient.connect();
                }
                break;
            case R.id.sign_out_button:
                if (mPlusClient.isConnected()) {
                    mPlusClient.clearDefaultAccount();
                    mPlusClient.disconnect();
                    mPlusClient.connect();
                }
                break;
            case R.id.revoke_access_button:
                if (mPlusClient.isConnected()) {
                    mPlusClient.revokeAccessAndDisconnect(this);
                    updateButtons(false /* isSignedIn */);
                }
                break;
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) {
            return super.onCreateDialog(id);
        }

        int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (available == ConnectionResult.SUCCESS) {
            return null;
        }
        if (GooglePlayServicesUtil.isUserRecoverableError(available)) {
            return GooglePlayServicesUtil.getErrorDialog(
                    available, this, REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES);
        }
        return new AlertDialog.Builder(this)
                .setMessage(R.string.plus_generic_error)
                .setCancelable(true)
                .create();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_SIGN_IN
                || requestCode == REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES) {
            if (resultCode == RESULT_OK && !mPlusClient.isConnected()
                    && !mPlusClient.isConnecting()) {
                // This time, connect should succeed.
                mPlusClient.connect();
            }
        }
    }

    @Override
    public void onAccessRevoked(ConnectionResult status) {
        if (status.isSuccess()) {
            mSignInStatus.setText(R.string.revoke_access_status);
        } else {
            mSignInStatus.setText(R.string.revoke_access_error_status);
            mPlusClient.disconnect();
        }
        mPlusClient.connect();
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        String currentPersonName = mPlusClient.getCurrentPerson() != null
                ? mPlusClient.getCurrentPerson().getDisplayName()
                : getString(R.string.unknown_person);
        mSignInStatus.setText(getString(R.string.signed_in_status, currentPersonName));
        updateButtons(true /* isSignedIn */);
    }

    @Override
    public void onDisconnected() {
        mSignInStatus.setText(R.string.loading_status);
        mPlusClient.connect();
        updateButtons(false /* isSignedIn */);
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        mConnectionResult = result;
        updateButtons(false /* isSignedIn */);
    }

    private void updateButtons(boolean isSignedIn) {
        if (isSignedIn) {
            mSignInButton.setVisibility(View.INVISIBLE);
            mSignOutButton.setEnabled(true);
            mRevokeAccessButton.setEnabled(true);
        } else {
            if (mConnectionResult == null) {
                // Disable the sign-in button until onConnectionFailed is called with result.
                mSignInButton.setVisibility(View.INVISIBLE);
                mSignInStatus.setText(getString(R.string.loading_status));
            } else {
                // Enable the sign-in button since a connection result is available.
                mSignInButton.setVisibility(View.VISIBLE);
                mSignInStatus.setText(getString(R.string.signed_out_status));
            }

            mSignOutButton.setEnabled(false);
            mRevokeAccessButton.setEnabled(false);
        }
    }
}

Tuesday 10 December 2013

Add reminder to default Calender from our Application

MainActivity.java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * To display the given data as notification at particular date and time
 *
 * @author Harshal Kalavadiya
 */

public class TaskReminderActivity extends Activity {
    /** Called when the activity is first created. */

    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;
    static final int DATE_DIALOG_ID = 1;
    static final int TIME_DIALOG_ID = 0;
    private Calendar c;  
    private EditText nameEdit;
    private EditText descEdit;
    private Context mContext;  
    private boolean dateFlag = false;
    private boolean timeFlag = false;
    private String time;
    private String contentTitle;
    private String contentText;
    public static int notificationCount;
    public Button dateButton;
    public Button timeButton;
    public Button reminButton;
    public TextListener textListener;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        mContext = this;
        textListener = new TextListener();
        dateButton= (Button)findViewById(R.id.dateButton);
        timeButton= (Button)findViewById(R.id.timeButton);
        reminButton= (Button)findViewById(R.id.reminderButton);
        dateButton.setEnabled(false);
  timeButton.setEnabled(false);
  reminButton.setEnabled(false);
        nameEdit = (EditText)findViewById(R.id.nameEditText);
        nameEdit.addTextChangedListener(textListener);
        descEdit = (EditText)findViewById(R.id.DescEditText);
        descEdit.addTextChangedListener(textListener);  
        c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
    }
 
    public class TextListener implements TextWatcher{

   @Override
  public void afterTextChanged(Editable s) {
   // TODO Auto-generated method stub
  }

   @Override
  public void beforeTextChanged(CharSequence s, int start, int count,
    int after) {
   // TODO Auto-generated method stub
  }

   @Override
  public void onTextChanged(CharSequence s, int start, int before,
    int count) {
   // TODO Auto-generated method stub
   if(descEdit.getText().length()==0 | nameEdit.getText().length()==0){
    dateButton.setEnabled(false);
    timeButton.setEnabled(false);
    reminButton.setEnabled(false);
   }
   else if(descEdit.getText().length()>0 & nameEdit.getText().length()>0){
    dateButton.setEnabled(true);
    timeButton.setEnabled(true);
    reminButton.setEnabled(true);
   }
  }  
    }
 
    public void onReminderClicked(View view){      
     if(dateFlag & timeFlag == true){
      notificationCount  = notificationCount+1;
      dateFlag = false;
      timeFlag = false;
      time = mYear+"-"+mMonth+"-"+mDay+" "+mHour+"-"+mMinute;                              
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh-mm");
            Date dt = null;
   try {
    dt = df.parse(time);
   } catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }                                      
            long when = dt.getTime();              
            contentTitle = nameEdit.getText().toString();
            contentText = descEdit.getText().toString();      
         AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
         Intent notificationIntent = new Intent(mContext, ReminderAlarm.class);
         notificationIntent.putExtra("Name",contentTitle );
            notificationIntent.putExtra("Description",contentText );
            notificationIntent.putExtra("NotifyCount",notificationCount );
         PendingIntent pi = PendingIntent.getBroadcast(mContext, notificationCount, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
         mgr.set(AlarmManager.RTC_WAKEUP,when, pi);
         Toast.makeText(mContext, "Your Reminder Activated", Toast.LENGTH_LONG).show();
            contentTitle = "";
         contentText = "";
         descEdit.setText("");
         nameEdit.setText("");
     }
     else if(dateFlag == false | timeFlag == false){
      Toast.makeText(mContext, "Please choose Date & Time", Toast.LENGTH_SHORT).show();
     }
    }
 
    public void onTimeClicked(View view){  
     showDialog(TIME_DIALOG_ID);
    }
    public void onDateClicked(View view){  
     showDialog(DATE_DIALOG_ID);  
    }
 
    @Override
    protected Dialog onCreateDialog(int id) {
     // TODO Auto-generated method stub
     switch (id) {
      case TIME_DIALOG_ID:
         return new TimePickerDialog(this,
              mTimeSetListener, mHour, mMinute, false);
      case DATE_DIALOG_ID:
          return new DatePickerDialog(this,
                      mDateSetListener,
                      mYear, mMonth, mDay);
      }
     return super.onCreateDialog(id);
    }
 
    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear+1;
                mDay = dayOfMonth;              
                dateFlag = true;
            }
    };
     
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                timeFlag = true;
            }
    };

}

ReminderAlarm.java

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.widget.Toast;

/**
 * Trigger Status bar Notification alert at particular date and time
 *
 * @author Kumaresan Palanisamy
 */
public class ReminderAlarm  extends BroadcastReceiver{
 private NotificationManager mNotificationManager;
 private Notification notification;

  @Override
 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub    
      mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      CharSequence from = intent.getStringExtra("Name");
      CharSequence message = intent.getStringExtra("Description");
      PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
      notification = new Notification(R.drawable.ic_launcher,"Notification", System.currentTimeMillis());
      notification.setLatestEventInfo(context, from, message, contentIntent);
      mNotificationManager.notify(Integer.parseInt(intent.getExtras().get("NotifyCount").toString()), notification);      
      Toast.makeText(context, "New Notification Received", Toast.LENGTH_LONG).show();
 }

}

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"
    android:orientation="vertical"    
     >
 <LinearLayout    
     android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/nameLayout">
      <TextView
          android:layout_width="100dp"
          android:layout_height="wrap_content"
          android:text="@string/Name"/>  
      <EditText
          android:id="@+id/nameEditText"
          android:hint="Enter Name "              
          android:layout_height="45dp"        
          android:layout_width="200dp" />  
    </LinearLayout>  
 <LinearLayout  
     android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/descLayout"
       android:layout_below="@id/nameLayout">
      <TextView
          android:layout_width="100dp"
          android:layout_height="wrap_content"
          android:text="@string/Desc"/>  
      <EditText
          android:id="@+id/DescEditText"
          android:hint="Enter Description"          
          android:layout_height="45dp"        
          android:layout_width="200dp" />  
    </LinearLayout>    
 <LinearLayout
     android:layout_marginTop="20dp"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal"
     android:layout_below="@id/descLayout"  
     android:gravity="center_horizontal"
     >  
  <Button
      android:id="@+id/dateButton"
      android:layout_width="100sp"
      android:layout_height="wrap_content"
      android:text="@string/Date"
      android:onClick="@string/DateClick"
      />
     <Button
         android:id="@+id/timeButton"
      android:layout_width="100sp"
       android:layout_height="wrap_content"
      android:text="@string/Time"
      android:onClick="@string/Timeclick"/>
     <Button
         android:id="@+id/reminderButton"
      android:layout_width="100sp"
      android:layout_height="wrap_content"
      android:text="@string/Reminder"
      android:onClick="@string/ReminderClick"/>
 </LinearLayout>

</RelativeLayout>

Friday 6 December 2013

Gridview inside ScrollView in android

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;

public class NestedGridView extends GridView {
boolean expanded = true;
public NestedGridView(Context context) {
super(context);
}
public NestedGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NestedGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// HACK! TAKE THAT ANDROID!
if (isExpanded()) {
// Calculate entire height by providing a very large height hint.
// View.MEASURED_SIZE_MASK represents the largest height possible.
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setIsExpanded(boolean expanded) {
this.expanded = expanded;
}

}

Thursday 5 December 2013

Custom Gridview With Checkbox in Android

public class Check extends Activity {
     
//    List <String> ImageList;
    ArrayList<ParserCategory>mList;
    DatabaseConnectionAPI mApi;
    ImageAdapter mAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        /*** Get Images from SDCard ***/
//        ImageList = getSD();
       
        // gridView1
        mApi=new DatabaseConnectionAPI(getApplicationContext());
        try {
            mApi.createDataBase();
              mApi.openDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     
        mList=mApi.getCategoryData();
        final GridView gView1 = (GridView)findViewById(R.id.gridView1);
           
        mAdapter=new ImageAdapter(Check.this, mList);
        gView1.setAdapter(mAdapter);
       

        // Check All
        Button btnCheckAll = (Button) findViewById(R.id.btnCheckAll);
        btnCheckAll.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                int count = gView1.getAdapter().getCount();
                for (int i = 0; i < count; i++) {
                    LinearLayout itemLayout = (LinearLayout)gView1.getChildAt(i); // Find by under LinearLayout
                    CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
                    checkbox.setChecked(true);
                } 
            }
        });
       
        // Clear All
        Button btnClearAll = (Button) findViewById(R.id.btnClearAll);
        btnClearAll.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                int count = gView1.getAdapter().getCount();
                for (int i = 0; i < count; i++) {
                    LinearLayout itemLayout = (LinearLayout)gView1.getChildAt(i); // Find by under LinearLayout
                    CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
                    checkbox.setChecked(false);
                } 
            }
        });
       
        // Get Item Checked
        Button btnGetItem = (Button) findViewById(R.id.btnGetItem);
        btnGetItem.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
//                int count = gView1.getAdapter().getCount();
                int count =  gView1.getChildCount();

                System.out.println("Count "+count);
                for (int i = 0; i < count; i++) {
                    ViewGroup gridChild = (ViewGroup) gView1.getChildAt(i);
//                    LinearLayout itemLayout = (LinearLayout)gView1.getChildAt(i); // Find by under LinearLayout
//                    System.out.println("itemLayout "+itemLayout);
                    CheckBox checkbox = (CheckBox)gridChild.findViewById(R.id.checkBox1);
                    if(checkbox.isChecked())
                    {
                        Log.d("Item "+String.valueOf(i), checkbox.getTag().toString());
                        System.out.println("ITEEMERM  "+String.valueOf(i)+checkbox.getTag().toString());
                        Toast.makeText(Check.this,checkbox.getTag().toString() ,2000).show(); 
                    }
                } 
            }
        });
     
    }

//    private List <String> getSD()
//    {
//        List <String> it = new ArrayList <String>();
//        File f = new File ("/mnt/sdcard/picture");
//        File[] files = f.listFiles ();
//       
//        for (int i = 0; i <files.length; i++)
//        {
//            File  file = files[i];
//            Log.d("Count",file.getPath());
//            it.add (file.getPath());
//        }
//        return it;
//    }
   
    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<ParserCategory> lis;
       
        public ImageAdapter(Context c, ArrayList<ParserCategory> mList)
        {
            //
            context = c;
            lis = mList;
        }

        public int getCount() {
            //
            return lis.size();
        }

        public Object getItem(int position) {
            //
            return position;
        }

        public long getItemId(int position) {
            //
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            //
           
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       
       
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.showimage, null);
                }
               
                TextView textView = (TextView) convertView.findViewById(R.id.textView1);
                String strPath = lis.get(position).toString();
               
                // Get File Name
                String fileName=lis.get(position).getCname();
//                String fileName = strPath.substring( strPath.lastIndexOf('/')+1, strPath.length() );
                textView.setText(lis.get(position).getCname());
               
                // Image Resource
                ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
                // CheckBox
                CheckBox Chkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
                Chkbox.setTag(fileName);
       
                return convertView;
               
        }
    }
   
   

}

Custom Gridview with Multiple radiobutton with Single Selection in Android

row_file.xml

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

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_height="wrap_content"
         />

    <TextView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/radioButton1"
         />

</RelativeLayout>





MainActivity.Java

 package com.example.china;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Adapter gAdapter;
    private GridView gBankLogo;
    private int lastPosition = -1;
    private View lastView;
  
    ArrayList<ParserCategory>mList;
    DatabaseConnectionAPI mApi;
    Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gBankLogo = (GridView)findViewById(R.id.gridView1);
        mButton=(Button)findViewById(R.id.btn);
        mButton.setOnClickListener(new View.OnClickListener() {
          
            @Override
            public void onClick(View v) {
              
                int count =  gBankLogo.getChildCount();

                System.out.println("Count "+count);
                for (int i = 0; i < count; i++) {
                    ViewGroup gridChild = (ViewGroup) gBankLogo.getChildAt(i);
                    RadioButton checkbox = (RadioButton)gridChild.findViewById(R.id.radioButton1);
                    if(checkbox.isChecked())
                    {
                        Log.d("Item "+String.valueOf(i), checkbox.getTag().toString());
                        System.out.println("ITEEMERM  "+String.valueOf(i)+checkbox.getTag().toString());
                        Toast.makeText(MainActivity.this,checkbox.getTag().toString() ,2000).show();
                    }
                }
            }
        });
        mApi=new DatabaseConnectionAPI(getApplicationContext());
        try {
            mApi.createDataBase();
              mApi.openDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        mList=mApi.getCategoryData();
      
      
        gAdapter = new Adapter(this,mList);
      //TEST
        for (int i = 0; i < mList.size(); i++) {
             String bank = "";
             gAdapter.addObject("bank"+i, bank);
        }    
        gBankLogo.setAdapter(gAdapter);
        gBankLogo.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (lastPosition == position)
                    return;
                if (lastPosition != position) {
                    if (lastPosition == -1) {
                        RadioButton tmp = (RadioButton) view.findViewById(R.id.radioButton1);
                        tmp.setChecked(true);
                        lastView = view;
                        lastPosition = position;
                    } else {
                        RadioButton tmp = (RadioButton) view.findViewById(R.id.radioButton1);
                        tmp.setChecked(true);
                        RadioButton tmp1 = (RadioButton) lastView.findViewById(R.id.radioButton1);
                        tmp1.setChecked(false);
                        lastView = view;
                        lastPosition = position;
                    }
                }
            }
        });     
    }
}
 Adapter.Java
 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;

public class Adapter extends BaseAdapter {
    private ViewHolder holder;
    private LayoutInflater mLayoutInflater;
    private static Map<String, Object> M = new HashMap<String, Object>();
    private static List<String> L = new ArrayList<String>();
    ArrayList<ParserCategory>mList;
    Activity mActivity;  
    public Adapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);

    }

    public Adapter(MainActivity mainActivity, ArrayList<ParserCategory> mList) {
        // TODO Auto-generated constructor stub
        mActivity=mainActivity;
        this.mList=mList;
    }

    public void addObject(String key, String bank) {
        if (!L.contains(key)) {
            L.add(key);
        }
        M.put(key, bank);
        this.notifyDataSetChanged();
    }

    public void removeObject(String key) {
        M.remove(key);
        L.remove(key);
        this.notifyDataSetChanged();
    }

    public void removeAllObject() {
        if (getCount() != 0) {
            M.clear();
            L.clear();
            this.notifyDataSetChanged();
        }
    }

    public void removeAllSelect() {
        if (getCount() != 0) {
            holder.rSelect.setChecked(false);
            this.notifyDataSetChanged();
        }
    }

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

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

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if (convertView == null) {
            holder = new ViewHolder();
          
            LayoutInflater inflater = (LayoutInflater) mActivity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        
        
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.item_msgbanklogo, null);
                }
//            convertView = mLayoutInflater.inflate(R.layout.item_msgbanklogo,null);
            holder.mTextView = (TextView) convertView
                    .findViewById(R.id.imageView1);
            holder.rSelect = (RadioButton) convertView
                    .findViewById(R.id.radioButton1);
            holder.mTextView.setText(mList.get(position).getCname());
             holder.rSelect.setTag(mList.get(position).getCname());
            holder.mTextView.setClickable(false);
            holder.rSelect.setClickable(false);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        return convertView;
    }
}
 ViewHolder.java

public class ViewHolder {
    TextView mTextView;
    RadioButton rSelect;
}





Monday 9 September 2013

ScrollView Inside Another Scrollview in Android

Layout File 

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

    <ScrollView
        android:id="@+id/activity_main_parent_scroll"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:focusableInTouchMode="true" >

        <LinearLayout
            android:id="@+id/activity_main_linear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <ScrollView
                android:id="@+id/activity_main_child_scroll"
                android:layout_width="fill_parent"
                android:layout_height="@dimen/widthsize100"
                android:focusable="true"
                android:focusableInTouchMode="true" >

                <TextView
                    android:id="@+id/activity_main_activity_main_text_description"
                    style="@style/Textview" />
            </ScrollView>

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_3"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_4"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_5"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_6"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_7"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_8"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_9"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_10"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_11"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_12"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_13"
                style="@style/Textview"
                 />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_14"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_15"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_16"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_17"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_18"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_19"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_20"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_21"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_22"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_23"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_24"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_25"
                style="@style/Textview" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

style.xml

<style name="Textview">
        <item  name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:scrollbars">vertical</item>
        <item name="android:text">@string/text</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textSize">@dimen/textsize12</item>
        <item name="android:padding">@dimen/padding5</item>
        </style>

string.xml

    <string  name="text">sdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfh</string>

dimen.xml

    <dimen name="textsize12">12dip</dimen>
    <dimen name="padding5">5dip</dimen>
    <dimen name="widthsize100">100dp</dimen>



MainActivity.java


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

public class MainActivity extends Activity {
   
    ScrollView mScrollViewParent;
    ScrollView mScrollViewChild;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScrollViewParent=(ScrollView)findViewById(R.id.activity_main_parent_scroll);
        mScrollViewChild=(ScrollView)findViewById(R.id.activity_main_child_scroll);
       
        mScrollViewParent.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                Log.v("A","PARENT TOUCH");
//             findViewById(R.id.child_scroll).getParent().requestDisallowInterceptTouchEvent(false);
                mScrollViewParent.getParent().requestDisallowInterceptTouchEvent(false);
                return false;
            }
        });
        mScrollViewChild.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event)
            {
                Log.v("B","CHILD TOUCH");
               // Disallow the touch request for parent scroll on touch of child view
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}