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.