Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Wednesday, 14 May 2014

The difference among : SAX Parser,XPath,DOM,XMLPullParser

SAX Parsing is the Best one to implement than DOM, see the difference between these two in the following:
DOM
The Nodes are in the form of Tree Structure Memory: It Occupies more memory, DOM is only preffered in the case of small XML documents Slower at runtime Stored as an objects Programmatically easy to implement Ease of navigation and use.
SAX
Sequence of events It doesn't use any memory preferred for large documents. Faster at runtime, because of the above mentioned point. Objects are to be created. Need to write code for creating objects In SAX Backward navigation is not possible as it sequentially processes the document
So if you have very large files then you should use SAX parser since it will fire events and releasing them ,nothing is stored in memory ,and using SAX parser you can't access element in a random way there is no going back ! , but Dom let you access any part of the xml file since it keeps the whole file/document in memory .
see this article and you can get what you want by reading the Summary.
also check this link to view performance of different xml parser
enter image description here

Thursday, 12 September 2013

Android: Get the x and y values of a View.



@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
TextView tv = (TextView) findViewById(R.id.advancedSearch_text);
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mfrags);
readLocation(mainLayout, tv);
}



private void readLocation(View mainview, View childView) {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int offsetX = displayMetrics.widthPixels - mainview.getMeasuredWidth();
int offsetY = displayMetrics.heightPixels
- mainview.getMeasuredHeight();
int[] locationInWindow = new int[2];
childView.getLocationInWindow(locationInWindow);
int[] locationOnScreen = new int[2];
childView.getLocationOnScreen(locationOnScreen);

System.out.println("vdjvhbjdhvbdjvhbdjvhbdjvh" +"getLocationInWindow() - " +          
                                   locationInWindow[0] + " : "
+ locationInWindow[1] + "getLocationOnScreen() - "
+ locationOnScreen[0] + " : " + locationOnScreen[1]
+ "Offset x: y - " + offsetX + " : " + offsetY);

}

Wednesday, 11 September 2013

Android: get the MIME type from the URL


String name="image.png"
String nameType = URLConnection.guessContentTypeFromName(name);

Android: get the number of lines occupied by the textview dynamically.


@Override
public void run() {
    // TODO Auto-generated method stub
    while(textView.getLineCount() == 0){

    }
    countLine = textView.getLineCount(); 

}

Wednesday, 4 September 2013

Android: Progress Image type loader using progress dialog


 <RelativeLayout
            android:id="@+id/loadingProgressLayout"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <ProgressBar
                style="?android:attr/indeterminateProgressStyle"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_centerInParent="true"
                android:layout_gravity="center"
                android:layout_marginLeft="12dp"
                android:layout_marginRight="12dp"
                android:layout_toLeftOf="@+id/textId" />

            <TextView
                android:id="@+id/textId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="Loading..."
                android:textAppearance="@android:style/TextAppearance.Medium"
                android:textColor="@android:color/black"
                android:visibility="visible" />
        </RelativeLayout>

Tuesday, 3 September 2013

Android: get the Childs of ListView with ListViewId


for (int i = 0; i < listview.getChildCount(); i++) {
RadioButton radioCatOne = (RadioButton) listview.getChildAt(i).findViewById(R.id.radiobuttonId);
}

Friday, 30 August 2013

Android: Get chars to fit in a textview width


int totalCharstoFit= textView.getPaint().breakText(fullString,  0, fullString.length(), 
 true, textView.getWidth(), null);
Now totalCharstoFit contains the exact characters that can be fit into one line. And now you can make a sub string of your full string and append it to the TextView like this,
String subString=fullString.substring(0,totalCharstoFit);
textView.append(substring);
And to calculate the remaining string, you can do this,
fullString=fullString.substring(subString.length(),fullString.length());
Now the full code,
Do this in a while loop,
while(fullstirng.length>0)
{
int totalCharstoFit= textView.getPaint().breakText(fullString,  0, fullString.length(), 
     true, textView.getWidth(), null);
 String subString=fullString.substring(0,totalCharstoFit);
    textView.append(substring);
 fullString=fullString.substring(subString.length(),fullString.length());

}

Android: How to detect device is Android phone or Android tablet?


public static boolean isTablet(Context context) {
    return (context.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK)
            >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

Friday, 23 August 2013

android: Alert Dialog theme


AlertDialog action_btn = new AlertDialog.Builder(MyActivity.this, AlertDialog.THEME_TRADITIONAL).create();

Wednesday, 21 August 2013

Android: Spacing between CheckBox and text


final float scale = this.getResources().getDisplayMetrics().density;
mRememberMyPwdCheckBox.setPadding(mRememberMyPwdCheckBox.getPaddingLeft() + (int)(10.0f * scale + 0.5f),
mRememberMyPwdCheckBox.getPaddingTop(),
mRememberMyPwdCheckBox.getPaddingRight(),
mRememberMyPwdCheckBox.getPaddingBottom());

Tuesday, 16 July 2013

Android: View pager imageslider in android


public class MainActivity extends Activity {

public ViewPager viewPager, viewPagerThumbnails;
public Integer[] pics = { R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher };
public Gallery ga;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new ViewAdapter());

ga = (Gallery) findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));

ga.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Toast.makeText(getBaseContext(),
"You have selected picture " + position,
Toast.LENGTH_SHORT).show();
viewPager.setCurrentItem(position);
}
});

viewPager.setOnPageChangeListener(new OnPageChangeListener() {

@Override
public void onPageSelected(int position) {
ga.setSelection(position);

}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub

}

@Override
public void onPageScrollStateChanged(int arg0) {

}
});

}

private class ViewAdapter extends PagerAdapter {

@Override
public int getCount() {
return 4;
}

@Override
public Object instantiateItem(View v, int position) {
View layout = getLayoutInflater().inflate(R.layout.responsive_item,
null);

((ViewPager) v).addView(layout);
return layout;
}

@Override
public void destroyItem(View v, int position, Object view) {
((ViewPager) v).removeView((View) view);
}

@Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}

}

public class ImageAdapter extends BaseAdapter {

public int imageBackground;

public ImageAdapter(MainActivity mainActivity) {
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
imageBackground = ta.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView iv = new ImageView(getApplicationContext());
iv.setImageResource(pics[position]);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(100, 80));
iv.setBackgroundResource(imageBackground);
return iv;
}

}

}

activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="300dip"
        android:layout_gravity="center_horizontal|center_vertical" />

    <Gallery
        android:id="@+id/Gallery01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom" >
    </Gallery>

</FrameLayout>

responsive_item.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" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="700dp"
        android:layout_height="400dp"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" >
    </ImageView>

    <TextView
        android:id="@+id/text1"
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="21dp"
        android:text="View Port: 1024x768" />

    <ImageView
        android:id="@+id/arrow11"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/text1"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="21dp"
        android:layout_toLeftOf="@+id/imageView1"
        android:src="@drawable/ic_launcher" />

    <ImageView
        android:id="@+id/arrow22"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text122"
        android:layout_toRightOf="@+id/imageView1"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/text122"
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/arrow22"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="44dp"
        android:layout_marginTop="30dp"
        android:text="IPad" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:orientation="vertical" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="port" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="land" />
    </LinearLayout>

</RelativeLayout>

styles.xml
<declare-styleable name="Gallery1">
    <attr name="android:galleryItemBackground"/>
     </declare-styleable>

Friday, 14 June 2013

Android: Toast After Certain Time uisng AlarmManager

 MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

    final static private long ONE_SECOND = 1000;
    final static private long TWENTY_SECONDS = ONE_SECOND * 20;
    PendingIntent pi;
    BroadcastReceiver br;
    AlarmManager am;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setup();
        findViewById(R.id.the_button).setOnClickListener(this);

    }

    private void setup() {
        br = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent i) {
                Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();

            }
        };
        registerReceiver(br, new IntentFilter("com.example.scheduleevent"));
        pi = PendingIntent.getBroadcast(this, 0, new Intent(
                "com.example.scheduleevent"), 0);
        am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
    }

    @Override
    public void onClick(View v) {
        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + TWENTY_SECONDS, pi);

    }

    @Override
    protected void onDestroy() {
        am.cancel(pi);
        unregisterReceiver(br);
        super.onDestroy();
    }

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Alarm Example" />
    <Button
        android:id="@+id/the_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set"/>
</LinearLayout>










Android: AlarmManager for certain Date


Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 32);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
am.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pendingIntent);

Android: Notification for certain time using AlaramManager


AlarmService.java

public class AlarmService extends Activity {

AlarmManager am;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
}

public void setOneTimeAlarm() {

Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (1 * 5000), pendingIntent);
}
//
// public void setRepeatingAlarm() {
// Intent intent = new Intent(this, AlarmReceiver.class);
// PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
// intent, PendingIntent.FLAG_CANCEL_CURRENT);
// am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
// (1 * 1000), pendingIntent);
// }

}

AlarmReceiver.java


public class AlarmReceiver extends BroadcastReceiver {

NotificationManager nm;

@Override
public void onReceive(Context context, Intent intent) {

intent = new Intent(context, AlarmService.class);
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Title";
CharSequence message = "Description...";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
intent, 0);
Notification notif = new Notification(R.drawable.ic_launcher,
"Message...", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}
}

Manifest


 <receiver
            android:name="com.example.alarmmanager.AlarmReceiver"
            android:process=":remote" >
        </receiver>



Thursday, 13 June 2013

android: achartengine BarChart


package com.example.graphtouch;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.view.MotionEvent;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

GridView gridviewloader;
private String[] xAxisBarDisplayBottomValues;
private int[] xAxisTempPositions;
private int[] barValues;
private GraphicalView mChartView;

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

xAxisBarDisplayBottomValues = new String[] { "Jan", "Feb", "Mar", "Apr" };
xAxisTempPositions = new int[] { 0, 1, 2, 3 };
barValues = new int[] { 20, 60, 27, 90 };

final XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setBarWidth(60);
multiRenderer.setXLabels(0);// set X- Interval
multiRenderer.setYLabels(5);// set Y- Interval
multiRenderer.setInScroll(true);
multiRenderer.setShowAxes(true);
multiRenderer.setApplyBackgroundColor(true);
multiRenderer.setBackgroundColor(Color.WHITE);
multiRenderer.setMarginsColor(Color.WHITE);
multiRenderer.setChartTitle("Income vs Expense Chart");
multiRenderer.setYTitle("% to Total Listings");
multiRenderer.setZoomButtonsVisible(false);
multiRenderer.setXLabelsColor(Color.BLACK);
multiRenderer.setYLabelsColor(0, Color.BLACK);
multiRenderer.setAxesColor(Color.parseColor("#949494"));
multiRenderer.setLabelsColor(Color.BLACK);
multiRenderer.setShowGrid(true);
multiRenderer.setYAxisMin(0);
multiRenderer.setYAxisMax(100);
multiRenderer.setXAxisMin(-0.5);
multiRenderer.setXAxisMax(3.5);
// multiRenderer.setBarSpacing(0.0);
multiRenderer.setFitLegend(true);
multiRenderer.setShowLegend(false);
multiRenderer.setZoomEnabled(true, false);
multiRenderer.setPanEnabled(true, false);
multiRenderer.setYLabelsAlign(Align.RIGHT);
multiRenderer.setMargins(new int[] { 45, 45, 45, 45 });
multiRenderer.setClickEnabled(true);

for (int i = 0; i < barValues.length; i++) {
XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
incomeRenderer.setColor(Color.BLACK);
// to give the gradient color to the bars.
incomeRenderer.setFillPoints(true);
incomeRenderer.setLineWidth(2);
incomeRenderer.setGradientEnabled(true);
incomeRenderer.setGradientStart(0, Color.rgb(165, 192, 15));
incomeRenderer.setDisplayChartValues(true);
multiRenderer.addXTextLabel(xAxisTempPositions[i],
xAxisBarDisplayBottomValues[i]);
multiRenderer.addSeriesRenderer(incomeRenderer);
}

XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

for (int i = 0; i < barValues.length; i++) {
XYSeries incomeSeries1 = new XYSeries("Income1");
incomeSeries1.add(xAxisTempPositions[i], barValues[i]);
dataset.addSeries(incomeSeries1);
}

LinearLayout rl = (LinearLayout) findViewById(R.id.icon_image);
mChartView = ChartFactory.getBarChartView(this, dataset, multiRenderer,
Type.STACKED);
rl.addView(mChartView);

}

}





Android: Send email in android using JavaMail API with smtp but without SSL

Add Jars

1)activation.jar
2)additionnal.jar
3)mail.jar

Mail.java


public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;

private String[] _to;
private String _from;

private String _port;
private String _sport;

private String _host;

private String _subject;
private String _body;

private boolean _auth;

private boolean _debuggable;

private Multipart _multipart;

public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port

_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body

_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on

_multipart = new MimeMultipart();

// There is something wrong with MailCap, javamail can not find a
// handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap
.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}

public Mail(String user, String pass) {
this();

_user = user;
_pass = pass;
}

public boolean send() throws Exception {
Properties props = _setProperties();

if (!_user.equals("") && !_pass.equals("") && _to.length > 0
&& !_from.equals("") && !_subject.equals("")
&& !_body.equals("")) {

Session session = Session.getInstance(props, this);
DataHandler handler = new DataHandler(new ByteArrayDataSource(
_body.getBytes(), "text/plain"));
MimeMessage msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(_from));
msg.setDataHandler(handler);
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

msg.setSubject(_subject);
msg.setSentDate(new Date());

// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);

// Put parts in message
msg.setContent(_multipart);

// send email
Transport.send(msg);
Log.v("mas", "Email was  send");
return true;
} else {
Log.v("mas", "Email was  not send");
return false;

}
}

public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;

public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}

public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}

public void setType(String type) {
this.type = type;
}

public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}

public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}

public String getName() {
return "ByteArrayDataSource";
}

public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}

private Properties _setProperties() {
Properties props = new Properties();

props.put("mail.smtp.host", _host);

if (_debuggable) {
props.put("mail.debug", "true");
}

if (_auth) {
props.put("mail.smtp.auth", "true");
}

props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

return props;
}

// the getters and setters
public String getBody() {
return _body;
}

public void setBody(String _body) {
this._body = _body;
}

public void setTo(String[] toArr) {
// TODO Auto-generated method stub
this._to = toArr;
}

public void setFrom(String string) {
// TODO Auto-generated method stub
this._from = string;
}

public void setSubject(String string) {
// TODO Auto-generated method stub
this._subject = string;
}

// more of the getters and setters …..
}



in Acitivity


Mail m = new Mail("abc@gmail.com", "XXXXXX");

String[] toArr = { "vd@gmail.com",
"vs@vsplash.net" };
m.setTo(toArr);
m.setFrom("abc");
m.setSubject("Subject");
m.setBody("Message body...");

try {
boolean i = m.send();
if (i == true) {
Toast.makeText(getApplicationContext(), "Email was sent successfully ", Toast.LENGTH_SHORT)
.show();

} else {
Toast.makeText(getApplicationContext(), "Email was not sent successfully ",
Toast.LENGTH_SHORT).show();

}

} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

Friday, 7 June 2013

Android: achartengine bar chart.



 mMonth = new String[] { "Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };



LayoutInflater li = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.grid_item, null);

LinearLayout rl = (LinearLayout) v.findViewById(R.id.icon_image);

int[] x = { 0, 1, 2, 3, 4, 5, 6, 7 };
int[] income = { 2000, 2500, 2700, 3000, 2800, 3500, 3700, 3800 };

XYSeries incomeSeries = new XYSeries("Income");
// Creating an XYSeries for Income

// Adding data to Income Series
for (int i = 0; i < x.length; i++) {
incomeSeries.add(i, income[i]);

}

// Creating a dataset to hold each series
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Income Series to the dataset
dataset.addSeries(incomeSeries);
// Adding Expense Series to dataset

// Creating XYSeriesRenderer to customize incomeSeries
XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
incomeRenderer.setColor(Color.rgb(130, 130, 230));
incomeRenderer.setFillPoints(true);
incomeRenderer.setLineWidth(2);
incomeRenderer.setDisplayChartValues(true);

// Creating a XYMultipleSeriesRenderer to customize the whole chart
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setXLabels(0);
multiRenderer.setInScroll(true);
multiRenderer.setShowAxes(false);
multiRenderer.setApplyBackgroundColor(true);
multiRenderer.setBackgroundColor(Color.WHITE);
multiRenderer.setMarginsColor(Color.WHITE);
multiRenderer.setChartTitle("Income vs Expense Chart");
multiRenderer.setXTitle("Year 2012");
multiRenderer.setYTitle("Amount in Dollars");
multiRenderer.setZoomButtonsVisible(false);
multiRenderer.setXLabelsColor(Color.BLACK);
multiRenderer.setYLabelsColor(0, Color.BLACK);
multiRenderer.setAxesColor(Color.BLACK);
multiRenderer.setLabelsColor(Color.BLACK);

// for bar spacing
multiRenderer.setBarSpacing(1.0);

for (int i = 0; i < x.length; i++) {
multiRenderer.addXTextLabel(i, months[i]);
}

multiRenderer.addSeriesRenderer(incomeRenderer);

mChartView = ChartFactory.getBarChartView(context, dataset,
multiRenderer, null);
rl.addView(mChartView);

Tuesday, 28 May 2013

Android: iPhone style cancel and done buttons for android

drawable/cancelbutton.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 
    <item>
        <shape>
            <gradient
                android:startColor="#b1b5ba"
                android:centerColor="#838991"
                android:endColor="#6b727d"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#4b4d4f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="6dp"
                android:right="10dp"
                android:bottom="6dp" />
        </shape>
    </item>
</selector>


drawable/done.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 
    <item>
        <shape>
            <gradient
                android:startColor="#8aaceb"
                android:centerColor="#4c80d9"
                android:endColor="#2a66d4"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#5a6d8a" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="6dp"
                android:right="10dp"
                android:bottom="6dp" />
        </shape>
    </item>
</selector>

Tuesday, 21 May 2013

Android: Drawable with rounded corners / rounded corners only top


<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/white" />
    <stroke android:width="1dp" android:color="@color/light_gray" />
    <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
    <corners android:radius="6dp" />
</shape>
 top corners:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/white" />
    <stroke android:width="1dp" android:color="@color/light_gray" />
    <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
   <corners android:topLeftRadius="6dp" android:topRightRadius="6dp" android:bottomLeftRadius="0       .1dp" android:bottomRightRadius="0.1dp"/>

</shape>