Display image capture using camera in android device - android-camera

i want's to display image capture using device camera and for that i have used below code.but i am getting null value in data that is return in onActivityResult .so please provide me solution for that..
thanks,
and my code is:
File root = new File(Environment.getExternalStorageDirectory()+"/TestCameraGallery");
root.mkdirs();
MyCameraGallery = new File(root, "mycamerapicname");
Uri outputFileUri = Uri.fromFile(MyCameraGallery );
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_PIC_REQUEST)
{
Uri uri = data.getData();
}
}
value of uri is null and give null pointer exception so please help me

Using your code you will get low resolution image. If you wanna get the high resolution image you can refer this answer.
And also you can refer this blog

get solution finally
String imageName = "image.jpg" ;
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, imageName);
uri_captureImage = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri_captureImage);
startActivityForResult(intent, requestCode_camera);
and in onAcitivity for result
String[] projection = new String[] {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri_captureImage, projection, null, null, null);
cursor.moveToFirst();
String capimage_path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));

Related

Pass data from android to flutter

I have added my Android side code:
I know that I need to use a platform channel to pass data,I am unable to figure out:
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends AppCompatActivity {
private Button Btn;
// Intent defaultFlutter=FlutterActivity.createDefaultIntent(activity);
String path;
private Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = findViewById(R.id.btn);
isStoragePermissionGranted();
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
path=takeScreenshot();
// activity.startActivity(defaultFlutter);
}
});
//write flutter xode here
//FlutterActivity.createDefaultIntent(this);
}
private String takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
Log.d("path",mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
return mPath;
///openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
return "Error";
}
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
}
I will receive a file from the android side, upon receiving I need to display it in a flutter. I also need to use cached engine for transferring data as normally it would cause a delay
You can use the cached engine, this will help me cover up for the delay.
Then you can add a invoke method onpressed that you can send method name and the data you want to pass.
On flutter side,you can create a platform and invoke method through which you can receive requirements and further process it,

Display specific Activity, when Firebase notification is tapped

When user taps on a notification sent from the Firebase console, I need to launch a specific Android Activity, only when the user taps on the notification. How can this be accomplished in the following 2 scenarios:
App is not opened or app running in Background
App is in the foreground
You can achieve this in two ways,
1. First way
Adding click_action in notification payload,
jNotification.put("click_action", "OPEN_ACTIVITY_1");
private void pushNotification(String token) {
JSONObject jPayload = new JSONObject();
JSONObject jNotification = new JSONObject();
JSONObject jData = new JSONObject();
try {
jNotification.put("title", "Google I/O 2016");
jNotification.put("text", "Firebase Cloud Messaging (App)");
jNotification.put("sound", "default");
jNotification.put("badge", "1");
jNotification.put("click_action", "OPEN_ACTIVITY_1");
jData.put("picture_url", "http://opsbug.com/static/google-io.jpg");
jPayload.put("to", token);
//jPayload.put("to", "/topics/news");
//jPayload.put("condition", "'logined' in topics || 'news' in topics");
//jPayload.put("registration_ids", jData);
jPayload.put("priority", "high");
jPayload.put("notification", jNotification);
jPayload.put("data", jData);
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", AUTH_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// Send FCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jPayload.toString().getBytes());
// Read FCM response.
InputStream inputStream = conn.getInputStream();
final String resp = convertStreamToString(inputStream);
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
#Override
public void run() {
Log.e("Response", resp);
//txtStatus.setText(resp);
}
});
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
Add this is in your AndroidManifest.xml
<activity android:name="com.example.fcm.SecondActivity">
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
RemoteMessage.Notification notification = remoteMessage.getNotification();
Map<String, String> map = remoteMessage.getData();
sendNotification(notification.getTitle(), notification.getBody(), map);
}
private void sendNotification(String title, String body, Map<String, String> map) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setContentInfo(title)
.setLargeIcon(icon)
.setSmallIcon(R.mipmap.ic_launcher);
try {
String picture_url = map.get("picture_url");
if (picture_url != null && !"".equals(picture_url)) {
URL url = new URL(picture_url);
Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(body));
}
} catch (IOException e) {
e.printStackTrace();
}
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.YELLOW, 1000, 300);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private static final String TAG = "SecondActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
for (String key : bundle.keySet()) {
Object value = bundle.get(key);
Log.d(TAG, "Key: " + key + " Value: " + value.toString());
}
}
}
}
2. Second way
Send key through data payload like below and get key in MainActivity via getIntent() and call specific activity or fragments.
json1.put("title","Your Title");
json1.put("body","body content");
json1.put("message","Your Message");
json1.put("screen","2"); //secondFragment is 2nd position in nav drawer
json.put("data", json1);
MainActivity.java
Intent intent = getIntent();
String pos = getIntent().getStringExtra("screen");
if(pos !=null){
selectDrawerItem(navigationView.getMenu().getItem(Integer.parseInt(pos)));
}
Sample project in GITHUB,
https://github.com/Google-IO-extended-bangkok/FCM-Android

Android ListView does not update dynamic location data

I have researched this topic thoroughly and found similar questions on StackOverflow but not specific enough for my question. I am trying to update my ListView with a SimpleCursorAdapter. I have a button, "Get Network Location" that when I press it, it dynamically populates my ListView with new location data (id, lat, lon, acc, time) every time the location changes inside method "onLocationChanged". This is done through adding the new location data to the database and setting the cursor to the adapter.
So it works fine until the "Back" button is pressed or the phone changes orientation. In onResume, the listview becomes empty, so I had to open the database again and set the cursor to the adapter and the adapter to listview again. This populates the listview with complete data from database at the time that "onResume" is called.
However, when a new location data gets added in "onLocationChanged", the new data doesn't populate the listview, until "onResume" gets called again. adapter.notifyDataSetChanged is called both in "onResume" an "onLocation" changed but to no avail. My guess is the listview has changed to a different one after "onCreate" is called but I don't know how to resolve that.
Please anyone with knowledge on this issue let me know what is wrong with my code.
Here's my code:
public class MainActivity extends Activity {
LocationManager locMan;
String provider;
Boolean netWork_enabled = false;
private static long MINTIME;
private static float MINDIS;
Cursor cursor;
NetworkScanDB GeoLocInfoDb;
String row;
double lat;
double lon;
double accur;
double time;
EditText etMinTime;
EditText etMinDis;
ListView lv;
SimpleCursorAdapter sd;
String[] columns;
int[] to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize lv
lv = (ListView) findViewById(R.id.listView1);
// getting min time and distance from edit text
etMinTime = (EditText) findViewById(R.id.et_minTime);
etMinDis = (EditText) findViewById(R.id.et_minDis);
// initiating location
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locMan.NETWORK_PROVIDER;
try {
netWork_enabled = locMan.isProviderEnabled(provider);
} catch (Exception ex) {
}
columns = new String[] { NetworkScanDB.Key_RowID,
NetworkScanDB.Key_Lat, NetworkScanDB.Key_Lon,
NetworkScanDB.Key_Accur, NetworkScanDB.Key_Time };
to = new int[] { R.id.t0, R.id.t1, R.id.t2, R.id.t3, R.id.t4 };
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
}
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
// insert row into DB
GeoLocInfoDb.insertGeoLocInfo(location.getLatitude(),
location.getLongitude(), location.getAccuracy(),
location.getTime());
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow,
cursor, columns, to, 0); // had to change to api 11.,
// 0=no query
Toast.makeText(getApplicationContext(),
"added new location onLocationChanged",
Toast.LENGTH_LONG).show();
// lv = (ListView) findViewById(R.id.listView1);
sd.notifyDataSetChanged();
lv.setAdapter(sd);
GeoLocInfoDb.close();
} catch (Exception e) {
Log.w("nwscan", e.toString());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
public void getNetworkLocation(View v) {
MINTIME = Long.parseLong(etMinTime.getText().toString());
MINDIS = Float.parseFloat(etMinDis.getText().toString());
if (netWork_enabled) {
locMan.requestLocationUpdates(provider, MINTIME, MINDIS,
locationListenerNetwork);
} else {
Toast.makeText(getApplicationContext(), "network not enable",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getApplicationContext(), "onResume ", Toast.LENGTH_LONG)
.show();
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
sd.notifyDataSetChanged();
lv.setAdapter(sd);
}
...
}

Upload image to server in GWT project using Servlet

I am developing a GWT application which, among its other functions, permits the user to upload an image file and to store it on the server.
So far, that's what I've done..
SERVLET
public class ImageUploadService extends HttpServlet {
private static final int MAX_FILE_SIZE = 1 * 1024 * 1024;
public void doPost(HttpServletRequest request, HttpServletResponse response) {
wlog("INFO: è partita la servlet");
if (!ServletFileUpload.isMultipartContent(request))
wlog("ERR: non è multipart!");
ServletFileUpload fileUpld = new ServletFileUpload();
try {
wlog("INFO: itero file");
FileItemIterator fileIt = fileUpld.getItemIterator(request);
while (fileIt.hasNext()) {
wlog("INFO: trovato file");
FileItemStream fileStream = fileIt.next();
BufferedInputStream in = new BufferedInputStream(
fileStream.openStream(), 4096);
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream("immagineSegnalazione.jpg"));
byte[] buf = new byte[MAX_FILE_SIZE];
int byteRead;
while ((byteRead = in.read(buf, 0, MAX_FILE_SIZE)) >= 0) {
out.write(buf, 0, byteRead);
}
in.close();
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void wlog(String s) {
System.out.println("UPLOAD SERVLET " + s);
}
}
MODULE ON CLIENT SIDE
[...]
PopupPanel inserisciSegnalazionePopup = new PopupPanel();
final FormPanel uploadForm = new FormPanel();
uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadForm.setMethod(FormPanel.METHOD_POST);
inserisciSegnalazionePopup.setAutoHideEnabled(true);
VerticalPanel holder = new VerticalPanel();
holder.add(new Label("se puoi, allega una foto della segnalazione"));
final FileUpload fu = new FileUpload();
uploadForm.add(fu);
holder.add(uploadForm);
uploadForm.setAction(GWT.getModuleBaseURL() + "imageUpload");
Button inviaBtn = new Button("INVIA SEGNALAZIONE");
inviaBtn.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
// TODO check file is image and size and other stuff
uploadForm.submit();
}
});
holder.add(inviaBtn);
[...]
..plus I've rightly made the changes needed on web.xml
The Servlet is correctly called and the method doPost() starts, but the FileItemIterator is always empty, as if there were no files at all..
Can someone guess what's wrong? I can't really see where's the mistake
Thank you in advance
just guessing I would say the request is parsed somewhere befor you use it. Try taking a look at that question and the answer to it, it seems to like it was nearly the same problem.
Sarajog
Have you tried this ??
Iterator<FileItem> iterator = upload.parseRequest(request).iterator();
The solution is...
Simply add .setName() to the FileUpload widget

Windows Phone 7 Facebook Image Posting Issue

I know these facebook api stuffs are really became a pain in the ass, after from my longer searches on internet, I could only find a message post API to facebook. I just want to modify it for both message and image posting. Here is relevant code which posts a message to facebook.(Windows Phone 7)
private void PostToWall_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtMessage.Text))
{
MessageBox.Show("Enter message.");
return;
}
var fb = new FacebookClient(_accessToken);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message));
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
_lastMessageId = (string)result["id"];
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Message Posted successfully");
txtMessage.Text = string.Empty;
btnDeleteLastMessage.IsEnabled = true;
});
};
var parameters = new Dictionary<string, object>();
parameters["message"] = txtMessage.Text;
fb.PostAsync("me/feed", parameters);
}
and I have also found a image post code, but I could not integrate it into my code. I think methods are not appropriate with each other.
Here is image post code;
var photo = new WriteableBitmap(0, 0).FromResource("Background200x200.jpg");
FacebookClient app = new FacebookClient();
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters["access_token"] = _facebookAccessToken; //set in another method where I authenticate...
parameters["name"] = "my picture";
parameters["message"] = "this is a picture uploaded from my the facebook sdk";
var mediaObject = new FacebookMediaObject {
FileName = "Background200x200.jpg",
ContentType = "image/jpeg",
};
mediaObject.SetValue(photo.ToByteArray());
parameters["source"] = mediaObject;
app.ApiAsync(
UploadComplete,
null,
"https://graph.facebook.com/me/feed",
parameters,
HttpMethod.Post);
I just want to post an image with a message. And If you can give me a sample link which posts an image to facebook (I ve been seeking for a ready-coded image post application,that is, Visual studio solution file which I can compile it and XAP it, and run on my phone)
or If you can help me to evolve my message poster to image poster, I would be really pleasured.
THANKS