Pages

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