Share Action provider to share image from imageView gives null pointer exception - java

I tried to share an image loaded into the imageview from glide following this guide, it gives me a null pointer exception. I've posted the code and stacktrace below, it
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText editText;
private ShareActionProvider myShareActionProvider;
//private Bitmap bitmap;
private Uri uri;
private Intent shareIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
String hi = "http://37n98a43dqtb4bua9n28nidp.wpengine.netdna-cdn.com/wp-content/uploads/2016/09/MyFriendPikachu.jpg";
Glide
.with(this)
.load(hi)
.listener(new RequestListener<String, GlideDrawable>() {
#Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
prepareShareIntent(((GlideBitmapDrawable) resource).getBitmap());
attachShareIntentAction();
return false;
}
})
.placeholder(R.drawable.ic_action_name)
.error(R.drawable.ic_img_error)
.centerCrop()
.into(imageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.img_menu, menu);
MenuItem item = menu.findItem(R.id.action_share);
myShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
attachShareIntentAction();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public void prepareShareIntent(Bitmap drawableImage) {
Uri bmpUri = getBitmapFromDrawable(drawableImage);
shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
}
public void attachShareIntentAction() {
if (myShareActionProvider != null && shareIntent != null)
myShareActionProvider.setShareIntent(shareIntent);
}
public Uri getBitmapFromDrawable(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "images" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = FileProvider.getUriForFile(MainActivity.this, "com.example.imnobody.sampleprojectnetwork", file); // use this version for API >= 24
// **Note:** For API < 24, you may use bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
}
fileprovider.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-file-path
name="images"
path="Pictures" />
</paths>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.imnobody.sampleprojectnetwork">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_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>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.imnobody.sampleprojectnetwork.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/fileprovider" />
</provider>
</application>
</manifest>
Stacktrace
java.lang.NullPointerException
at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
at com.example.imnobody.sampleprojectnetwork.MainActivity.getBitmapFromDrawable(MainActivity.java:134)
at com.example.imnobody.sampleprojectnetwork.MainActivity.prepareShareIntent(MainActivity.java:95)
at com.example.imnobody.sampleprojectnetwork.MainActivity$1.onResourceReady(MainActivity.java:59)
at com.example.imnobody.sampleprojectnetwork.MainActivity$1.onResourceReady(MainActivity.java:51)
at com.bumptech.glide.request.GenericRequest.onResourceReady(GenericRequest.java:522)
at com.bumptech.glide.request.GenericRequest.onResourceReady(GenericRequest.java:507)
at com.bumptech.glide.load.engine.EngineJob.handleResultOnMainThread(EngineJob.java:158)
at com.bumptech.glide.load.engine.EngineJob.access$100(EngineJob.java:22)
at com.bumptech.glide.load.engine.EngineJob$MainThreadCallback.handleMessage(EngineJob.java:202)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)

Your <provider> has the following android:authorities value:
com.example.imnobody.sampleprojectnetwork.fileprovider
This is what you are providing to getUriForFile(), claiming that it is your provider's authority:
com.example.imnobody.sampleprojectnetwork
These are not the same, and they need to be.

Related

Service doesnt work correctly in Background

I am making Music Player which downloads music from Firebase.
Its working fine but I cannot play music in background.
It works for like 1.5 minute (after locking screen) and it stops.
In logs after I lock screen it says "Inactivity, disconnecting from Service".
I think this may be main problem here.
Here code :
Fragment of Playing Music:
public class PlayerFragment extends Fragment {
private FirebaseStorage storage;
private ImageButton main_btn, next_btn, back_btn, fav_btn, settings_btn;
private Uri localSong;
private Intent myService;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_player, container, false);
storage = FirebaseStorage.getInstance();
main_btn= view.findViewById(R.id.player_main_btn);
next_btn= view.findViewById(R.id.player_next_btn);
back_btn= view.findViewById(R.id.player_back_btn);
fav_btn = view.findViewById(R.id.player_song_fav_btn);
settings_btn = view.findViewById(R.id.player_song_options_btn);
storage.getReference().child("songs/ni_bien_ni_mal.mp3").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
localSong=uri;
}
});
MainActivity mainActivity = (MainActivity) getActivity();
myService = new Intent(getActivity(), BackgroundSoundService.class);
main_btn.setOnClickListener(v -> {
if( main_btn.getDrawable().getConstantState().equals( main_btn.getContext().getDrawable(R.drawable.ic_play).getConstantState()))
{
new Thread(new Runnable() {
#Override
public void run() {
myService.putExtra("uri",localSong.toString() );
mainActivity.startService(myService);
}
}).start();
main_btn.setImageResource(R.drawable.ic_pause);
}
else
{
new Thread(new Runnable() {
#Override
public void run() {
// mainActivity.stopService(myService);
main_btn.setImageResource(R.drawable.ic_play);
}
}).start();
}
});
fav_btn.setOnClickListener(v->{
if( fav_btn.getDrawable().getConstantState().equals( fav_btn.getContext().getDrawable(R.drawable.ic_heart_empty).getConstantState()))
{
fav_btn.setImageResource(R.drawable.ic_heart_full);
}else{
fav_btn.setImageResource(R.drawable.ic_heart_empty);
}
});
return view;
}
}
Manifest: ( Service declaration is at bottom)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.company.altasnotas">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<application
android:allowBackup="true"
android:icon="#drawable/altas_notes"
android:label="#string/app_name"
android:roundIcon="#drawable/altas_notes"
android:supportsRtl="true"
android:testOnly="false"
android:theme="#style/Theme.AltasNotas">
<activity
android:name=".IntroActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AltasNotas.NoActionBar"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"
tools:replace="android:value" />
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
</activity>
<service android:enabled="true" android:name=".BackgroundSoundService" />
</application>
</manifest>
Service :
public class BackgroundSoundService extends Service {
String song_string;
int x;
private static final String TAG = "BackgroundSoundService";
MediaPlayer player;
public IBinder onBind(Intent arg0) {
Log.i(TAG, "onBind()" );
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public int onStartCommand(Intent intent, int flags, int startId) {
song_string= intent.getStringExtra("uri");
if (song_string != null) {
System.out.println("Song string : " + song_string);
player = MediaPlayer.create(this, Uri.parse(song_string));
player.setLooping(false); // Set looping
player.setVolume(0.5f, 0.5f);
if (!(String.valueOf(x) == null || String.valueOf(x).isEmpty())) {
player.seekTo(x);
}
player.start();
}
return Service.START_STICKY;
}
public IBinder onUnBind(Intent arg0) {
Log.i(TAG, "onUnBind()");
return null;
}
public void onStop() {
Log.i(TAG, "onStop()");
}
public void onPause() {
Log.i(TAG, "onPause()");
x=player.getCurrentPosition();
player.pause();
}
#Override
public void onDestroy() {
if(player!=null) {
player.stop();
player.reset();
player.release();
Log.i(TAG, "onCreate() , service stopped...");
}
}
#Override
public void onLowMemory() {
Log.i(TAG, "onLowMemory()");
}
}
Despite Sticky and declaration in Manifest , it still doesnt work in background. Also I want to add pause button and I dont know exacly how can I do that.

Permission denied error when uploading image to server

In my app I'm trying to take a picture and send it over to the server coded as a String when I run it, I am able to take the picture but as soon as I click ok the app crashes and I get the following error:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/test123.jpeg: open failed: EACCES (Permission denied)
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: info.androidhive.loginandregistration, PID: 8775
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at info.androidhive.loginandregistration.activity.ImageActivity$Encode_image.doInBackground(ImageActivity.java:86)
at info.androidhive.loginandregistration.activity.ImageActivity$Encode_image.doInBackground(ImageActivity.java:79)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
Heres my code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.loginandregistration"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.Camera" android:required="true"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name="info.androidhive.loginandregistration.app.AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".activity.LoginActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activity.RegisterActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" />
<activity
android:name=".activity.MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop" />
<activity
android:name=".activity.test"
android:label="#string/app_name"
android:launchMode="singleTop" />
<activity
android:name=".activity.SearchActivity"
android:label="MY SICK APP"
android:launchMode="singleTop" />
<activity
android:name=".activity.ImageActivity"
android:label="MY SICK APP"
android:launchMode="singleTop"
android:largeHeap="true"/>
</application>
</manifest>
-
public class ImageActivity extends Activity{
final String URL = "linktophpfile";
private Button button;
private String coded_string, name;
private Bitmap bitmap;
private File file;
private Uri uri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_main);
button = (Button) findViewById(R.id.bt_main);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getUri();
i.putExtra(MediaStore.EXTRA_OUTPUT,uri);
startActivityForResult(i,5);
}
});
}
public void getUri() {
String name = "test123.jpeg";
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ file.separator + name);
uri = Uri.fromFile(file);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==5 && resultCode== RESULT_OK){
new Encode_image().execute();
}
}
private class Encode_image extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(uri.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
bitmap.recycle();
byte[] array = stream.toByteArray();
coded_string = Base64.encodeToString(array,0);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
makeRequest();
}
}
private void makeRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST,URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError{
HashMap<String, String> map = new HashMap<>();
map.put("coded_String", coded_string);
map.put("image_name", name);
return map;
}
};
queue.add(request);
}
}
php code:
<?php
header('Content-type : bitmap; charset=utf-8');
if(isset($_POST["encoded_string"])){
$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);
$path = 'images/'.$image_name;
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
if($is_written > 0) {
$connection = mysqli_connect('localhost', 'username', 'password','dbname');
$query = "INSERT INTO images(name,path) values('$image_name','$path');";
$result = mysqli_query($connection, $query) ;
if($result){
echo "success";
}else{
echo "failed";
}
mysqli_close($connection);
}
}
?>
Any ideas of what could be wrong? thanks
Make sure you have
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Declared in your manifest.xml file
1 check your app's permission states in phone settings.
2 Check this photo's real uri in debug mode.

Android Wear not receiving OnDataChanged call

I have read any thread that is on this topic in the last 2 days.. but I still cannot figure out what is wrong with my code.
I have Mobile and Wear app. the mobile has only widget and widgetconfig activities (no main activity).
Here is the mobile app files:
AndroidManifest: (simple appwidget and appwidget_config activities)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.xx.yy.remotedoor">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/housek"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".DoorConf"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
<receiver android:name=".upDoor">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/up_door_info" />
</receiver>
</application>
</manifest>
upDoor.java: (Look at send_to_wear function)
package net.xx.yy.remotedoor;
import ...
public class upDoor extends AppWidgetProvider {
public static String TAG = "Remote door GAPI";
public static String CLICK_DOOR = "ClickDoorOpen";
public static String DOOR_ID = "DoorID";
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
CharSequence widgetText = "Test";
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.up_door_widget);
views.setTextViewText(R.id.textView, widgetText);
Intent intent = new Intent(context, upDoor.class);
intent.setAction(CLICK_DOOR);
intent.putExtra(DOOR_ID, Integer.toString(appWidgetId));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.houseIcon, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
send_to_wear(context);
}
}
private static void send_to_wear(Context context) {
// Sending data to wear
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed: " + result);
}
})
.addApi(Wearable.API)
.build();
Log.w("Google API", "Connecting");
mGoogleApiClient.connect();
Log.w("Google API", Boolean.toString(mGoogleApiClient.isConnected()));
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/doors/1");
putDataMapReq.getDataMap().putString("caption", "test"); putDataMapReq.getDataMap().putLong("Time",System.currentTimeMillis());
putDataMapReq.setUrgent();
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
com.google.android.gms.common.api.ResultCallback<DataApi.DataItemResult> send_callback =
new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult result) {
if (!result.getStatus().isSuccess()) {
Log.w("Result", "Failed");
}else{
Log.w("Result", "Success");
}
Log.w("Item", result.getDataItem().getUri().toString());
Log.w("Reason", result.getStatus().getStatusMessage());
}
};
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
pendingResult.setResultCallback(send_callback);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onEnabled(Context context) {...}
#Override
public void onDisabled(Context context) {...}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(CLICK_DOOR)) {
send_to_wear(context);
}
}
}
On the Wear side:
Manifest: (I configured it at same package name, is that ok?)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.xx.yy.remotedoor">
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#drawable/housek"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name=".main"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".dataLayer" android:exported="false" android:enabled="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="*" />
</intent-filter>
</service>
</application>
</manifest>
and the dataLayer java part:
package net.xx.yy.remotedoor;
import ...
public class dataLayer extends WearableListenerService { //implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LOG";
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.w(TAG, "Wear got on_change");
final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
// Do I need it??
ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG, "Failed to connect to GoogleApiClient.");
return;
}
for (DataEvent dataEvent : events) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = dataEvent.getDataItem();
Log.w(TAG, "item path: " + item.getUri().getPath());
if(item.getUri().getPath().startsWith("/doors/")){
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
// Do something
}
}
}
}
}
On the mobile log I can see:
DataItemResult : Success
Item: wear://HOST_ID/doors/1
On the wear log I cannot see anything related to this..
What am I doing wrong!?
Thanks!!

Issue using TextureView with NDK

I'm working on a small piece of code using a TextureView to display the result of a MediaPlayer.
I'm facing an issue trying to mix managed code and native code using NDK.
If my Activity inherit from NativeActivity instead of Activity, my app is broken.
Is it a known limitation? Is it a related to the NDK glue?
Here is my Activity Code:
public class SurfaceActivity extends NativeActivity {
private static final boolean VERBOSE = true;
private static final String TAG = "native";
private static final String FILES_DIR = "/sdcard/";
private static final String INPUT_FILE = "video1.mp4";
TextureView mView = null;
MediaPlayer mPlayer = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
File inputFile = new File(FILES_DIR, INPUT_FILE);
mPlayer.setDataSource(inputFile.toString());
} catch(Exception e) {
Log.e(TAG, "File Exception", e);
}
FrameLayout content = new FrameLayout(this);
content.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
mView = new TextureView(this);
mView.setSurfaceTextureListener( new TextureViewListener( ) );
mView.setOpaque(false);
mView.setLayoutParams(new FrameLayout.LayoutParams(200, 200));
mView.setBackgroundColor(Color.TRANSPARENT);
content.addView(mView);
addContentView(content, content.getLayoutParams());
}
public class TextureViewListener implements TextureView.SurfaceTextureListener
{
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
Log.i(TAG,"onSurfaceTextureAvailable");
mPlayer.setSurface(new Surface(surface));
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return true;
}
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
}
And C++ side:
#include <jni.h>
#include <errno.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#include <android/native_window_jni.h>
void android_main( android_app* state )
{
app_dummy();
__android_log_print(ANDROID_LOG_INFO, "native-lib", "android_main");
}
Finally in the manifest:
android:hardwareAccelerated="true"
EDIT:
Ok, after reading the logcat, it seem that the TextureView is not created:
W/TextureView( 571): A TextureView or a subclass can only be used with hardware acceleration enabled.
Complete manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sample.surfaceview" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="19" />
<uses-feature android:glEsVersion="0x00020000">
</uses-feature>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
<application android:allowBackup="true" android:icon="#drawable/ic_launcher" android:label="#string/app_name" android:theme="#style/AppTheme" android:hasCode="true" android:hardwareAccelerated="true" android:debuggable="true">
<activity android:name="com.sample.surfaceview.SurfaceActivity" android:hardwareAccelerated="true" android:label="#string/app_name" android:configChanges="orientation|keyboardHidden">
<!-- Tell NativeActivity the name of or .so -->
<meta-data android:name="android.app.lib_name" android:value="native" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

ERROR/dalvikvm(1399): Could not find class 'maptest.xyz.com.maps', referenced from method maptest.xyz.com.maptest$1.onClick

The problem is that if i use these two lines of code,my app closes unxepectedly and if not used, the app works just fine...is there any other way to get to the maps.class?
The following is the code i used:
Intent in = new Intent(BlobCity.this, maps.class)
startActivity(in);
the following is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="BlobCity.xyz.com"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-library android:name="com.google.android.maps" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".BlobCity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".maps" />
</application>
</manifest>
blobcity.java:
public class BlobCity extends Activity
{
/** Called when the activity is first created. */
Button signIn,register;
TextView Blob,City,username,password;
EditText eUsername,ePassword;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
signIn = (Button) findViewById(R.id.signIn);
register = (Button) findViewById(R.id.register);
Blob = (TextView) findViewById(R.id.blob);
City = (TextView) findViewById(R.id.city);
username = (TextView) findViewById(R.id.username);
password = (TextView) findViewById(R.id.password);
eUsername = (EditText) findViewById(R.id.eUsername);
ePassword = (EditText) findViewById(R.id.ePassword);
signIn.setOnClickListener(new sendUserPass());
register.setOnClickListener(new regPage());
}
class sendUserPass implements Button.OnClickListener
{
public void onClick(View v)
{
String uname = eUsername.getText().toString();
String pwd = ePassword.getText().toString();
String requestString = ("http://192.168.1.102:8080/BlobCity/RemoteLogin?email="+ uname + "&pwd=" + pwd);
String line;
try {
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(requestString));
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder rb = new StringBuilder("");
while ((line=br.readLine()) != null)
{
rb.append(line) ;
}
if(rb.toString().equals("0"))
{
Toast toast = Toast.makeText(getApplicationContext(), "Please enter a valid Username and/or Password!", Toast.LENGTH_LONG);
toast.show();
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
eUsername.setText("");
ePassword.setText("");
}
else
{
Intent in = new Intent(BlobCity.this, maps.class);
startActivity(in);
eUsername.setText("");
ePassword.setText("");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class regPage implements Button.OnClickListener
{
public void onClick(View v)
{
Intent browse = new Intent( Intent.ACTION_VIEW , Uri.parse("http://www.blobcity.com") );
startActivity(browse);
}
}
}
maps.java:
import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
public class maps extends MapActivity{
MapView mapView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
mapView = (MapView) findViewById(R.id.map);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Your tag <uses-library android:name="com.google.android.maps" /> has to be inside the <application> tag!
manifest has to be like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="BlobCity.xyz.com"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
**<uses-library android:name="com.google.android.maps" />**
<activity android:name=".BlobCity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".maps" />
</application>
</manifest>
Try:
Intent in = new Intent(BlobCity.this.getApplicationContext(), maps.class)
startActivity(in);
Activity (Class) name must start with capital letter, and instead of using BlobCity.this use only "this" keyword which refers the Context of the current Activity
e.g.
Intent in = new Intent(this, Maps.class)
startActivity(in);
also make sure entry of this Activity must be in your AndroidManifest.xml file
e.g.
<activity android:name=".Maps"></activity>
also you can follow a great tutorial on Android Google Maps here :
http://mobiforge.com/developing/story/using-google-maps-android

Categories