developing an application to take a photo and draw GPS coordinates over it.
just gave a test for the drawtext() method, which isn't showing up.
GPS is working fine.
Camera is working fine.
Canvas is having problems.
code for mainactivity.java
package com.example.camera;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageView;
import android.widget.Button;
import android.view.View;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileOutputStream;
import android.os.Environment;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Date;
import android.widget.Toast;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
public class MainActivity extends Activity
{
double lat,lon;
private static final String TAG = "CallCamera";
private static final int CAPTURE_IMAGE_ACTIVITY_REQ = 0;
private String photoUri=null;
Uri fileUri = null;
ImageView photoImage = null;
private File getOutputPhotoFile()
{
File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getPackageName());
Log.d("directory check ", directory.toString());
if (!directory.exists())
{
if (!directory.mkdirs())
{
Log.e(TAG, "Failed to create storage directory.");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.US).format(new Date());
return new File(directory.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg");
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
photoImage = (ImageView) findViewById(R.id.photo_image);
try
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
catch(Exception e)
{
Log.d("GPS","Exception in location part-->"+e.toString());
}
Button callCameraButton = (Button)
findViewById(R.id.button_callcamera);
callCameraButton.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(getOutputPhotoFile());
i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQ );
}
}
);
}
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
if (location != null)
{
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
lat=location.getLatitude();
lon=location.getLongitude();
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0)
{
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQ)
{
if (resultCode == RESULT_OK)
{
Uri photoUri = null;
if (data == null)
{
// A known bug here! The image should have saved in fileUri
Log.d("Image Code","Image Saved");
photoUri = fileUri;
}
else
{
photoUri = data.getData();
Log.d("Image Code","Image Saved at"+data.getData());
}
drawLatLong(photoUri.getPath());
}
else if (resultCode == RESULT_CANCELED)
{
Log.d("Image Code", "Cancled");
}
else
{
Log.d("Image Code", "Callout for image capture failed!");
}
}
}
/**
* takes the PhotoURI and draws the Latitude and longitude over it
* #param photoUri
*/
private void drawLatLong(String photoUri)
{
File imageFile = new File (photoUri);
if (imageFile.exists())
{
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// Resources res=getResources();
// BitmapDrawable drawable = new BitmapDrawable(res,bitmap);
try
{
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.WHITE); // Text Color
paint.setStrokeWidth(12); // Text Size
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern
// some more settings...
canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.drawText("Testing...", 10, 10, paint);
-
FileOutputStream fOut = new FileOutputStream(photoUri);
Log.d("Path"," "+photoUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
System.out.println(photoUri);
//bitmap.recycle();
// System.gc();
}
catch(Exception ex)
{
Log.d("Canvas Part", "Exception caused in canvas drawing-->"+ex.toString());
}
showPhoto(bitmap);
}
}
/**
* Takes the Bitmap from the drawLatLong() method and displays it over the image view.
* #param bitmapShow
*/
private void showPhoto(Bitmap bitmapShow)
{
try
{
Resources res=getResources();
BitmapDrawable drawable = new BitmapDrawable(res,bitmapShow);
photoImage.setImageDrawable(drawable);
photoImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
photoImage.setImageBitmap(bitmapShow);
}
catch(Exception ex)
{
Log.d("canvas","exception in canvas"+ex);
}
}
}
the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.camera"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.camera.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The bitmap needs to be inMutable. set it with the following code.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(),options);
This section of the code is not needed as the canvas already has this bitmap.
//Not needed:
//canvas.drawBitmap(bitmap, 0, 0, paint);
Related
I want to run a Backgroundservice (FileObserver) that will look for any filechanges in the system (CREATE, DELETE, MOVE, ...).
When I start my application it works a few seconds and logs everything fine. For example at taking a picture by the camera it logs that. After a few seconds the service is still listed in Settings => Developer Options => Running Services but does not work and log anything anymore.
Android Version: 7.0
Device: Samsung Galaxy S7 Edge
I copied the code from Niza Siwale's answer here 1:1 and added only the Logs like that :
How to monitor folder for file changes in background?
#Override
public void onEvent(int event, final String path) {
if (event == FileObserver.OPEN) {
Log.v("Event: ", "Open" + path);
} else if (event == FileObserver.CREATE && (!path.equals(".probe"))) {
Log.v("Event: ", "Create" + path);
} else if (event == FileObserver.DELETE_SELF || event == FileObserver.DELETE) {
Log.v("Event: ", "Delete" + path);
} else if (event == FileObserver.MOVE_SELF || event == FileObserver.MOVED_FROM || event == FileObserver.MOVED_TO) {
Log.v("Event: ", "Move" + path);
}
}
Why is the service running in background (as I can see in Running Services) but not donig any logs, if something changes in the filesystem?
Full Code:
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spicysoftware.phonesaver">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<!-- Adding the permission -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service
android:name=".FileSystemObserverService"
android:enabled="true"
android:exported="true" >
</service>
<!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
<receiver android:name=".StartupReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity
package com.spicysoftware.phonesaver;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String TAG = "Log: ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isReadStoragePermissionGranted()){
Intent myIntent = new Intent(this, FileSystemObserverService.class);
this.startService(myIntent);
}
}
public boolean isReadStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted1");
return true;
} else {
Log.v(TAG,"Permission is revoked1");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 3);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted1");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 3:
Log.d(TAG, "External storage1");
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
}else{
}
break;
}
}
}
FileSystemOberveService
package com.spicysoftware.phonesaver;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class FileSystemObserverService extends Service {
String externalPath = "";
String internalPath = "";
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
observe();
return super.onStartCommand(intent, flags, startId);
}
public File getInternalStoragePath() {
File parent = Environment.getExternalStorageDirectory().getParentFile();
File external = Environment.getExternalStorageDirectory();
File[] files = parent.listFiles();
File internal = null;
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].getName().toLowerCase().startsWith("sdcard") && !files[i].equals(external)) {
internal = files[i];
}
}
}
return internal;
}
public File getExtenerStoragePath() {
return Environment.getExternalStorageDirectory();
}
public void observe() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
//File[] listOfFiles = new File(path).listFiles();
File str = getInternalStoragePath();
if (str != null) {
internalPath = str.getAbsolutePath();
new Obsever(internalPath).startWatching();
}
str = getExtenerStoragePath();
if (str != null) {
externalPath = str.getAbsolutePath();
new Obsever(externalPath).startWatching();
}
}
});
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}
class Obsever extends FileObserver {
List<SingleFileObserver> mObservers;
String mPath;
int mMask;
public Obsever(String path) {
// TODO Auto-generated constructor stub
this(path, ALL_EVENTS);
}
public Obsever(String path, int mask) {
super(path, mask);
mPath = path;
mMask = mask;
// TODO Auto-generated constructor stub
}
#Override
public void startWatching() {
// TODO Auto-generated method stub
if (mObservers != null)
return;
mObservers = new ArrayList<SingleFileObserver>();
Stack<String> stack = new Stack<String>();
stack.push(mPath);
while (!stack.empty()) {
String parent = stack.pop();
mObservers.add(new SingleFileObserver(parent, mMask));
File path = new File(parent);
File[] files = path.listFiles();
if (files == null) continue;
for (int i = 0; i < files.length; ++i) {
if (files[i].isDirectory() && !files[i].getName().equals(".") && !files[i].getName().equals("..")) {
stack.push(files[i].getPath());
}
}
}
for (int i = 0; i < mObservers.size(); i++) {
mObservers.get(i).startWatching();
}
}
#Override
public void stopWatching() {
// TODO Auto-generated method stub
if (mObservers == null)
return;
for (int i = 0; i < mObservers.size(); ++i) {
mObservers.get(i).stopWatching();
}
mObservers.clear();
mObservers = null;
}
#Override
public void onEvent(int event, final String path) {
if (event == FileObserver.OPEN) {
Log.v("Event: ", "Open" + path);
// makeToast("Opened: "+path);
} else if (event == FileObserver.CREATE && (!path.equals(".probe"))) {
Log.v("Event: ", "Create" + path);
// makeToast("Created: "+path);
} else if (event == FileObserver.DELETE_SELF || event == FileObserver.DELETE) {
Log.v("Event: ", "Delete" + path);
// makeToast("Deleted: "+path);
} else if (event == FileObserver.MOVE_SELF || event == FileObserver.MOVED_FROM || event == FileObserver.MOVED_TO) {
Log.v("Event: ", "Move" + path);
// makeToast("Moved: "+path);
}
}
private class SingleFileObserver extends FileObserver {
private String mPath;
public SingleFileObserver(String path, int mask) {
super(path, mask);
// TODO Auto-generated constructor stub
mPath = path;
}
#Override
public void onEvent(int event, String path) {
// TODO Auto-generated method stub
String newPath = mPath + "/" + path;
Obsever.this.onEvent(event, newPath);
}
}
}
/*
public void makeToast(final String strMessage){
//Let this be the code in your n'th level thread from main UI thread
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), strMessage, Toast.LENGTH_SHORT).show();
}
});
}
*/
}
StartupReceiver
package com.spicysoftware.phonesaver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartupReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, FileSystemObserverService.class);
context.startService(myIntent);
}
}
I want to create an application to get the user location info in coordinates using Locaion manager. The problem is my application always has stopped when it runs and always get java.lang.NullPointerException
this is my Main ACtivity
package com.ionlab.project.volley;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ionlab.project.volley.app.AppController;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements LocationListener {
//location
private TextView textView;
private LocationManager locationManager;
//waktu
TextView textviewDate;
Button buttonChoose;
FloatingActionButton buttonUpload;
Toolbar toolbar;
ImageView imageView;
EditText txt_name;
EditText txt_item;
Bitmap bitmap, decoded;
int success;
int PICK_IMAGE_REQUEST = 1;
int bitmap_size = 60; // range 1 - 100
private static final String TAG = MainActivity.class.getSimpleName();
/* 10.0.2.2 adalah IP Address localhost Emulator Android Studio. Ganti IP Address tersebut dengan
IP Address Laptop jika di RUN di HP/Genymotion. HP/Genymotion dan Laptop harus 1 jaringan! */
private String UPLOAD_URL = "http://192.168.1.4/android/upload_image/upload.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private String KEY_ITEM = "item";
private String KEY_LOKASI = "lokasi";
private String KEY_WAKTU = "waktu";
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (FloatingActionButton) findViewById(R.id.buttonUpload);
txt_name = (EditText) findViewById(R.id.editText);
txt_item = (EditText) findViewById(R.id.editItem);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
//Calendar
Calendar calendar = Calendar.getInstance();
String currenDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
textviewDate = findViewById(R.id.text_view_date);
textviewDate.setText(currenDate);
//textloc
textView = (TextView) findViewById(R.id.id_textview);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
//menampilkan progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
if (success == 1) {
Log.e("v Add", jObj.toString());
Toast.makeText(MainActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
kosong();
} else {
Toast.makeText(MainActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
//menghilangkan progress dialog
loading.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//menghilangkan progress dialog
loading.dismiss();
//menampilkan toast
Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, error.getMessage().toString());
}
}) {
#Override
protected Map<String, String> getParams() {
//membuat parameters
Map<String, String> params = new HashMap<String, String>();
//menambah parameter yang di kirim ke web servis
params.put(KEY_IMAGE, getStringImage(decoded));
params.put(KEY_NAME, txt_name.getText().toString().trim());
params.put(KEY_ITEM, txt_item.getText().toString().trim());
params.put(KEY_WAKTU, textviewDate.getText().toString().trim());
params.put(KEY_LOKASI, textView.getText().toString().trim());
//kembali ke parameters
Log.e(TAG, "" + params);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_json_obj);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//mengambil fambar dari Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// 512 adalah resolusi tertinggi setelah image di resize, bisa di ganti.
setToImageView(getResizedBitmap(bitmap, 512));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void kosong() {
imageView.setImageResource(0);
txt_name.setText(null);
txt_item.setText(null);
}
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//menampilkan gambar yang dipilih dari camera/gallery ke ImageView
imageView.setImageBitmap(decoded);
}
// fungsi resize image
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
#Override
public void onLocationChanged(Location location) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
textView.setText("Longitude:" + longitude + "\n" + "Latitude:" + latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
i also make sure that my android manifest is correct
I have Spent Day and Night trying to solve this problem, Browsed through numerous pages on the topic, Tried different codes of my own.
And it still happens. I am a beginner in Android. And please, please do help me. Is there no possible way to solve my problem?
this is my logcat
LogCat
Firstly, you should include your logcat in text form as a part of your question!
However, from what I can read from your screenshot the issue is in the onLocationChanged() method. Perform a check on "location" to see if it is null before trying to read it.
#Override
public void onLocationChanged(Location location) {
if(location != null){
double longitude = location.getLongitude();
double latitude = location.getLatitude();
textView.setText("Longitude:" + longitude + "\n" + "Latitude:" + latitude);
}
else{
Log.e(TAG, "onLocationChanged -- location is null!");
}
}
Note:
Just in case you didn't know the "TAG" is generally added to the beginning of most Android class like this:
public class MainActivity extends AppCompatActivity implements LocationListener {
private static final String TAG = MainActivity.class.getSimpleName();
Why MainActivity.class.getSimpleName() instead of just "MainActivity"? Because if you ever refactor your code, then the name will automatically be changed.
EDIT:
Have you added the necessary permissions in your manifest file?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>
I have tried 3 diffrent methods for sending a image from my Android to PHP.
All three gives the message "Missing inp_image name". I am thinking that I maybe am not sending the image as an image, but rather as some text ?
I am using this http request class in Android: https://github.com/kevinsawicki/http-request
Method 1 with encoding it to base64:
//String selectedFilePath = FilePath.getPath(context, imageUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bm = BitmapFactory.decodeFile(destImage,options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byteImage_photo = baos.toByteArray(); // bitmap object
//generate base64 string of image
String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
// Send image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", encodedImage);
stringResponse = request.body();
Method 2 - sending a input stream of image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", in); // sending input stream
stringResponse = request.body();
Method 3 - sending file:
String sourceFilename= FilePath.getPath(context, imageUri);
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", new File(sourceFilename)); // sending input stream
stringResponse = request.body();
Android Mainifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity:
package com.nettport.imageupload.imageupload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Check permission */
checkPermissionRead();
checkPermissionWrite();
/* Button listener */
buttonListener();
} // onCreate
private void checkPermissionRead(){
int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
private void checkPermissionWrite(){
int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
public void buttonListener() {
// Image button listener
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadImage);
buttonLoadImage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
// Load gallery
// User can select images and upload them
// Result will be in onActivityResult
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
});
// Camera
Button buttonLoadCamera = (Button) findViewById(R.id.buttonLoadCamera);
buttonLoadCamera.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
// Load camera
// Result will be in onActivityResult
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code
}
});
} // buttonListener
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Set image
ImageView imageViewImage = (ImageView)findViewById(R.id.imageViewImage);
imageViewImage.setImageURI(selectedImageUri);
// Save image
String destinationFilename = savefile(selectedImageUri);
try {
InputStream in = getContentResolver().openInputStream(selectedImageUri);
TextView textViewDynamicText = (TextView) findViewById(R.id.textViewDynamicText); // Dynamic text
String apiURL = "https://xxxxxx.com/xxxxxx/image_upload.php";
UploadImage task = new UploadImage(this, apiURL, in, selectedImageUri, destinationFilename, textViewDynamicText, new UploadImage.TaskListener() {
#Override
public void onFinished(String result) {
// Do Something after the task has finished
imageUploadResult();
}
});
task.execute();
//in.close();
}
catch (java.io.FileNotFoundException e) {
Toast.makeText(this, "MainAcrivity java.io.FileNotFoundException: " + e.toString(), Toast.LENGTH_LONG).show();
}
catch (java.io.IOException e) {
Toast.makeText(this, "MainAcrivity java.io.IOException: " + e.toString(), Toast.LENGTH_LONG).show();
}
} // RESULT_OK
} // onActivityResult
public void imageUploadResult(){
// Dynamic text
TextView textViewDynamicText = (TextView)findViewById(R.id.textViewDynamicText);
Toast.makeText(this, textViewDynamicText.getText().toString(), Toast.LENGTH_SHORT).show();
} // imageUploadResult
public String savefile(Uri sourceuri) {
String sourceFilename= FilePath.getPath(this, sourceuri);
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Upload";
String destinationFilename = destinationPath+"/upload_me.png";
// Make dir
File folder = new File(destinationPath);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
} else {
Toast.makeText(this, "Dir failed", Toast.LENGTH_LONG).show();
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
// Toast.makeText(this, "Saved to " + destinationFilename, Toast.LENGTH_LONG).show();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "savefile#1: " + e.toString() + "\nFrom: " + sourceFilename, Toast.LENGTH_LONG).show();
}
finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "savefile#2: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
return destinationFilename;
}
}
UploadImage class:
package com.nettport.imageupload.imageupload;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by bruker on 08.08.2017.
* Updated
*/
public class UploadImage extends AsyncTask<String, Void, String> {
/* Class variables */
private Context context; // Holder (this)
private String apiUrl; // URL for image upload form, example http://website.com/image_upload.php
private TextView dynamicText;
private InputStream in;
private Uri imageUri;
private String destImage;
private final UploadImage.TaskListener taskListener; // This is the reference to the associated listener
public interface TaskListener {
public void onFinished(String result);
}
/*- Constructor GET, SEND --------------------------------------------------------------- */
public UploadImage(Context ctx, String applicationPIUrl, InputStream input, Uri selectedImageUri, String destinationFilename, TextView textViewDynamicText, UploadImage.TaskListener listener) {
context = ctx;
apiUrl = applicationPIUrl;
in = input;
imageUri = selectedImageUri;
destImage = destinationFilename;
dynamicText = textViewDynamicText;
this.taskListener = listener; // The listener reference is passed in through the constructor
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dynamicText.setText(dynamicText.getText().toString() + "\n" + "Loading...");
}
#Override
protected String doInBackground(String... params) {
// Run methods
String stringResponse ="";
try {
try{
// Method 1 - Base 64
/*
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bm = BitmapFactory.decodeFile(destImage,options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byteImage_photo = baos.toByteArray(); // bitmap object
//generate base64 string of image
String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
// Send image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", encodedImage);
stringResponse = request.body();
*/
// Method 2 - Input stream
/*
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", in); // sending input stream
stringResponse = request.body();
*/
// Method 3 - File
String sourceFilename= FilePath.getPath(context, imageUri);
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", new File(sourceFilename)); // sending input stream
stringResponse = request.body();
}
catch (Exception e){
return e.toString();
}
}
catch(Exception e){
return e.toString();
}
return stringResponse;
}
#Override
protected void onPostExecute(String result) {
// Set text view with result string
if(dynamicText == null){
Toast.makeText(context, "NULL", Toast.LENGTH_SHORT).show();
}
else {
dynamicText.setText(dynamicText.getText().toString() + "\n" + result);
}
// In onPostExecute we check if the listener is valid
if(this.taskListener != null) {
// And if it is we call the callback function on it.
this.taskListener.onFinished(result);
}
}
#Override
protected void onProgressUpdate(Void... values) {}
}
PHP Script:
<?php
/**
*
* File: image_upload.php
* Date 13:05 04.08.2017
* Version 1
* Copyright (c) 2017 S. A. Ditlefsen
* License: http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/*- Get extention ---------------------------------------------------------------------- */
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
/*- Path -------------------------------------------------------------------------------- */
if(!(is_dir("_images"))){
mkdir("_images");
}
/*- Script start ------------------------------------------------------------------------ */
$name = stripslashes($_FILES['inp_image']['name']);
if($name){
$extension = getExtension($name);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
echo"unknown_file_extension";
}
else{
$date_time = date("Y-m-d_h-i-s");
$new_name = $date_time . ".png";
$new_path = "_images/";
$uploaded_file = $new_path . $new_name;
// Upload file
if (move_uploaded_file($_FILES['inp_image']['tmp_name'], $uploaded_file)) {
// Get image size
$file_size = filesize($uploaded_file);
// Check with and height
list($width,$height) = getimagesize($uploaded_file);
if($width == "" OR $height == ""){
echo"getimagesize_failed";
}
else{
// Resize to $settings_image_width
$newwidth=1000;
$newheight=($height/$width)*$newwidth; // 667
$tmp=imagecreatetruecolor($newwidth,$newheight);
if($extension=="jpg" || $extension=="jpeg" ){
$src = imagecreatefromjpeg($uploaded_file);
}
else if($extension=="png"){
$src = imagecreatefrompng($uploaded_file);
}
else{
$src = imagecreatefromgif($uploaded_file);
}
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight, $width,$height);
imagepng($tmp,$uploaded_file);
imagedestroy($tmp);
echo"$new_name";
} // width height
} // move_uploaded_file
else{
switch ($_FILES['inp_food_image_b']['error']) {
case UPLOAD_ERR_OK:
echo"image_to_big";
break;
case UPLOAD_ERR_NO_FILE:
echo"no_file_uploaded";
break;
case UPLOAD_ERR_INI_SIZE:
echo"to_big_size_in_configuration";
break;
case UPLOAD_ERR_FORM_SIZE:
echo"to_big_size_in_form";
break;
default:
echo"unknown_error";
break;
}
}
} // extention
} // name
else{
echo"Missing inp_image name";
}
?>
try this and it is working for me ,
String imgstring = getStringImage(bitmap)
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
volley
public void addimage() {
String link = CommonVariables.SERVER_IP + "/uploadimage.php";
StringRequest request = new StringRequest(Request.Method.POST, link, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError != null && volleyError.getMessage() != null) {
Toast.makeText(getContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("imagename", "yourimagename");
params.put("imagecode", imageString);
return params;
}
};
RetryPolicy mRetryPolicy = new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(mRetryPolicy);
queue.add(request);
}
php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$imgcode = $_POST['imagecode'];
$imagename = $_POST['imagename'];
require_once('dbconnect.php');
// this is ths path where your image is stored in the file in server
$path = "images/$imagename.jpg";
$sql = "INSERT INTO productlist(proimagename)
VALUES ('$imagename')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($imgcode));
echo "1";
}
mysqli_close($con);
}else{
echo "0";
}
i already set google tts language to hindi.And in my code i am setting that hindi as a default language by tts.setLanguage(Locale.getDefault()),my code working fine.But when i am using Locale.getDefault().getDisplayLanguage() to get default language,logcat shows English.
I want to set language according to user.
package com.example.texttospeech;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("unused")
public class MainActivity extends Activity implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
EditText ed1,ed2;
Button b1,b2;
AudioManager audioManager;
static final int READ_BLOCK_SIZE = 100;
protected static final int PICKFILE_RESULT_CODE = 1;
protected static final int ACTIVITY_TTS_PASS=1;
#SuppressWarnings("static-access")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText1);
b1=(Button)findViewById(R.id.button1);
ed2=(EditText)findViewById(R.id.editText2);
b2=(Button)findViewById(R.id.button2);
tts = new TextToSpeech(this, this);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int amStreamMusicMaxVol = audioManager.getStreamMaxVolume(audioManager.STREAM_MUSIC);
audioManager.setStreamVolume(audioManager.STREAM_MUSIC, amStreamMusicMaxVol, 0);
audioManager.setSpeakerphoneOn(true);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "clicked",Toast.LENGTH_SHORT).show();
try {
if(ed1.getText().toString()==null || ed1.getText().toString().matches(""))
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file.txt/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}else
{
savefile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// openfile();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
Locale.getDefault().getDisplayLanguage();
Log.e("--f----f-----f-- ",""+Locale.getDefault().getDisplayLanguage());
if (status == TextToSpeech.SUCCESS)
{
int result = tts.setLanguage(Locale.getDefault());
Log.e("--g----g-----g--",""+result);
tts.setLanguage(new Locale("hi_IN"));
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED)
{
Log.e("TTS", "This Language is not supported");
}
else {
b1.setEnabled(true);
try {
savefile();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void savefile() throws IOException {
String text = ed1.getText().toString();
FileOutputStream fos = null;
final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MynewText/" );
if (!dir.exists())
{
dir.mkdirs();
}
final File myFile = new File(dir, "newtest" + ".txt");
if (!myFile.exists())
{
myFile.createNewFile();
}
fos = new FileOutputStream(myFile);
fos.write(text.getBytes());
fos.close();
Toast.makeText(getBaseContext(), "File saved successfully!",Toast.LENGTH_SHORT).show();
tts.setSpeechRate(0);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
try {
// Read text from file
File sdcard = Environment.getExternalStorageDirectory();
File file1 = new File(sdcard,"MynewText/newtest.txt");
//Read text from file
StringBuilder text1 = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file1));
String line;
while ((line = br.readLine()) != null)
{
text1.append(line);
text1.append('\n');
}
ed2.setText(text1);
br.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case ACTIVITY_TTS_PASS:
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
tts = new TextToSpeech(getApplicationContext(), this);
int availability = tts.isLanguageAvailable(new Locale("hin-IND"));
switch(availability)
{
case TextToSpeech.LANG_AVAILABLE:
Log.d("TTS", "Language available");
break;
case TextToSpeech.LANG_NOT_SUPPORTED:
Log.d("TTS", "Language not supported");
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
ArrayList<String> languages = new ArrayList<String>();
languages.add("hin-IND"); // hin - hindi, IND - INDIA
installTTSIntent.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
startActivity(installTTSIntent);
break;
case TextToSpeech.LANG_MISSING_DATA:
Log.d("TTS", "Language missing data");
break;
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
Log.d("TTS", "Contry available");
break;
default:
Log.d("TTS", "default");
}
}
else {
Log.d("TTS", "fail");
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
ArrayList<String> languages = new ArrayList<String>();
languages.add("hin-IND"); // hin - hindi, IND - INDIA
installTTSIntent.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
startActivity(installTTSIntent);
}
break;
default:
Log.d("TTS", "case default");
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
For getting Default language set in setting > Language and Input > Google-Text-To-Speech default language set , i used :
tts.getLanguage();
I am Newbie to Android.
I have tried all the posts in this forum. But could not get the success.
I am trying to share an mp3 file from asset folder to whatsapp.
Below is my code.
This is my Code in Main Activity:
package com.example.sharedemo;
import com.example.sharedemo.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button sharebutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharebutton = (Button) findViewById(R.id.sharebutton1);
sharebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri theUri = Uri.parse("content://com.example.sharedemo.Assetsprovider/gotShocked.mp3");
Intent theIntent = new Intent(Intent.ACTION_SEND);
theIntent.setType("audio/mp3");
theIntent.setPackage("com.whatsapp");
theIntent.putExtra(Intent.EXTRA_STREAM,theUri);
startActivity(Intent.createChooser(theIntent,"Share using"));
}
});
}
}
Code in ContentProvider:
package com.example.sharedemo;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
public class Assetsprovider extends ContentProvider {
#Override
public AssetFileDescriptor openAssetFile( Uri uri, String mode ) throws FileNotFoundException
{
AssetManager am = getContext( ).getAssets( );
String file_name = uri.getLastPathSegment( );
// String file_name = uri.getPath();
if( file_name == null )
throw new FileNotFoundException( );
AssetFileDescriptor afd = null;
try
{
afd = am.openFd(file_name);
}
catch(IOException e)
{
e.printStackTrace( );
}
return afd;//super.openAssetFile(uri, mode);
}
#Override
public String getType( Uri p1 )
{
// TODO: Implement this method
return null;
}
#Override
public int delete( Uri p1, String p2, String[] p3 )
{
// TODO: Implement this method
return 0;
}
#Override
public Cursor query( Uri p1, String[] p2, String p3, String[] p4, String p5 )
{
// TODO: Implement this method
return null;
}
/* #Override
public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal )
{
// TODO: Implement this method
return super.query( uri, projection, selection, selectionArgs, sortOrder, cancellationSignal );
}*/
#Override
public Uri insert( Uri p1, ContentValues p2 )
{
// TODO: Implement this method
return null;
}
#Override
public boolean onCreate( )
{
// TODO: Implement this method
return false;
}
#Override
public int update( Uri p1, ContentValues p2, String p3, String[] p4 )
{
// TODO: Implement this method
return 0;
}
}
Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sharedemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Assetsprovider"
android:label="#string/app_name" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="com.example.sharedemo.Assetsprovider"
android:authorities="com.example.sharedemo.Assetsprovider"
android:grantUriPermissions="true"
android:exported="true" />
</application>
</manifest>
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM,Uri.parse("file:///"+mypath));
startActivity(Intent.createChooser(share, "Share Sound File"));
break;
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}```