Tuesday, 4 February 2014

Google map

1)Create Activity ContactUsActivity.java
import android.os.Bundle;

import com.google.android.gms.common.GooglePlayServicesUtil;
import com.rws.ohmsantihyoga.R;
import com.rwsutil.masterview.MyBaseActivity;

public class ContactUsActivity extends MyBaseActivity {
private ContactContentFrag mContent;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Contact Us");
setContentView(R.layout.base_layout);
hideMenuIcon();
GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
mContent = new ContactContentFrag();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mContent).commit();
getSlidingMenu().setSlidingEnabled(false);
}
}
2)ContactContentFrag.java
===================

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

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.rws.localwsutils.AppUtil;
import com.rws.ohmsantihyoga.R;
import com.rwsutil.masterview.GroupPrefrences.ContactPref;
import com.rwsutil.masterview.MyBaseFragment;
import com.rwsutil.masterview.WebServiceUrl;

public class ContactContentFrag extends MyBaseFragment implements
OnClickListener, WebServiceUrl, ContactPref {

private int contact_info_responcCode = 900;

private TextView txtTitle, txtAddress;
private Button abtMapType;
private EditText edtName, edtEmail, edtMessage;
private ImageView abtRefresh;
private CheckBox chkSendcopy;
private Button btnSubmit;
private GoogleMap mGooleMap;
private double mlat = 0;
private double mlng = 0;
private String mapTitle = "Ohm Santih", map_maptype = "";

@Override
public void onStop() {
putPref(ABT_NAME, edtName.getText().toString());
putPref(ABT_EMAIL, edtEmail.getText().toString());
putPref(ABT_MSG, edtMessage.getText().toString());
putPref(ABT_IS_CHECKED, chkSendcopy.isChecked());
super.onStop();
}

@Override
public void onStart() {
edtName.setText(getPrefString(ABT_NAME));
edtEmail.setText(getPrefString(ABT_EMAIL));
edtMessage.setText(getPrefString(ABT_MSG));
chkSendcopy.setChecked(getPrefBoolean(ABT_IS_CHECKED));
super.onStart();
}

private void clearPrefrenc() {
edtName.setText("");
edtEmail.setText("");
edtMessage.setText("");
chkSendcopy.setChecked(false);
putPref(ABT_NAME, "");
putPref(ABT_EMAIL, "");
putPref(ABT_MSG, "");
putPref(ABT_IS_CHECKED, false);
}

// [{"bStatus":"0","sMessage":"Contact Info fetch Successfully.","sData":{""
// +
// "contact_number":"9336 2556 (available from 9 am to 9 pm only)","" +
// "map_callout_text":"OhmSantih Yoga Pte Ltd\r\n",
// "title":" Ltd","" +
// "contactform_map_coords":"1.30065236072045, 103.85920733213425",
// "address":"10A, Ha<br \/>\r\nEmail us at : " +
// "enquiries@abc.com <br \/>\r\n",
// "contact_fax":"","map_maptype":"G_SATELLITE_MAP"}}]
//

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.contact_us_frag, null);

txtTitle = (TextView) v.findViewById(R.id.abtTitle);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/Chalet Comprime Cologne Sixty.otf");
txtTitle.setTypeface(font);
txtAddress = (TextView) v.findViewById(R.id.abtAddress);

abtMapType = (Button) v.findViewById(R.id.abtMapType);
abtMapType.setOnClickListener(this);

edtName = (EditText) v.findViewById(R.id.abtName);
observeText(edtName);
edtEmail = (EditText) v.findViewById(R.id.abtEmail);
observeText(edtEmail);
edtMessage = (EditText) v.findViewById(R.id.abtMessage);
observeText(edtMessage);

chkSendcopy = (CheckBox) v.findViewById(R.id.abtCheckMail);
abtRefresh = (ImageView) v.findViewById(R.id.abtRefresh);
abtRefresh.setOnClickListener(this);

btnSubmit = (Button) v.findViewById(R.id.abtSubmit);
btnSubmit.setOnClickListener(this);
mGooleMap = ((SupportMapFragment) getActivity()
.getSupportFragmentManager().findFragmentById(R.id.abtmapfragment)).getMap();
mGooleMap.setMyLocationEnabled(true);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mGooleMap.animateCamera(zoom);
return v;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callWsPost(CONTACT_INFO_URL, new JSONObject(), contact_info_responcCode);
}

@Override
public void onResult(int mResponceCode, JSONArray mResponce) {
try {
JSONObject mJsonObject = mResponce.getJSONObject(0);
if (mResponceCode == contact_info_responcCode) {
onContactInfoResponce(mJsonObject);
} else if (mResponceCode == R.id.abtSubmit&& showMessage(mJsonObject)) 
clearPrefrenc();
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void onContactInfoResponce(JSONObject mJsonObject) {
try {
JSONObject mData = mJsonObject.getJSONObject("sData");
txtTitle.setText(mapTitle = mData.getString("title"));
map_maptype = mData.getString("map_maptype");

String address = Html.fromHtml(mData.getString("address"))
.toString();
address += "Tel:" + mData.getString("contact_number");
txtAddress.setText(address + "\n");
// address = "\nemail : enquiries@ohmsantih.com";
txtAddress
.append(Html
.fromHtml("Email : <a href=\"enquiries@abc.com\">enquiries@abc.com</a>"));
txtAddress.setMovementMethod(LinkMovementMethod.getInstance());

String[] latlng = mData.getString("contactform_map_coords").split(
",");
mlat = Double.parseDouble(latlng[0]);
mlng = Double.parseDouble(latlng[1]);
refreshMap();
} catch (Exception e) {
e.printStackTrace();
parseError();
}
}

private void refreshMap() {
if (mlat != 0 && mlng != 0 && mGooleMap != null) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(
mlat, mlng));
if (selectedType != -1)
mGooleMap.setMapType(selectedType);
else if (TextUtils.equals(map_maptype, "G_NORMAL_MAP"))
mGooleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
else if (TextUtils.equals(map_maptype, "G_SATELLITE_MAP"))
mGooleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
else if (TextUtils.equals(map_maptype, "G_HYBRID_MAP"))
mGooleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
else if (TextUtils.equals(map_maptype, "G_PHYSICAL_MAP"))
mGooleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
else
mGooleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
mGooleMap.addMarker(new MarkerOptions().position(
new LatLng(mlat, mlng)).title(mapTitle));
mGooleMap.moveCamera(center);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mGooleMap.animateCamera(zoom);
}
}

@Override
public void onResume() {
super.onResume();
clearPrefrenc();
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.abtSubmit:
JSONObject validResponce = getValidResponce();
if (validResponce != null) {
clearPrefrenc();
callWsPost(CONTACT_US_URL, validResponce, R.id.abtSubmit)
.setCacheEnable(false);
}
break;
case R.id.abtRefresh:
refreshMap();
break;
case R.id.abtMapType:
showMapTypeDaiog();
break;
}
}

private int selectedType = -1;

public void showMapTypeDaiog() {
// GoogleMap.MAP_TYPE_NONE,
final int[] mapType = new int[] { GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_SATELLITE, GoogleMap.MAP_TYPE_TERRAIN,
GoogleMap.MAP_TYPE_HYBRID, };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Map Type").setItems(
// "None",
new String[] { "Normal", "Satellite", "Terrain", "Hybrid", },
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (mGooleMap != null)
mGooleMap.setMapType(selectedType = mapType[which]);
}
});
builder.create().show();
}

public JSONObject getValidResponce() {
String name = edtName.getText().toString();
String email = edtEmail.getText().toString();
String message = edtMessage.getText().toString();

if (TextUtils.isEmpty(name)) {
edtName.requestFocus();
edtName.setError("Please Enter Valid Name");
return null;
} else if (!AppUtil.isValidEmail(email)) {
edtEmail.requestFocus();
edtEmail.setError("Please Enter Valid Email");
return null;
} else if (TextUtils.isEmpty(message)) {
edtMessage.requestFocus();
edtMessage.setError("Please Enter Message");
return null;
} else {
JSONObject mJsonObject = new JSONObject();
try {
mJsonObject.put("name", name);
mJsonObject.put("email", email);
mJsonObject.put("message", message);
mJsonObject
.put("sendcopy", chkSendcopy.isChecked() ? "0" : "1");
return mJsonObject;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

public void clearData() {
edtName.setText("");
edtEmail.setText("");
edtMessage.setText("");
}
}
3)MyBaseFragment.java
=====================

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

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

import com.rws.localwsutils.AppUtil;
import com.rws.wsutil.AsyncData;
import com.rws.wsutil.AsyncData.PostType;
import com.rws.wsutil.PostAndGetData;
import com.rws.wsutil.PostAndGetData.onJsonResult;

public abstract class MyBaseFragment extends AppPreferenceFrag implements
onJsonResult {

public abstract void onResult(int mResponceCode, JSONArray mResponce);

public AsyncData callWsPost(String BaseUrl, JSONObject mJsonData) {
return callWsPost(BaseUrl, mJsonData, (int) System.currentTimeMillis());
}

public AsyncData callWsPost(String BaseUrl, JSONObject mJsonData,
int responceCode) {
PostAndGetData mAndGetData = new PostAndGetData(getActivity(), this);
AsyncData mAsyncData = new AsyncData(PostType.POST, true, responceCode);
mAsyncData.setBASEURL(BaseUrl);
mAsyncData.setParams(mJsonData);
mAsyncData.setRootParam("webdata");
mAsyncData.setCacheEnable(true);
mAndGetData.execute(true, mAsyncData);
return mAsyncData;
}

public AsyncData callWsPost(String BaseUrl, JSONObject mJsonData,
onJsonResult onJsonResult) {
PostAndGetData mAndGetData = new PostAndGetData(getActivity(),
onJsonResult);
AsyncData mAsyncData = new AsyncData(PostType.POST, true);
mAsyncData.setBASEURL(BaseUrl);
mAsyncData.setParams(mJsonData);
mAsyncData.setRootParam("webdata");
mAsyncData.setCacheEnable(true);
mAndGetData.execute(true, mAsyncData);
return mAsyncData;

}

public boolean isSuccess(JSONObject mJsonObject) {
String message = "web responce error";
try {
message = mJsonObject.getString("sMessage");
if (mJsonObject.has("bStatus")
&& TextUtils.equals(mJsonObject.getString("bStatus"), "0")) {
return true;
} else
return alertMessage(message);
} catch (JSONException e) {
return alertMessage(message);
}
}

public boolean showMessage(JSONObject mJsonObject) {
String message = "web responce error";
try {
message = mJsonObject.getString("sMessage");
if (mJsonObject.has("bStatus")
&& TextUtils.equals(mJsonObject.getString("bStatus"), "0")) {
return !alertMessage(message);
} else
return alertMessage(message);
} catch (JSONException e) {
return alertMessage(message);
}
}

public boolean alertMessage(String message) {
AppUtil mAppUtil = AppUtil.getInstance();
mAppUtil.showAlertDialog(getActivity(), message);
return false;
}

public void parseError() {
Toast.makeText(getActivity(), "Responce Parse Error", Toast.LENGTH_LONG)
.show();
}

public void toast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}

public void observeText(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (!editText.getText().toString().equals("")) {
editText.setError(null);
}
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}

@Override
public void afterTextChanged(Editable s) {

}
});
}
}
4)AppPreferenceFrag.java
=====================

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;

public class AppPreferenceFrag extends Fragment {

private SharedPreferences preferences;

@Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
preferences = getActivity().getSharedPreferences("AppPref",
Context.MODE_MULTI_PROCESS);
}

public void putPref(String KEY, String VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(KEY, VAL);
editor.commit();
}

public void putPref(String KEY, int VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(KEY, VAL);
editor.commit();
}

public void putPref(String KEY, boolean VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(KEY, VAL);
editor.commit();
}

public String getPrefString(String KEY) {
return preferences.getString(KEY, "");
}

public String getPrefString(String KEY, String _default) {
return preferences.getString(KEY, _default);
}

public int getPrefInt(String KEY) {
return preferences.getInt(KEY, 0);
}

public int getPrefInt(String KEY, int _default) {
return preferences.getInt(KEY, _default);
}

public boolean getPrefBoolean(String KEY) {
return preferences.getBoolean(KEY, false);
}

public boolean getPrefBoolean(String KEY, boolean _default) {
return preferences.getBoolean(KEY, _default);
}
}
6)base_layout.xml
=============
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_frame"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="-4dp"
    android:background="@drawable/aboutus_bg" >

</FrameLayout>
7)contact_us_frag
===========
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/aboutus_bg"
    android:orientation="vertical"
    android:paddingBottom="8dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp" >

    <RelativeLayout
        android:id="@+id/mapLayour"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.4" >

        <fragment
            android:id="@+id/abtmapfragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            class="com.google.android.gms.maps.SupportMapFragment" />

        <ImageView
            android:id="@+id/abtRefresh"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginTop="7dp"
            android:background="@drawable/refresh_map"
            android:contentDescription="@string/app_name"
            android:singleLine="true"
            android:textColor="#945C44" />

        <Button
            android:id="@+id/abtMapType"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_below="@+id/abtRefresh"
            android:layout_marginBottom="30dp"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/mape_type"
            android:padding="4dp"
            android:text="@string/type" />
    </RelativeLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="@dimen/val_10"
        android:layout_weight="0.6" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:ignore="UselessLeaf" >

            <TextView
                android:id="@+id/abtTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/brn_dark"
                android:textSize="@dimen/t_val_28"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/abtAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:textColor="@color/brn_dark"
                android:textSize="18sp" />

            <EditText
                android:id="@+id/abtName"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="7dp"
                android:hint="@string/name"
                android:singleLine="true"
                android:textColor="@color/brn_dark" />

            <EditText
                android:id="@+id/abtEmail"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="7dp"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:singleLine="true"
                android:textColor="@color/brn_dark" />

            <EditText
                android:id="@+id/abtMessage"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginTop="7dp"
                android:gravity="bottom"
                android:hint="@string/message"
                android:inputType="textMultiLine"
                android:minLines="3"
                android:singleLine="false"
                android:textColor="@color/brn_dark"
                android:verticalScrollbarPosition="right" />

            <CheckBox
                android:id="@+id/abtCheckMail"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="7dp"
                android:checked="false"
                android:minLines="6"
                android:text="@string/send_a_copy_of_this_email_to_yourself"
                android:textColor="@color/brn_dark" />

            <Button
                android:id="@+id/abtSubmit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:background="@drawable/submit_btn"
                android:padding="@dimen/val_10" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>
9)MyBaseActivity.java
====================

import org.json.JSONArray;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.rws.ohmsantihyoga.R;

public class MyBaseActivity extends MyBaseActivityWS implements OnClickListener {

private CharSequence title = "Title";

public void setTitle(CharSequence title) {
this.title = title;
if (txtTitle != null)
txtTitle.setText(title);
}
public TextView txtTitle;
public ImageView menuIcon, homeIcon;
public ImageView imgLeftDivider, imgRightDivider;

@Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
setBehindContentView(R.layout.menu_frame);
getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.headder);
getActionBar().setBackgroundDrawable(new ColorDrawable(R.color.brn_lite));
setSlidingActionBarEnabled(false);
SlidingMenu sm = getSlidingMenu();
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindScrollScale(0.75f);
sm.setFadeDegree(0.25f);
sm.setBackgroundColor(getResources().getColor(R.color.brn_lite));
}

public void hideMenuIcon() {
menuIcon.setVisibility(View.INVISIBLE);
imgLeftDivider.setVisibility(View.INVISIBLE);
}

public void hideHomeIcon() {
homeIcon.setVisibility(View.INVISIBLE);
imgRightDivider.setVisibility(View.INVISIBLE);
}

@Override
public void setContentView(int id) {
super.setContentView(id);
txtTitle = (TextView) findViewById(R.id.headderTitle);
txtTitle.setText(title);

menuIcon = (ImageView) findViewById(R.id.iconMenu);
menuIcon.setOnClickListener(this);

homeIcon = (ImageView) findViewById(R.id.iconHome);
homeIcon.setOnClickListener(this);

imgLeftDivider = (ImageView) findViewById(R.id.imgLeftDivider);
imgRightDivider = (ImageView) findViewById(R.id.imgRightDivider);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iconMenu:
toggle();
break;
case R.id.iconHome:
finish();
break;
default:
break;
}
}

@Override
public void onResult(int mResponceCode, JSONArray mResponce) {
}
}

Wednesday, 29 June 2011

About android3

Android Shell Commands

Here you can find the available command set in the shell by typing this at the android shell prompt:

dumpcrash, am, dumpstate, input, itr, monkey, pm, svc, ssltest,
debuggerd, dhcpcd, hostapd_cli, fillup, linker, logwrapper, telnetd, iftop, mkdosfs, mount,
mv, notify, netstat, printenv, reboot, ps, renice, rm, rmdir,rmmod, sendevent, schedtop,
ping, sh, hciattach, sdptool, logcat, servicemanager, dbus-daemon, debug_tool, flash_image, installd,
dvz, hostapd, htclogkernel, mountd, qemud, radiooptions, toolbox, hcid,
route, setprop, sleep, setconsole, smd, stop, top, start, umount,
vmstat, wipe, watchprops, sync, netcfg, Chmod, date, dd, cmp, cat, dmesg, df,
getevent, getprop, hd, id, ifconfig, insmod, ioctl, kill,
ln, log, lsmod, ls, mkdir, dumpsys, service, playmp3, sdutil,
rild, dalvikvm, dexopt, surfaceflinger, app_process, mediaserver, system_server,

Sunday, May 22, 2011

Combine two images in android java


In this blog we are combine two images and we have two images stored locally on an SD card or drawble folder in android.

Steps:

Read the image from Source
InputStream istream = context.getResources().openRawResource(R.drawable.img1);
try {
image1 = BitmapFactory.decodeStream(istream);
istream = context.getResources().openRawResource(R.drawable.img2);
image2 = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch (IOException e) {
}
}

Define the Image property
int width = 0, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}

Create your target Bitmap,
Bitmap combinedImages = Bitmap.createBitmap(width * 2, height, Bitmap.Config.ARGB_8888);

Create a Canvas for it,
Canvas comboImage = new Canvas(combinedImages);
Use Canvas.drawBitmap to blit each source bitmap into your target bitmap
comboImage.drawBitmap(image1, 0f, 0f, null);
comboImage.drawBitmap(image2, 0f, image1.getHeight()+1, null);

Example:
public Bitmap combineImages(Context context, int img1, int img2) {
// Bitmap[] mBitmap = new Bitmap[6];
Bitmap image1, image2;

InputStream istream = context.getResources().openRawResource(img1);
try {
image1 = BitmapFactory.decodeStream(istream);
istream = context.getResources().openRawResource(img2);
image2 = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch (IOException e) {
}
}
int width = 0, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
Bitmap combinedImages = null;
combinedImages = Bitmap
.createBitmap(width * 2, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(combinedImages);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight()+1, null);
return cs;
}

Sunday, May 15, 2011

Scrollable Text View in andriod -2


This article helps to making Scrollable TextView using TextView with dispatchKeyEvent

we can make a scrollable textview while implement the setMovementMethod and dispatchKeyEvent.

1. private TextView mTextView;

2. Set the Required data in the TextView
mTextView = (TextView) findViewById(R.id.textView1);
mTextView.setText("this is for testing \nthis is for testing \nthis is for testing
\nthis is for testing \nthis is for testing \nthis is for testing \n");

3. mTextView.setMovementMethod(new ScrollingMovementMethod(){.....})

4. Override the methods in ScrollingMovementMethod

new ScrollingMovementMethod() {
public void onTakeFocus(TextView widget, Spannable text, int dir) {}
@Override
public boolean onKeyDown(TextView widget, Spannable buffer,
int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
down(widget, buffer);
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
up(widget, buffer);
}
return true;
default:
return super.onKeyDown(widget, buffer, keyCode, event);
}
}

private int getScrollAmount(TextView widget) {
final int visibleLineCount = (int) ((1f * widget.getHeight()) / widget
.getLineHeight());
int scrollAmount = visibleLineCount - 1;
if (scrollAmount < 1) {
scrollAmount = 1;
}
return scrollAmount;
}
}


5. Call the dispatch method in your code
mTextView.dispatchKeyEvent(event);


SAMPLE

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

private TextView mTextView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.textView1);
mTextView
.setText("this is for testing \nthis is for testing \nthis is for testing \nthis is for testing \nthis is for testing \nthis is for testing \n");

mTextView.setMovementMethod(new ScrollingMovementMethod() {
public void onTakeFocus(TextView widget, Spannable text, int dir) {

}

@Override
public boolean onKeyDown(TextView widget, Spannable buffer,
int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
down(widget, buffer);
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
up(widget, buffer);
}
return true;
default:
return super.onKeyDown(widget, buffer, keyCode, event);
}
}
private int getScrollAmount(TextView widget) {
final int visibleLineCount = (int) ((1f * widget.getHeight()) / widget
.getLineHeight());
int scrollAmount = visibleLineCount - 1;
if (scrollAmount < 1) {
scrollAmount = 1;
}
return scrollAmount;
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:

return true;
case KeyEvent.KEYCODE_DPAD_UP:
mTextView.dispatchKeyEvent(event);
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
}

Scrollable Text View in andriod


This article helps to making Scrollable TextView in Android.

We can do it two ways. 1.Create a TextView inside the ScrollView and 2. TextView with dispatch Events.


Create a TextView inside the ScrollView
< ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:fillViewport="true">
< LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent">
< TextView android:text="@+id/TextView01"
android:id="@+id/mTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent">< / TextView>

< / LinearLayout>
< / ScrollView>

Activity Implementation
mTextView = (TextView) findViewById(R.id.logTextView);
mTextView .setText("");
mTextView .setMovementMethod(ScrollingMovementMethod.getInstance());

Thursday, May 12, 2011

How to Obfuscated Android Code

Obfuscated code is source or machine code that has been made difficult to understand for humans. Programmers may deliberately obfuscate code to conceal its purpose or its logic to prevent tampering, deter reverse engineering, or as a puzzle or recreational challenge for someone reading the source code.
Programs known as obfuscators transform readable code into obfuscated code using various techniques. Code obfuscation is different in essence from hardware obfuscation, where description and/or structure of a circuit is modified to hide its functionality.


The following steps to describe the android obfuscation


1) Setup the obfuscated environment Download the follwing file before you starts
ProGuard
ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. Finally, it preverifies the processed code for Java 6 or for Java Micro Edition.

Download files from internet
  • add-proguard-release.xml
  • procfg.txt
1) To update an existing Android project, open a command-line and navigate to the tools/ directory of your SDK. Now run:
android update project --name --target --path
2) So, now you have a signed build from the command line, but still no obfuscated build.
To make things easy, you’re going to want to get two helper files:

add-proguard-release.xml and procfg.txt
Copy these files into your root directory (where the build.xml file found).
3) To add Proguard to your build, you first need to edit your local properties file to add the location of the directory that Proguard is installed in:

proguard.dir=/Directory/Proguard/Is/Installed/In
3) Finally... you need to add our script to your build file and have it override a few targets. To do this, we use the XML “entity” construct. At the top of your build.xml file, add an entity that references our script file:
]
>
4) By default ADT creates a proguard.cfg file with every new project, so if you have an existing project just copy it over from a new dummy project. The next step is to enable ProGuard, you do this by adding the following to your default.properties file:
proguard.config=proguard.cfg
(assuming proguard.cfg is the ProGuard configuration file created for you, or copied from a new project, into the project root folder.)

Thursday, April 28, 2011

Read Text From the Raw Content in Resource Folder.

You can store the raw content in the raw folder and read using the below method..
1. Create a file in and Raw content
2. Create Method called readTextResource() in the util class
3. Use the below code to read the data
StringBuffer strBuffer = new StringBuffer();
InputStream inputStream = null;
try {
inputStream = owner.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String str = br.readLine();
while (str != null) {
strBuffer.append(str);
str = br.readLine();
}
} catch (IOException e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
4. Return the StringBuffer value.
5. If you need a html format, you can use the html util class
Html.fromHtml(text); - It returns Spanned instance.

Sample Code
---------->
public class MainActivity extends Activity {

private Spanned mText = null;
private TextView mTextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.sampleText);
if (mText == null) {
String text = readTextResource(R.raw.license, this);
mText = Html.fromHtml(text);
}
mTextView.setText(mText);
}
public String readTextResource(int resourceId, Activity owner) {
StringBuffer strBuffer = new StringBuffer();
InputStream inputStream = null;
try {
inputStream = owner.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String str = br.readLine();
while (str != null) {
strBuffer.append(str);
str = br.readLine();
}
} catch (IOException e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
return strBuffer.toString();
}
}

Monday, April 25, 2011

Android Tips - Using Layout Param

Layout Param is used to change the layout properties. You can create a layout instance and assign to required view.

LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

Sample Code

LinearLayout.LayoutParams mLayoutParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button mButton = new Button(this);
mButton.setLayoutParams(layoutParam);

The above code works fine but this is not a current solution. It should like the below code

Button mButton = new Button(this);
ViewGroup.LayoutParam mLayoutParam= mButton.getLayoutParams();
mLayoutParam.height = ViewGroup.LayoutParams.FILL_PARENT


Thanks to Ashok , I have done the mistake and corrected me

Android Window Leak

The WindowLeaked exception in the log usually happens when you have some sort of async task that is finishing after the activity that began it is destroyed.
Solution for the above issue, we can dismiss the progress dialog before finish the activity.


Issue :

Activity com.sample.ViewLeakIssueActivity has leaked window com.android.internal.policy.impl.TvWindow$DecorView@6bc30788 that was originally added here
E/WindowManager( 1687): at android.view.ViewRoot.(ViewRoot.java:230)
E/WindowManager( 1687): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
-----

Sample Leak Issue
public class ViewLeakIssueActivity extends Activity {
volatile ProgressDialog pd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pd = ProgressDialog.show(ViewLeakIssueActivity.this, "", "test...", true);

new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("@@@@@@@@@@@"+ViewLeakIssueActivity.this+pd.isShowing());

pd.dismiss();
}
}.start();

finish();

}

}

Solution for the above issue, we can dismiss the progress dialog before finish the activity.

@Override
public void finish() {
if(pd.isShowing()){
pd.dismiss();
}
super.finish();
}


Thursday, March 31, 2011

Android Versions...