Advertisemnet

Earn Extra Money At Home. Starting from Now!!!

Monday, July 21, 2014

Relative Layout In Android

Relativelayout is a Viewgroup that shows kid View components in relative positions. The position of a View could be defined as in respect to kin components, (for example, to the left-of or underneath a given component) or in positions with respect to the Relativelayout zone, (for example, adjusted to the bottom, left of focus).

Utilizing Relative Layout we can plan extravagant and excellent GUI.


<?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" >

    <Button
        android:id="@+id/btnButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1"/>

    <Button
        android:id="@+id/btnButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2"
        android:layout_toRightOf="@+id/btnButton1"/>

     <Button
        android:id="@+id/btnButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 3"
        android:layout_below="@+id/btnButton1"/>

     <TextView
         android:id="@+id/textView1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/btnButton3"
         android:layout_marginTop="94dp"
         android:text="User :"
         android:textAppearance="?android:attr/textAppearanceLarge" />

     <EditText
         android:id="@+id/editText1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentRight="true"
         android:layout_alignTop="@+id/textView1"
         android:layout_toRightOf="@+id/btnButton3" />

     <Button
         android:id="@+id/btnSubmit"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentRight="true"
         android:layout_below="@+id/editText1"
         android:text="Submit" />

</RelativeLayout>

Android Advanced Interview Questions And Answers

When to use?
The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

How to trigger?
The Service is triggered calling to method onStartService().
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.

Triggered From
The Service may be triggered from any thread.
The IntentService must be triggered from Main Thread.

Runs On
The Service runs in background but it runs on the Main Thread of the application.
The IntentService runs on a separate worker thread.

Limitations / Drawbacks
The Service may block the Main Thread of the application.
The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.

Make a phone call from your android application

Set permissions in the manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.bubudsadasdas"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon"android:label="@string/app_name">
        <activity android:name=".phonecalls"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
</manifest>

Create a new activity

private void call(String num) {
    try {
        Intent callIntent = new Intent(Intent.ACTION_CALL);
       num="tel:"+num;
        callIntent.setData(Uri.parse(num));
        startActivity(callIntent);
    } catch (ActivityNotFoundException e) {
        Log.e("helloandroid dialing example", "Call failed", e);
    }
}

What happens when you begin a telephone call depends, partially, on the phone system. The number may be inaccurate. The system may be occupied or generally inaccessible. The call could be interfered. Here, on the other hand, you see no failure taking care of rationale, aside from discovering and logging special cases that might be tossed if slip experiences an issue when discovering applications that can prepare Intent articles.

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class phonecalls extends Activity implements OnClickListener {
 /** Called when the activity is first created. */
 private EditText mEtNum;
 private Button mBtnCall;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  mEtNum = (EditText) findViewById(R.id.xEtNumber);
  mBtnCall = (Button) findViewById(R.id.xBtnCall);
  mBtnCall.setOnClickListener(this);
 }

 public void onClick(View v) {
  String num = mEtNum.getText().toString();
  if (num.length() > 5) {
   call(num);
  } else {
   Toast.makeText(getApplicationContext(), " Wrong Number ", 1).show();
  }
 }

 private void call(String num) {
  try {
   Intent callIntent = new Intent(Intent.ACTION_CALL);
   num = "tel:" + num;
   callIntent.setData(Uri.parse(num));
   startActivity(callIntent);
  } catch (ActivityNotFoundException activityException) {
   Log.e("dialing-example", "Call failed", activityException);
  }
 }

}

Send SMS Message In Android

In Android, you can use SmsManager API or device’s Built-in SMS application to send a SMS message.

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

Inside the application put the following code.

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content"); 
sendIntent.setType("vnd.android-dir/mms-sms");

startActivity(sendIntent);

Set the permission inside manifest file

<uses-permission android:name="android.permission.SEND_SMS" />

SmsManager Example

main.xml

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

    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Phone Number : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:phoneNumber="true" >
    </EditText>

    <TextView
        android:id="@+id/textViewSMS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter SMS Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:lines="5"
        android:gravity="top" />

    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />


</LinearLayout>

SendSMSActivity.java

package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendSMSActivity extends Activity {

Button buttonSend;
EditText textPhoneNo;
EditText textSMS;

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

buttonSend = (Button) findViewById(R.id.buttonSend);
textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
textSMS = (EditText) findViewById(R.id.editTextSMS);

// main Logic to Send SMS 

buttonSend.setOnClickListener(new OnClickListener() {


 @Override

public void onClick(View v) {
String phoneNo = textPhoneNo.getText().toString();
String sms = textSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
 }
}
});
}


}

AndroidManifest.xml

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

    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.SEND_SMS" />

    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".SendSMSActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>

YOU'ER DONE!

Thursday, March 29, 2012

Android Chapter 7 : Loading Screen

Hello everyone, welcome to Android Chapter 7 : Loading Screen.
It's mihiran again. In this chapter we are going to look, how to create a simple loading screen in android.

So lets get started.

Loading screen is a very useful feature to give a professional look to your app. In my application I'm using it in several places.. First look at it and how nice it is..

                       Starting                                          Login                                           Log off



In my case I'm using a Thread to handle this. Coding part is very simple. When your are using thread, you must have to surround it by try catch block. Lets see how I have used it in my Starting page.

package com.solution.dude;
public class SolutionDudeActivity extends Activity {
/** Called when
the activity is first created.
**/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ProgressDialog pd.new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("Loading ...");
pd.show();
setContentView(R.layout.main);
new Thread(new Runnable() {
public void run() {
try
{
Thread.sLeep(2000);
pd.dismiss();
}
catch
(InterruptedException e) {
e.printStackTrace();
}).start();

You have to have a runnable thread here. Otherwise it won't work properly. I want to pop up the loading screen for two seconds. That is why I'm using 2000 here.
You can have a object from ProgressDialog class and set the style, message and many more. In here I'm using progressDialog.STYLE_SPINNER. If you use progressDialog.STYLE_HORIZONTAL you'll see it like below.


And that's it.
See you in the next chapter again !
Android

Android Chapter 6 : Passing Values

Hello everyone, welcome back. This is Android Chapter 6 : Passing Values. I'm Mihiran Rupasinghe. As I said earlier today I'm going to show you how you can pass values from one activity to another.

Its very simple.

I think you remember this code.


Button btn.(Button)findViewById(R.id.btnStart);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

Intent intent = new Intent(SolutionDudeActivity.this,Login.class);
startActivity(intent);
});


When I press the START button in my main page, I can move to the Login screen. 

Now think, I want to display my name in welcome screen when I logged in to the application. I'm using putExtra and getExtra methods. All I want to do is modify the code like below.

Intent intent = new Intent(Login.this,Welcome.class);
intent.putExtra("user", name.getText().toString());
startActivity(intent);

You can use "putExtra" method to pass values. First parameter is to identify what you are passing. In here I'm getting the string value of EditTextBox and pass it to welcome screen. I have to do one thing. That is change the code of Welcome.java to catch the passed value.

package com.solution.dude;
import android.app.Activity;
public class Welcome extends Activity {
@Override
protected void 
onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);
setContentView(R.layout.weLcome);
TextView tv.(TextView)findViewById(R.id.user);
tv.setText("Hello " + getIntent().getExtras().getString("user") + ",");

I have a textview called user and Log out button at top of my Welcome.xml.
And the output will be appeared like this.



And that's it.
Next chapter we'll look at how to create a simple loading screen..
See you in the next chapter.

Tuesday, March 27, 2012

Android Chapter 5 : Web Services in Android (WCF) Part 2

Hello everyone, welcome back to Web Services in Android (WCF). This is Android Chapter 4 : Web Services in Android (WCF) Part 2. I'm Mihiran Rupasinghe. In previous chapter http://androidplusiphone.blogspot.com/2012/03/android-chapter-4-web-services-in.html we looked at how to create a web service in ASP.NET with SQL database.  Now lets see how to connect our android application with our web service.

Since I'm using "SoapSerializationEnvelop" to use web services in my app, I must have a special jar file called "ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar". you can download it from here. Go to this link and click "View raw file". Then you can download the file. http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.5.2/ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar?r=498

Then copy the file in to this directory. "C:\Program Files\Android\android-sdk\platforms\android-10". Now you are done with that.

Now go to the android project in eclipse. Right click the project and go to properties. Select "Java Build Path", select "Libraries", click "Add External JARs", select the .jar file and press ok.


Ok. Now you have to give INTERNET permission for your app. To do that, in your manifest file write the uses-permission tag like this at bottom.

</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

 Now I go to Login.java file which is going to access remote database. Import these headers.

 import org.ksoap2.*;
 import org.ksoap2.serialization.*;
 import org.ksoap2.transport.*;


Then I modify the file like below. In here, to connect to the web server I'm using "SoapSerializationEnvelop" and "HttpTransportSE" classes.

public class Login extends Activity {

private static final String SOAP_ACTION = nhttp://tempuri.org/memberValidation";
private static final String METHOD_NAME = nmemberValidationn;
private static final String MAMESPACE = "http://tempuri.orgr;
private static final String URL = nhttp://10.0.2.2:8833/WebService/Service.asmx";

EditText name;
EditText pass;
TextView tv;
 
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.Login);
name.(EditText)findViewById(R.id.txtname);
pass.(EditText)findViewById(R.id.txtpassword);
tv.(TextView)findViewById(R.id.txtError);
Button btnSignIn.(Button)findViewById(R.id.htnsignin);
btnSignIn.setOnClickListener(new OnClickListener() {
public void onClick(View v) 
{
SoapObject Request = new SoapObject(NAMESPACE, METHOD NAME);
Request.addProperty("name" , name.getText().toString());
Request.addProperty("passwd", pass.getText().toString());
SoapSerializationEnvelope soapEnvelop;
soapEnvelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelop.dotNet = true;
soapEnvelop.setOutputSoapObject(Request);
HttpTransportSE htp = new HttpTransportSE(URL);
try{
tv.setText("");
htp.call(SOAPACTION,soapEnvelop);
SoapPrimitive resultString = (SoapPrimitive)soapEnvelop.getResponse();
String id = resultString.toString();
Intent intent = new Intent(Login.this,Welcome.class);
startActivity(intent);
catch 
(Exception e){
tv.setText("Invalid details. Please check again!");
});

This is the most important part.
The four string in above are defined according to your web service web page.

SOAP_ACTION -

METHOD_NAME - your method name (" memberValidation ")

NAMESPACE - "http://tempuri.org/"

URL - replacing 'localhost' by '10.0.2.2' .

And also, I'm using a textview for error message. If user is not valid it gives an error message.

Important :
The first parameter name of Request.addProperty method should be equal to parameter name in memberValidation method. Otherwise it won't work.

If everything is fine user redirect to the welcome page.
Run it in emulator and see how nice it is.
Make sure your web service is running..




Congratulation !
We are done with the web services in our app.

In my next chapter I'll explain how to pass a value from one activity to another.
See you in the next chapter.