Friday, April 4, 2014

Send data to the Server like image(captured photo from camera), name, email




import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.media.MediaPlayer;
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.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;

public class CameraActivity extends Activity {

private static final int PICK_IMAGE = 1;
private static final int PICK_Camera_IMAGE = 2;
private ImageView imgView;
private Button upload, skip, btnCameraOn, btnTerm, btnPolicy;
private Bitmap bitmap;
private ProgressDialog dialog;
Uri imageUri;
Session mySession;
int imageFrom;
private UiLifecycleHelper uiHelper;
LoginButton authButton;
MediaPlayer mp = new MediaPlayer();
private String storeDataUrl;
String fb_id, stringBitmap, jsonResponse;
String filePath;
File file;
DefaultHttpClient mHttpClient;
HttpResponse response;
EditText etinternet;
private String internetMessage;
Typeface type_optima_bold;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_screen);

imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.imguploadbtn);
btnCameraOn = (Button) findViewById(R.id.btnCameraOn);

etinternet = (EditText)findViewById(R.id.etinternet);
type_optima_bold = Typeface.createFromAsset(getAssets(),
"fonts/Optima Demi Bold.ttf");
etinternet.setTypeface(type_optima_bold);

imageFrom = Global.viaemail;
try {
Bundle b = new Bundle();
b = getIntent().getExtras();
// fb_id = b.getString("facebook_id");
fb_id = Global.fbid;
System.out.println("from camera activity===" + fb_id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, callback,
savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
}

// ///////////
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
authButton = (LoginButton) findViewById(R.id.authButton);

/*
* authButton.setReadPermissions(Arrays.asList("email", "user_birthday",
* "basic_info"));
*
* authButton.clearPermissions();
*/

/*
* authButton.setPublishPermissions("publish_actions", "email",
* "user_birthday", "basic_info");
*/

btnCameraOn.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
String fileName = "new-photo-name.jpg";
// create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image captured by camera");
// imageUri is the current activity attribute, define and save
// it for
// later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
}
});
upload.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
if (bitmap == null) {
/*Toast toast1=Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast1.show();*/
internetMessage = etinternet.getText().toString();
myAlertBox(internetMessage);
} else {

new ImageGalleryTask().execute();
}
}
});





}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImageUri = null;
uiHelper.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {

case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
// use imageUri here to access the image
selectedImageUri = imageUri;

} else if (resultCode == RESULT_CANCELED) {
Toast toast2=Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT);
toast2.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast2.show();
} else {
Toast toast3=Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT);
toast3.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast3.show();
}
break;
}

if (selectedImageUri != null) {
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();

// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);

if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast toast4=Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG);
toast4.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast4.show();

Log.e("Bitmap", "Unknown path");
}

if (filePath != null) {
file = new File(filePath);
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast toast5=Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG);
toast5.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast5.show();

Log.e(e.getClass().getName(), e.getMessage(), e);
}
}

}

private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
Exception exception) {
mySession = session;
System.out.println("statusCallBack Called");
onSessionStateChange(session, state, exception);

}
};

private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
authButton.setVisibility(View.GONE);
} else if (state.isClosed()) {
authButton.setVisibility(View.VISIBLE);
}
}

@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}

@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}

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

@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(CameraActivity.this, "Uploading",
"Please wait...", true);
super.onPreExecute();
}

@Override
protected String doInBackground(Void... unsued) {

if (imageFrom == 1) {
// put the uploading of image,name and email like else part
try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient();
File file = new File(filePath);
HttpPost httppost = new HttpPost("paste server url");
MultipartEntity entity = new MultipartEntity();
entity.addPart("name", new StringBody(Global.name));
entity.addPart("email", new StringBody(Global.email));
entity.addPart("file", new FileBody(file));
httppost.setEntity(entity);
response = mHttpClient.execute(httppost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {

try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient();
File file = new File(filePath);
HttpPost httppost = new HttpPost("paste server url");
MultipartEntity entity = new MultipartEntity();
entity.addPart("fb_id", new StringBody(fb_id));
entity.addPart("file", new FileBody(file));
httppost.setEntity(entity);
response = mHttpClient.execute(httppost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

return null;

}

@Override
protected void onProgressUpdate(Void... unsued) {

}

@Override
protected void onPostExecute(String sResponse) {
try {
if(imageFrom==1){
System.out.println("Global.name========"+Global.name);
System.out.println("Global.email==="+Global.email);
}else{
System.out.println("imageFrom="+imageFrom);
}
System.out.println("filepath is===" + filePath);
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
Log.i("UPLOAD==", responseString);
System.out.println("respose from camera multipart==="
+ responseString);
if (dialog.isShowing())
dialog.dismiss();
Intent in = new Intent(getApplicationContext(),
ThankYouActivity.class);
in.putExtra("session", mySession);
startActivity(in);
} catch (Exception e) {
Toast toast6=Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG);
toast6.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast6.show();

Log.e(e.getClass().getName(), e.getMessage(), e);
}
}

}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}



public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);

// The new size we want to scale to
final int REQUIRED_SIZE = 1024;

// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}

// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);

System.out.println("what is bitmap==" + bitmap);
stringBitmap = BitMapToString(bitmap);
System.out.println("String bitmap is==" + stringBitmap);
imgView.setImageBitmap(bitmap);

}

// convert bitmap to string
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String strBitMap = Base64.encodeToString(b, Base64.DEFAULT);
return strBitMap;
}
public void myAlertBox(String msg) {
final Dialog dialog1 = new Dialog(CameraActivity.this);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setContentView(R.layout.my_custom_popup_alert);

Button ok = (Button) dialog1.findViewById(R.id.button1);
TextView tv = (TextView) dialog1.findViewById(R.id.tv1);
tv.setTypeface(type_optima_bold);
tv.setText(msg);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog1.dismiss();
//startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
//finish();
}
});
dialog1.show();
}

}

No comments:

Post a Comment