Pages

Thursday, 20 November 2014

SlidingMenu in android

To create a sliding Menu in android:

I have used two library to create this project.
Please reference below link before going to implement your project.

https://github.com/jfeinstein10/SlidingMenu
https://github.com/umano/AndroidSlidingUpPanel

For complete code

MainActivity.java

public class MainActivity extends SlidingFragmentActivity {

private SlidingUpPanelLayout mLayout;
TextView first, second,firstLeft,secondLeft,firstRight,secondRight;

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

// Declaring Left and right SlidingMenu
final SlidingMenu slidingMenu = getSlidingMenu();
slidingMenu.setSecondaryMenu(R.layout.right);
slidingMenu.setMode(SlidingMenu.LEFT_RIGHT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
int height = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 100, getResources()
.getDisplayMetrics());
slidingMenu.setBehindOffset(height);

// For perfect SlidingUpLayout
mLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
mLayout.setOverlayed(true);

// You can write your own code here.
first = (TextView) findViewById(R.id.first_tv);
second = (TextView) findViewById(R.id.second_tv);
firstLeft= (TextView) findViewById(R.id.first_tv_left);
secondLeft= (TextView) findViewById(R.id.second_tv_left);
firstRight= (TextView) findViewById(R.id.first_tv_right);
secondRight= (TextView) findViewById(R.id.second_tv_right);

first.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "first",
Toast.LENGTH_LONG).show();
}
});

second.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "second",
Toast.LENGTH_LONG).show();
}
});

firstLeft.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "firstLeft",
Toast.LENGTH_LONG).show();
}
});

secondLeft.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "secondLeft",
Toast.LENGTH_LONG).show();
}
});

firstRight.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "firstRight",
Toast.LENGTH_LONG).show();
}
});

secondRight.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "secondRight",
Toast.LENGTH_LONG).show();
}
});
}
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <com.sothree.slidinguppanel.SlidingUpPanelLayout
        xmlns:sothree="http://schemas.android.com/apk/res-auto"
        android:id="@+id/sliding_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        sothree:dragView="@+id/dragView"
        sothree:panelHeight="25dp"
        sothree:shadowHeight="0dp" >

        <!-- MAIN CONTENT -->

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="match_parent" >

            <FrameLayout
                android:id="@+id/transaction"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </RelativeLayout>
        <!-- SLIDING LAYOUT -->

        <RelativeLayout
            android:id="@+id/dragView"
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:clickable="true"
            android:focusable="false"
            android:orientation="vertical" >

            <RelativeLayout
                android:id="@+id/first"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#ffffff" >

                <TextView
                    android:id="@+id/first_tv"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="15dp"
                    android:gravity="center_vertical"
                    android:text="First"
                    android:textColor="#128C79"
                    android:textSize="20sp"
                    android:textStyle="normal" />
            </RelativeLayout>

            <View
                android:id="@+id/line"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_below="@+id/first"
                android:background="#128C79" />

            <RelativeLayout
                android:id="@+id/second"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/line"
                android:background="#ffffff" >

                <TextView
                    android:id="@+id/second_tv"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:layout_alignParentLeft="true"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="15dp"
                    android:gravity="center_vertical"
                    android:text="Second"
                    android:textColor="#128C79"
                    android:textSize="20sp"
                    android:textStyle="normal" />
            </RelativeLayout>

            <View
                android:id="@+id/line1"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_below="@+id/second"
                android:background="#128C79" />

            <RelativeLayout
                android:id="@+id/menu_action"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/line1" >

                <ImageView
                    android:id="@+id/down"
                    android:layout_width="match_parent"
                    android:layout_height="66dp"
                    android:layout_centerHorizontal="true"
                    android:layout_centerInParent="true"
                    android:alpha="0.9"
                    android:src="@drawable/down_menu"
                    android:visibility="visible" />
            </RelativeLayout>
        </RelativeLayout>
    </com.sothree.slidinguppanel.SlidingUpPanelLayout>

</RelativeLayout>

Left.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <RelativeLayout
                android:id="@+id/first"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#ffffff" >

                <TextView
                    android:id="@+id/first_tv_left"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="15dp"
                    android:gravity="center_vertical"
                    android:text="First"
                    android:textColor="#128C79"
                    android:textSize="20sp"
                    android:textStyle="normal" />
            </RelativeLayout>

            <View
                android:id="@+id/line"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_below="@+id/first"
                android:background="#128C79" />

            <RelativeLayout
                android:id="@+id/second"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/line"
                android:background="#ffffff" >

                <TextView
                    android:id="@+id/second_tv_left"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:layout_alignParentLeft="true"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="15dp"
                    android:gravity="center_vertical"
                    android:text="Second"
                    android:textColor="#128C79"
                    android:textSize="20sp"
                    android:textStyle="normal" />
            </RelativeLayout>

            <View
                android:id="@+id/line1"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_below="@+id/second"
                android:background="#128C79" />


</RelativeLayout>

Right.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <RelativeLayout
                android:id="@+id/first"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#ffffff" >

                <TextView
                    android:id="@+id/first_tv_right"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="15dp"
                    android:gravity="center_vertical"
                    android:text="First"
                    android:textColor="#128C79"
                    android:textSize="20sp"
                    android:textStyle="normal" />
            </RelativeLayout>

            <View
                android:id="@+id/line"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_below="@+id/first"
                android:background="#128C79" />

            <RelativeLayout
                android:id="@+id/second"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/line"
                android:background="#ffffff" >

                <TextView
                    android:id="@+id/second_tv_right"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:layout_alignParentLeft="true"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="60dp"
                    android:layout_marginTop="15dp"
                    android:gravity="center_vertical"
                    android:text="Second"
                    android:textColor="#128C79"
                    android:textSize="20sp"
                    android:textStyle="normal" />
            </RelativeLayout>

            <View
                android:id="@+id/line1"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_below="@+id/second"
                android:background="#128C79" />

</RelativeLayout>

Project Layout:
 



Monday, 22 September 2014

Easy way to get json response for both GET and POST method

For POST method:

   HttpResponse response;
JSONObject jsonObject = null;
// Simulates a background job.

DefaultHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(www.google.com/api");

List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("sessionkey", "xxx"));

post.setEntity(new UrlEncodedFormEntity(params1));
response = client.execute(post);
jsonObject = new JSONObject(EntityUtils.toString(response
.getEntity()));

Log.d("result", jsonObject.toString() + "");

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



Wednesday, 7 August 2013

Cutom Actionbar in android

Here i am going to show you how to create custom action bar in all the screen.

My XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MainActivity" >

    <LinearLayout
            android:id="@+id/menu_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="@drawable/abplain" >

            <TextView
                android:id="@+id/login_name"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:fontFamily="Arial"
                android:paddingLeft="5dp"
                android:paddingTop="10dp"
                android:text="Custom Action bar"
                  android:textColor="@color/white"
                android:textStyle="bold" />
        </LinearLayout>



</RelativeLayout>

Color.XML
Add this color.xml in your Values folder

<?xml version="1.0" encoding="utf-8"?>
<resources >
   
    <color name="white">#FFFFFF</color>
 <color name="yellow">#FFFF00</color>
 <color name="fuchsia">#FF00FF</color>
 <color name="red">#FF0000</color>
 <color name="silver">#C0C0C0</color>
 <color name="gray">#808080</color>
 <color name="olive">#808000</color>
 <color name="purple">#800080</color>
 <color name="maroon">#800000</color>
 <color name="aqua">#00FFFF</color>
 <color name="lime">#00FF00</color>
 <color name="teal">#008080</color>
 <color name="green">#008000</color>
 <color name="blue">#0000FF</color>
 <color name="navy">#000080</color>
 <color name="black">#000000</color>
 <color name="terrorblue">#33b5e5</color>
 <color name="headingblue">#29a2d6</color>
</resources>

Manifest:
<activity
            android:name="com.example.Test.MainActivity"
            android:label="@string/app_name"
             android:theme="@android:style/Theme.NoTitleBar" >
        </activity>


Shared Preference in android

Application shared preferences allows you to save and retrieve key, value pair data. Before getting into tutorial, I am giving basic information needed to work with shared preferences.

Initialization
Application shared preferences can be fetched using getSharedPreferences() method.You also need an editor to edit and save the changes in shared preferences. The following code can be used to get application shared preferences.

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

Storing Data

You can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long

editor.commit(); // commit changes

Retrieving Data

Data can be retrived from saved preferences by calling getString() (For string) method. Remember this method should be called on Shared Preferences not on Editor.

//returns stored preference value
//If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

Clearing / Deleting Data

If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear()

editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email

editor.commit(); // commit changes

Following will clear all the data from shared preferences

editor.clear();

editor.commit(); // commit changes

Code for SharedPreference


public class SessionManager {

// http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

SharedPreferences pref;
Editor editor;
Context context;
int PRIVATE_MODE = 0;
String prefName = "eatPref";
String key_NAME = "username";
String key_PASS = "password";
String IS_LOGIN = "IsLoggedIn";

   //constructor
public SessionManager(Context context) {
this.context = context;
pref = context.getSharedPreferences(prefName, PRIVATE_MODE);
editor = pref.edit();
}

public void login(String username, String password) {
editor.putBoolean(IS_LOGIN, true);
editor.putString(key_NAME, username);
editor.putString(key_PASS, password);
editor.commit();
}

public HashMap<String, String> getDetails() {
HashMap<String, String> user = null;
user.put(key_NAME, pref.getString(key_NAME, null));
user.put(key_PASS, pref.getString(key_PASS, null));
return user;
}

// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}

}

LoginActivity:

public class Login extends Activity {
LinearLayout Signin;
EditText username;
EditText password;

@SuppressLint("ResourceAsColor")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.login_main);
// getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
// R.layout.header);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
password.setTypeface(Typeface.DEFAULT);

Signin = (LinearLayout) findViewById(R.id.signin_ll);

Signin.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

SessionManager sm = new SessionManager(getApplicationContext());
sm.login(username.getText().toString().trim().toLowerCase(),
password.getText().toString().trim().toLowerCase());
}
}
});
}

Monday, 5 August 2013

Split the Json format.


Here i am going to show you how to split the json format.

toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object

sample format.

{"user_id":"1","email":"xxx@gmail.com","password":"12","name":"yyy","gender":"male"}

Step1:
  Create a class for this json example

Class Info
{
public String user_id;
public String email;
public String password;
public String name;
public String gender;
}

Step2:
Download the gson jar file and add it in your lib folder.to know more about gson and json.

Step3:
//fromJson is used to convert back to object and display it.

        String result = "Your json string"
Gson gson = new Gson();
Info getResponse = gson.fromJson(result, Info.class);
        String name = getResponse.name; //To get the value of name.
        Toast.makeText(getApplicationContext(),
getResponse.name, Toast.LENGTH_LONG)
.show();

Sunday, 4 August 2013

Cosume PHP(POST METHOD) webservice in android.



Here i am passing json string parameter to php webservice. To consume php post method we will use HttpPost.

To create JSON String in android:

JSONObject json = new JSONObject();

json.put("name", "");
json.put("email", "");
json.put("password", "");

Log.i("json Object", json.toString());

Pass the parameter to post method:

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("userinfo", json.toString()));

Get the response InputStream like this:

HttpResponse response;
InputStream is = null;

   response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();

Full Code:

HttpResponse response;
JSONObject json = new JSONObject();
String json1 = "";
JSONObject jObj = null;
InputStream is = null;

DefaultHttpClient client = new DefaultHttpClient();

try {
HttpPost post = new HttpPost(
"Your URL");
json.put("name", "");
json.put("email", "");
json.put("password", "");

Log.i("jason Object", json.toString());
post.setHeader("userinfo", json.toString());

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userinfo", json.toString()));

post.setEntity(new UrlEncodedFormEntity(params));
response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();

try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json1 = sb.toString();
Log.i("jason Object", sb.toString());

Log.e("JSON", json1);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json1);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String

Log.d("final Response", jObj.toString());
Log.d("status", jObj.getString("status")); //Declare your status or message or json string variable

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

HttpResponse to String android

Manifest.xml:

Add the following line in your manifest.
<uses-permission android:name="android.permission.INTERNET"/>

Note:
In AVD to connect to localhost you need to use urlhttp://10.0.2.2/ instead of http://localhost/.

Thursday, 1 August 2013

Uploading file to webservice using KSOAP


1st step: Get the file from the SDcard and assign that file in INPUTSTREAM.
2nd step: Write the file into BYTEARRAYOUTPUTSTREAM
3rd step: Convert that Stream into BYTEARRAY
4th step: Convert Bytearray into BASE64STRING


Coding

   final String SOAP_ACTION = "";//Your soap action
final String METHOD_NAME = "";//Your method name
final String NAMESPACE = "";//Your name space
final String URL = "";//Your url

                InputStream is = null;

try {
is = new BufferedInputStream(new FileInputStream(
Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ "/download/"
+ yourfilename));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

//http://ricky-tee.blogspot.in/2012/06/converting-from-file-to-byte-array.html?showComment=1362738218958#c5250835248744198937

ByteArrayOutputStream bos = new ByteArrayOutputStream();

                               try {
while (is.available() > 0) {
bos.write(is.read());
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

byte[] byteArray = bos.toByteArray();
                             
                                String base64= Base64.encodeToString(byteArray,
Base64.DEFAULT);

      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  request.addProperty("str", base64);
  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE ht = new HttpTransportSE(URL);

try {
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
String str = response.toString();
                                     } catch (Exception e) {
e.printStackTrace();

}          

For Reference.

Downloading file from webservice using KSOAP

Here is the code to download the file from webservice.

Coding:

                final String SOAP_ACTION = "";//Your soap action
final String METHOD_NAME = "";//Your method name
final String NAMESPACE = "";//Your name space
final String URL = "";//Your url


                                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
                                //If you have some parameter to pass
//request.addProperty("", "");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE ht = new HttpTransportSE(URL);

try {
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();

String str = response.toString();

                                        //converting string to byte[]

byte[] decodedString = Base64.decode(str, Base64.DEFAULT);

                                  
File direct = new File(
Environment.getExternalStorageDirectory()
+ "/Download/");

if (!direct.exists()) {
direct.mkdir();
}

File file = new File(
Environment.getExternalStorageDirectory()
+ "/Download/", yourfilename);
    
if (file.exists()) {
file.delete();
}
                                              
try {
                                        //http://stackoverflow.com/a/7982964/1835764

FileOutputStream fos = new FileOutputStream(
file.getPath());

fos.write(decodedString);
fos.close();
                                             } catch (java.io.IOException e) 
                                             {
Log.e("fileDemo", "Exception in fileCallback", e);
}
}

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

}

Wednesday, 31 July 2013

AsyncTask in android

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Read this fully more about AsyncTask

Coding:

public class Login extends Activity {

 LinearLayout Signin;

 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.login_main);


Signin = (LinearLayout) findViewById(R.id.signin_ll);

Signin.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View arg0) {
// TODO Auto-generated method stub

                  myasynctask MAT = new myasynctask();
   MAT.execute();

   }
});

}

 class myasynctask extends AsyncTask<String, Void, String> {

       @Override
protected String doInBackground(String... params) {
   // TODO Auto-generated method stub
           //Background process like downloading, webservices etc...
           Log.d("doInBackground", "backgroundprocess is ongoing");
          return value;
}

        @Override
public void onPostExecute(String result) {
   // TODO Auto-generated method stub
             Log.d("PostExecute", "after finished the backgroundprocess");
   super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
   // TODO Auto-generated method stub
            Log.d("PreExecute", "before going to start the backgroundprocess");
   super.onPreExecute();
}
}
}

Friday, 26 July 2013

Cosume PHP(GET METHOD) webservice in android.

Here i am going to show you the exact code for cosume php webservice in android. But in this example i have passes emailid and password in the url to check whether the user is valid or not.
To consume php get method we will use HttpGet.

Get the response InputStream like this:

InputStream is = null;

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

Full Code:

  InputStream is = null;
JSONObject jObj = null;
String json = "";

       //Place your own url here
String URL = "http://domain.com/login.php?email="
+ username.getText().toString().trim().toLowerCase()
+ "&password="
+ password.getText().toString().trim().toLowerCase() + "";

   Log.d("username", username.getText().toString().trim()
   .toLowerCase());
   Log.d("password", password.getText().toString().trim()
   .toLowerCase());

   // Making HTTP request
   // (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/)

   try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);

Log.d("pre", URL);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

   } catch (UnsupportedEncodingException e) {
e.printStackTrace();
   } catch (ClientProtocolException e) {
e.printStackTrace();
   } catch (IOException e) {
e.printStackTrace();
   }

   try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
   sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
   } catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
   }

   // try parse the string to a JSON object
   try {
jObj = new JSONObject(json);
   } catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
   }

   // return JSON String

   Log.d("test", jObj.toString());


Manifest.xml:

Add the following line in your manifest.
<uses-permission android:name="android.permission.INTERNET"/>

convert httpresponse to string android 

Consume .net webservice in android



This simple example demonstrates how we can access a .net web service  from Android application.

 XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/web_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="112dp"
        android:layout_marginTop="146dp"
        android:text="Web Service" />

    <TextView
        android:id="@+id/fetch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView" />

    <ImageView
        android:id="@+id/fetch_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/fetch"
        android:layout_below="@+id/fetch"
        android:layout_marginTop="52dp"
        android:src="@drawable/ic_action_search" />

</RelativeLayout>

Activity:

public class MainActivity extends Activity {

Button web_service;
TextView fetch_service;

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

fetch_service = (TextView) findViewById(R.id.fetch);
web_service = (Button) findViewById(R.id.web_service);
web_service.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myasynctask MAT = new myasynctask();
MAT.execute();
}
});
}

class myasynctask extends AsyncTask<String, Void, String> {

String str;
private static final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
private static final String METHOD_NAME = "CelsiusToFahrenheit";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";

@Override
protected String doInBackground(String... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Celsius", "32");

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE ht = new HttpTransportSE(URL);

try {
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
str = response.toString();

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

}
Log.d("WebRespone", str);
return str;
}

@Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
fetch_service.setText(result);
super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}

}
}
Manifest:
add the following thins in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>

To Do:

You Must add this KSOAP jar file in your Lib folder




Recording Video in android


• To access the video recording by using intent We use MediaStore.ACTION_VIDEO_CAPTURE  in Intent function.

     
Function

• Intent(MediaStore.ACTION_VIDEO_CAPTURE).
• startActivityForResult

     Coding Part:

           XML:

       <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:text="Click" />

Activity:
        public class Recording extends Activity {

           Button clickBtn;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.menu);
        clickBtn=(Button)findViewById(R.id.button1);

clickBtn.setOnClickListener(new OnClickListener() {
   
      @Override
      public void onClick(View v) {
   // TODO Auto-generated method stub
      public void onClick(View arg0) {
 Intent takePicture = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(takePicture, 0);

              }
});
}
 }

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
                 super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

                 switch(requestCode) {
                 case 0:
                     if(resultCode == RESULT_OK){
                     Uri selectedImage = imageReturnedIntent.getData();
                             String[] filePathColumn = {MediaStore.Images.Media.DATA};

                                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                                cursor.moveToFirst();

                                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                               //file path of captured image
                                filePath = cursor.getString(columnIndex);
                                //file path of captured image
                                File f = new File(filePath);
                                filename= f.getName();
                             
                                Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
                                Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
                                cursor.close();
                                 
                              //Convert file path into bitmap image using below line.
                               // yourSelectedImage = BitmapFactory.decodeFile(filePath);
                             Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
                             
                               //put bitmapimage in your imageview
                               //yourimgView.setImageBitmap(yourSelectedImage);  


}
                     break;
                     }}}

Add these things in your android.manifest:


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

Recording audio in android



• To access the recording by using intent We use Intent.ACTION_GET_CONTENT in Intent function.
• Then, We have to set type to intent.setType("audio/*").
       
Function

• Intent(Intent.ACTION_GET_CONTENT).
• setType("audio/*").
• startActivityForResult

     Coding Part:

           XML:

       <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:text="Click" />

Activity:

        public class Recording extends Activity {

           Button clickBtn;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.menu);
        clickBtn=(Button)findViewById(R.id.button1);

clickBtn.setOnClickListener(new OnClickListener() {
 
      @Override
      public void onClick(View v) {
   // TODO Auto-generated method stub
      public void onClick(View arg0) {
 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("audio/*");
    startActivityForResult(intent, 0);
              }
});
}
 }

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
                 super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

                 switch(requestCode) {
                 case 0:
                     if(resultCode == RESULT_OK){
                     Uri selectedImage = imageReturnedIntent.getData();
                             String[] filePathColumn = {MediaStore.Images.Media.DATA};

                                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                                cursor.moveToFirst();

                                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                               //file path of captured image
                                filePath = cursor.getString(columnIndex);
                                //file path of captured image
                                File f = new File(filePath);
                                filename= f.getName();
                             
                                Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
                                Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
                                cursor.close();
                               
                              //Convert file path into bitmap image using below line.
                               // yourSelectedImage = BitmapFactory.decodeFile(filePath);
                             Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
                           
                               //put bitmapimage in your imageview
                               //yourimgView.setImageBitmap(yourSelectedImage);  


}
                     break;
                     }}}

Add these things in your android.manifest:


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