Pages

Wednesday, September 10, 2014

Multipart Entity


HttpClient httpClient = new DefaultHttpClient();
   HttpPost postRequest = new HttpPost("");
   MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
   try {
 
reqEntity.addPart("profile_id",new StringBody(Session_id));
reqEntity.addPart("file_name", new StringBody("abc"));
reqEntity.addPart("file_type",new StringBody(ext));
reqEntity.addPart("caption",new StringBody(ed.getText().toString()));
reqEntity.addPart("upload_data", new FileBody(new File(pathMaster)));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
 
   postRequest.setEntity(reqEntity);      
   HttpResponse response = null;
try {
response = httpClient.execute(postRequest);

Log.e("Response", ""+response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   String sResponse;
   StringBuilder s = new StringBuilder();
   try {
while ((sResponse = reader.readLine()) != null) {
   s = s.append(sResponse);
   Log.e("VIDEO RESPONSE", s.toString());
 
   vd = s.toString();
   JSONObject obj = new JSONObject(vd);
   Status = obj.getString(Constant.STATUS);
   Log.e("aaa", Status);
   pd.dismiss();
 
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Thursday, July 3, 2014

custom listview

public class ListViewAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
private int[] colors = new int[] { 0xAAff0000, 0xAAffffff };

public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
return data.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView brand,price;

ImageView logo;
Button btn;

inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View itemView = inflater.inflate(R.layout.test, parent, false);
// Get the position
resultp = data.get(position);

// Locate the TextViews in listview_item.xml
brand = (TextView) itemView.findViewById(R.id.tv_brand1);
price = (TextView) itemView.findViewById(R.id.tv_price11);

logo = (ImageView) itemView.findViewById(R.id.iv_logo11);
btn = (Button) itemView.findViewById(R.id.btn_view);

// Capture position and set results to the TextViews
brand.setText(resultp.get(CountryFragment.Name));

price.setText(resultp.get(CountryFragment.Price));






imageLoader.DisplayImage("http://jbtechnology.in/Krishna_Mobile/Logo/"+resultp.get(CountryFragment.Logo), logo);
// Capture ListView item click




btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, detail.class);

intent.putExtra("Name", resultp.get(CountryFragment.Name));
intent.putExtra("Price", resultp.get(CountryFragment.Price));
intent.putExtra("Logo", "http://jbtechnology.in/Krishna_Mobile/Logo/"+resultp.get(CountryFragment.Logo));
intent.putExtra("Desc", resultp.get(CountryFragment.Desc));



context.startActivity(intent);

}
});

/*int colorPos = position % colors.length;
itemView.setBackgroundColor(colors[colorPos]);*/
return itemView;
}

Monday, June 30, 2014

FB



import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;

public class Activity extends Activity {

private Session.StatusCallback statusCallback = new SessionStatusCallback();
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private ProgressDialog mProgressDialog = null;
private SharedPreferences preferences;
private TextView txtFBName;
private Button txtFBLogin;
private boolean isFacebookLogin;
private String userName,Email,bdate,contact;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

preferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);

Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
}
}

txtFBLogin = (Button) findViewById(R.id.activity_login_btn_fb);
txtFBName = (TextView) findViewById(R.id.textView1);
updateView();
txtFBLogin.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (isFacebookLogin) {
postImage();
//openShareContentDialog(FBpostActivity.this, 0, userName);
} else {
onClickLogin();
}
}
});
}

public void postImage() {
       if (checkPermissions()) {
           Bitmap img = BitmapFactory.decodeResource(getResources(),
                   R.drawable.ic_launcher);
           Request uploadRequest = Request.newUploadPhotoRequest(
                   Session.getActiveSession(), img, new Request.Callback() {
                       @Override
                       public void onCompleted(Response response) {
                           Toast.makeText(FBpostActivity.this,
                                   "Photo uploaded successfully",
                                   Toast.LENGTH_LONG).show();
                       }
                   });
           uploadRequest.executeAsync();
       } else {
           requestPermissions();
       }
   }
public boolean checkPermissions() {
       Session s = Session.getActiveSession();
       if (s != null) {
           return s.getPermissions().contains("publish_actions");
       } else
           return false;
   }

   public void requestPermissions() {
       Session s = Session.getActiveSession();
       if (s != null)
           s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                   this, PERMISSIONS));
   }

private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForPublish(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(PERMISSIONS));
} else {
Session.openActiveSession(this, true, statusCallback);
}
}

private void onClickLogout() {
Session session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
txtFBName.setText("");
}
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}

private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state, Exception exception) {
getFBUserData(session);
updateView();
}
}

public void openShareContentDialog(Context activity, final int option, String userName) {

final Dialog dialogView = new Dialog(activity);
dialogView.setContentView(R.layout.facebook_dialog);
dialogView.setCancelable(false);
dialogView.setCanceledOnTouchOutside(false);
dialogView.setTitle("Share Message");
final Button btnLogout = (Button) dialogView.findViewById(R.id.facebook_dialog_btnLogout);
final Button btnCancel = (Button) dialogView.findViewById(R.id.facebook_dialog_btnCancel);
final Button btnPost = (Button) dialogView.findViewById(R.id.facebook_dialog_btnPost);
final EditText edDescription = (EditText) dialogView.findViewById(R.id.facebook_dialog_edttext_post);
final TextView txtUserName = (TextView) dialogView.findViewById(R.id.facebook_dialog_txt_username);

if (option == 0) {
txtUserName.setText(userName);
} else if (option == 1) {
txtUserName.setText(userName);
}

/**
* Get the data from dialog's control and share the data on faceBook or
* Twitter according to selectedOption.
*/
btnLogout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialogView.dismiss();
if (option == 0) {
onClickLogout();
} else if (option == 1) {
//\\ shared.shareOnTwitter(edDescription.getText().toString());

}
}
});
btnPost.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialogView.dismiss();
if (option == 0) {
postStatusUpdate(edDescription.getText().toString().trim());
} else if (option == 1) {
// shared.shareOnTwitter(edDescription.getText().toString());

}
}
});

btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialogView.dismiss();
}
});

dialogView.show();
}

private void updateView() {
preferences = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
Session session = Session.getActiveSession();

if (session.isOpened()) {
txtFBLogin.setText("Already Login");
isFacebookLogin = true;
final String name = preferences.getString("Name", "");
//final String email = preferences.getString("Email", "");

if (name.equalsIgnoreCase("")) {
} else {
txtFBName.setVisibility(View.VISIBLE);
txtFBName.setText("Hello" + " " + name);
}
} else {
txtFBLogin.setText("Login");
isFacebookLogin = false;
txtFBName.setText("");
txtFBName.setVisibility(View.GONE);
}
}

private void postStatusUpdate(String user) {
if (txtFBName.getText() != null && hasPublishPermission()) {
Log.v("KETAN", "hasPublishPermission" + hasPublishPermission());
final String message = getString(R.string.status_update, user, (new Date().toString()));
Request request = Request.newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
@Override
public void onCompleted(Response response) {
Toast.makeText(FBpostActivity.this, message, Toast.LENGTH_LONG).show();
}
});
request.executeAsync();
}
}

private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}

@Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}

@Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}

public void getFBUserData(Session session) {

if (session.isOpened()) {
if (FBpostActivity.this != null) {
mProgressDialog = ProgressDialog.show(FBpostActivity.this, "", "Please Wait...");
}

Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}

String link = user.getLink();
userName = user.getUsername();
Email = user.getFirstName();
bdate = user.getBirthday();


isFacebookLogin = true;

if (link.length() != 0) {
SharedPreferences preferences = FBpostActivity.this.getSharedPreferences(
FBpostActivity.this.getString(R.string.app_name), Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("Link", link);
editor.putString("Name", userName);
editor.commit();
}

if (userName != null && userName.length() > 0) {
txtFBName.setText(userName);

Toast.makeText(getApplicationContext(), ""+userName+Email+bdate, 10).show();
//openShareContentDialog(FBpostActivity.this, 0, userName);
}
}
}
});
}
}

}
 <activity android:name="com.facebook.LoginActivity"
                  android:label="@string/app_name" />
        <meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id"/>


sqlite image database android

b1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
   Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
               startActivityForResult(intent, 0);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
      {
          super.onActivityResult(requestCode, resultCode, data);
       
          if(resultCode == RESULT_OK)
          {
          selectedImage = data.getData();  
          bmImage.setImageURI(selectedImage);
          }
      }

b3 = (Button)findViewById(R.id.add);
b3.setOnClickListener(new OnClickListener() {

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


                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
           if(c == null) return;            
           c.moveToFirst();
           int columnIndex = c.getColumnIndex( MediaStore.Images.Media.DATA);
           ImagePath = c.getString(columnIndex);
           c.close();
               
                byte byteImage1 [] = null;
                try{
                FileInputStream instream = new FileInputStream(ImagePath);
             BufferedInputStream bif = new BufferedInputStream(instream);
             byteImage1 = new byte[bif.available()];
             bif.read(byteImage1);
           
             Log.d("Byte Value",""+byteImage1.length);
                }catch (IOException e) {

}
                d = h.getWritableDatabase();
                ContentValues cv =new  ContentValues();
                cv.put(h.IMAGE_DATA, byteImage1);
                d.insert(h.IMAGE_TABLE, null,cv);
                d.close();
                Toast.makeText(getApplicationContext(), "Save", 6).show();
             
             
       

}
});




Saturday, June 14, 2014

Update Listview by every 1 minute Android

final Handler handler = new Handler()
handler.postDelayed( new Runnable() {

    @Override
    public void run() {
        adapter.notifyDataSetChanged();
        handler.postDelayed( this, 60 * 1000 );
    }
}, 60 * 1000 );

Friday, June 13, 2014

Sorting Listview in Android



Collections.sort(list, comparator);
ActAdapter adp = new ActAdapter(getParent(), list);
lv.setAdapter(adp);
adp.notifyDataSetChanged();

Change Order of map1 and map2 as per your requirement


Comparator<HashMap<String, String>> comparator = new Comparator<HashMap<String, String>>() {
    @Override
    public int compare(HashMap<String, String> map1, HashMap<String, String> map2) {
        return map2.get(CREATED).compareTo(map1.get(CREATED));
    }
};

Thursday, June 12, 2014

Date/Time difference in Duration Android


public static TimeZone timeZone;

public static String dateDiff(String d){


SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 timeZone = TimeZone.getDefault();

 timeZone = TimeZone.getTimeZone("America/New_York");
format.setTimeZone(timeZone);
String currentDateandTime = format.format(new Date());

 Date dt1 = null;
       Date dt2 = null;
       try {
           dt1 = format.parse(d);
           dt2 = format.parse(currentDateandTime);
       } catch (ParseException e) {
           e.printStackTrace();
       }  
     
       long diff = dt2.getTime() - dt1.getTime();
       long diffSeconds = diff / 1000 % 60;
       long diffMinutes = diff / (60 * 1000) % 60;
       long diffHours = diff / (60 * 60 * 1000);
       long a = diffHours%24;
       int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));

       if(diffInDays>0){
       
        return ""+diffInDays+" day";
       }

       else if(a>0){
     
return ""+a+" hr";
}else  {
return ""+diffMinutes+" min";
}
}

Friday, June 6, 2014

Inner Tab Android

public class first extends ActivityGroup{


Button launchButton;
/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);


launchButton = (Button)findViewById(R.id.button1);
launchButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent activity3Intent = new Intent(v.getContext(), second.class);

replaceContentView("activity3", activity3Intent);
}
});
}
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView(); this.setContentView(view);
}  
}





For Next Class

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

Intent activity4Intent = new Intent(v.getContext(), third.class);
//StringBuffer urlString = new StringBuffer();
first parentActivity = (first)getParent();
parentActivity.replaceContentView("activity4", activity4Intent);

}

Saturday, May 31, 2014

Image pass in Json Android

package com.example.fb;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;





import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Test extends Activity implements OnClickListener{
EditText email,pass;
Button btn,btn1,btn2;
ArrayList<NameValuePair> np;
ProgressDialog pd;
JSONParser jp;
String Status;
AlertDialogManager alert;
String pathMaster ="";
byte[] byteImage1 = null;
String byteImage;
String Image;
Bitmap bmp;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);

alert = new AlertDialogManager();

/*email = (EditText)findViewById(R.id.editresetemail);
pass = (EditText)findViewById(R.id.editresetpass);*/
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
btn1 = (Button)findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2 = (Button)findViewById(R.id.button3);
btn2.setOnClickListener(this);

jp = new JSONParser();
}

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


if(v == btn){

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
   // request code

   startActivityForResult(cameraIntent, 99);
}
if(v == btn1){

Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 0);
}
if(v == btn2){

getImage1();
new insert().execute();
}

}

private void getImage1() {
// TODO Auto-generated method stub

ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byteImage1 = bao.toByteArray();
    Image=Base64.encodeToString(byteImage1, Base64.DEFAULT);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK && requestCode==99)
{
Uri targetUri = data.getData();
pathMaster = getRealPathFromURI(targetUri);

bmp = ShrinkBitmap(pathMaster, 100, 100);
        ImageView image1 = (ImageView)findViewById(R.id.image);
        image1.setImageBitmap(bmp);

}
else if(resultCode == RESULT_OK && requestCode==0)
{
Uri targetUri = data.getData();
        pathMaster = getRealPathFromURI(targetUri).toString();            
        bmp = ShrinkBitmap(pathMaster, 100, 100);
        ImageView image1 = (ImageView)findViewById(R.id.image);

        image1.setImageBitmap(bmp);
    }  
super.onActivityResult(requestCode, resultCode, data);
}


/*
************************ Compress Image **************************
*/
private Bitmap ShrinkBitmap(String path, int width, int height) {
// TODO Auto-generated method stub

BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(path, bmpFactoryOptions);

int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);

if (heightRatio > 1 || widthRatio > 1)
{
 if (heightRatio > widthRatio)
 {
  bmpFactoryOptions.inSampleSize = heightRatio;
 } else {
  bmpFactoryOptions.inSampleSize = widthRatio;
 }
}

bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(path, bmpFactoryOptions);
return bitmap;


}

/*
*************** Get path of image from camera or gallery *******************
*/

private String getRealPathFromURI(Uri targetUri) {
// TODO Auto-generated method stub
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( targetUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}




class insert extends AsyncTask<Void, Void, Void>{





@Override
protected void onPreExecute() {
// TODO Auto-generated method stub

pd = new ProgressDialog(Test.this);
pd.setMessage("Loading....");
pd.setTitle("Update Password");
pd.show();

super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params) {



np = new ArrayList<NameValuePair>();
np.add(new BasicNameValuePair("session_id","85"));
np.add(new BasicNameValuePair("ns_data",Image));



JSONObject jo = jp.makeHttpRequest(Constant.PROFILEPIC, "POST", np);



// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pd.dismiss();



super.onPostExecute(result);
}



}



}

Tuesday, May 6, 2014

SOAP

package com.webservice;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WebServiceDemoActivity extends Activity
{
    /** Called when the activity is first created. */
      private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
      private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
      private static String NAMESPACE = "http://tempuri.org/";
      private static String METHOD_NAME1 = "FahrenheitToCelsius";
      private static String METHOD_NAME2 = "CelsiusToFahrenheit";
      private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";

      Button btnFar,btnCel,btnClear;
      EditText txtFar,txtCel;
   
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        btnFar = (Button)findViewById(R.id.btnFar);
        btnCel = (Button)findViewById(R.id.btnCel);
        btnClear = (Button)findViewById(R.id.btnClear);
        txtFar = (EditText)findViewById(R.id.txtFar);
        txtCel = (EditText)findViewById(R.id.txtCel);
     
        btnFar.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        //Initialize soap request + add parameters
                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);      
               
                  //Use this to add parameters
                  request.addProperty("Fahrenheit",txtFar.getText().toString());
               
                  //Declare the version of the SOAP request
                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
               
                  envelope.setOutputSoapObject(request);
                  envelope.dotNet=true;
               
                  try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                     
                        //this is the actual part that will call the webservice
                        androidHttpTransport.call(SOAP_ACTION1, envelope);
                     
                        // Get the SoapResult from the envelope body.
                        SoapObject result = (SoapObject)envelope.bodyIn;

                        if(result != null)
                        {
                              //Get the first property and change the label text
                              txtCel.setText(result.getProperty(0).toString());
                        }
                        else
                        {
                              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  }
            });
     
        btnCel.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        //Initialize soap request + add parameters
                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);      
               
                  //Use this to add parameters
                  request.addProperty("Celsius",txtCel.getText().toString());
               
                  //Declare the version of the SOAP request
                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
               
                  envelope.setOutputSoapObject(request);
                  envelope.dotNet = true;
               
                  try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                     
                        //this is the actual part that will call the webservice
                        androidHttpTransport.call(SOAP_ACTION2, envelope);
                     
                        // Get the SoapResult from the envelope body.
                        SoapObject result = (SoapObject)envelope.bodyIn;

                        if(result != null)
                        {
                              //Get the first property and change the label text
                              txtFar.setText(result.getProperty(0).toString());
                        }
                        else
                        {
                              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  }
            });
     
        btnClear.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        txtCel.setText("");
                        txtFar.setText("");
                  }
            });
    }
}

FB Login

Declare

private boolean isFacebookLogin = false;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
String name,email,bdate,contact;
private ProgressDialog mProgressDialog = null;
ProgressDialog pd;

RelativeLayout rl;

//OnCreate()

Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }
        getFBUserData(session);

Login Click

call  onClickLogin()

@Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }
 

    private void onClickLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            Toast.makeText(Login.this, "sucess", 10).show();
           // getFBUserData(session);
        } else {
            Session.openActiveSession(this, true, statusCallback);
            Toast.makeText(Login.this, "sucess", 10).show();
           // getFBUserData(session);
        }
    }

    private void onClickLogout() {
        Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        public void call(Session session, SessionState state, Exception exception) {
        getFBUserData(session);
       
        }
    }
    public void getFBUserData(Session session) {

if (session.isOpened()) {
if (Login.this != null) {
mProgressDialog = ProgressDialog.show(Login.this, "", "Please Wait...");
}

Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

public void onCompleted(GraphUser user, Response response) {
if (user != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}

String link = user.getLink();
name = user.getName();
email = user.getUsername();
bdate = user.getBirthday();


isFacebookLogin = true;

if (link.length() != 0) {

SharedPreferences savedData = getSharedPreferences("Dompanion", 0);

SharedPreferences.Editor editor = savedData.edit();



editor.putString("email", email);
editor.putString("name", name);

editor.putInt("logged_in", 2);
editor.putString("dom", "A");
editor.commit();

Intent i = new Intent(Login.this,MainActivity.class);
startActivity(i);

}


}
}
});
}

Menifest.xml

<meta-data
            android:name="com.facebook.sdk.ApplicationId"

            android:value="@string/client_app_id" />

Download