Sharing Image Using Intent on whats app getting error sharing failed - java

I am loading single jpg image from drawable folder set file provider permission in manifest but when i share image on whatsapp i got error sharing failed please try again.When i share text it works fine but when i tried to share image it gives me error.Here is following files
Fullscreenadapter.java
package com.mobdev.birthdaycakesquotes;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ShareCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Fullscreenadapter extends PagerAdapter {
private Integer[] Image;
private int _resource;
private Activity _activity;
private LayoutInflater inflater;
private String images;
TextView t1,t2;
public Fullscreenadapter(Activity activity,
Integer[] image) {
this._activity = activity;
this.Image=image;
}
#Override
public int getCount() {
return this.Image.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final ImageView imgDisplay,shareimage;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.fullscreenlayoutdesign,
container,
false);
imgDisplay = (ImageView) viewLayout.findViewById(R.id.show);
shareimage=(ImageView)viewLayout.findViewById(R.id.share);
t1=(TextView)viewLayout.findViewById(R.id.currentposition);
t2=(TextView)viewLayout.findViewById(R.id.totalimage);
imgDisplay.setImageResource(Image[position]);
t1.setText(String.valueOf(position));
t2.setText(String.valueOf(Image.length));
images=createImageOnSDCard(R.drawable.sw);
shareimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri path = FileProvider.getUriForFile(_activity,
"com.mobdev.birthdaycakesquotes",new File(images));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "This is one image I'm
sharing.");
shareIntent.putExtra(Intent.EXTRA_STREAM, path);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("image/*");
_activity.startActivity(Intent.createChooser(shareIntent,
"Share..."));
}
});
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
private String createImageOnSDCard(int resID) {
Bitmap bitmap = BitmapFactory.decodeResource(Resources.getSystem(), resID);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + resID + ".jpg";
File file = new File(path);
try {
OutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getPath();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
AndroidManifestfile
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobdev.birthdaycakesquotes">
<application
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomePage"
android:label="#string/title_activity_home_page"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" />
<activity android:name=".Details_activity"></activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mobdev.birthdaycakesquotes"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="." />
</paths>

private void shareImage(Uri imagePath) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
sharingIntent.setType("image/*");
sharingIntent.putExtra(Intent.EXTRA_STREAM, imagePath);
//sharingIntent.setPackage("com.whatsapp"); for whatsapp only
startActivity(Intent.createChooser(sharingIntent, "Share Image Using"));// for all generic options
}
Finaly in your manifest Add this without fail
<activity
android:name=".YourActivity"
android:icon="#drawable/share_this"
android:label="#string/shared_activity" >
<intent-filter>
<action android:name="android.intent.action.SEND" /> <!-- Send
action required to display activity in share list -->
<category android:name="android.intent.category.DEFAULT" /> <!--
Make activity default to launch -->
<!-- Mime type i.e. what can be shared with this activity only image and text -->
<data android:mimeType="image/*" />
<data android:mimeType="text/*" />
</intent-filter>
</activity>
This will owrk

ArrayList<Uri> uriArrayList = new ArrayList<>();
uriArrayList.add(getUriFromFile(your file path))
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.setType("image/*");
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, myFilesUriList);
startActivity(intent);
public Uri getUriFromFile(File theSrcPath) {
Uri requirdUri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
requirdUri = FileProvider.getUriForFile(theCtx,
theCtx.getApplicationContext().getPackageName() + PROVIDER_FILE_EXTENSION,
theSrcPath);
} else {
requirdUri = Uri.fromFile(theSrcPath);
}
}

Related

How do I fix Android Image Capture App Crashes

I'm not sure what is going on. I click the button to take the image and my app closes.
I'm attempting to make an app to capture and use an image. I haven't even been able to capture the image.
I get the following message in log cat:
FATAL EXCEPTION: main
Process: com.example.fixmyphysics, PID: 23526
java.lang.IllegalArgumentException: Missing android.support.FILE_PROVIDER_PATHS meta-data
at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:613)
at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
at com.example.fixmyphysics.MainActivity.dispatchPictureTakerAction(MainActivity.java:67)
at com.example.fixmyphysics.MainActivity.access$000(MainActivity.java:27)
at com.example.fixmyphysics.MainActivity$1.onClick(MainActivity.java:44)
at android.view.View.performClick(View.java:7356)
at android.widget.TextView.performClick(TextView.java:14230)
at android.view.View.performClickInternal(View.java:7322)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27804)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7073)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
MainActivity.java
package com.example.fixmyphysics;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.os.Environment.getExternalStoragePublicDirectory;
public class MainActivity extends AppCompatActivity {
Button picture_btn;
ImageView display;
String pathToFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
picture_btn = findViewById(R.id.capture_image);
if (Build.VERSION.SDK_INT >=23){
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
picture_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchPictureTakerAction();
}
});
display = findViewById(R.id.imageView4);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
Bitmap imageBitmap = BitmapFactory.decodeFile(pathToFile);
display.setImageBitmap(imageBitmap);
}
}
private void dispatchPictureTakerAction(){
Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) !=null){
File photoFile = null;
photoFile = createImageFile();
if (photoFile != null){
pathToFile = photoFile.getAbsolutePath();
Uri photoURI = FileProvider.getUriForFile(MainActivity.this, "com.fixmyphysics.FileProvider", photoFile);
takePic.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePic, 1);
}
}
}
private File createImageFile() {
String name = new SimpleDateFormat("yyyyMMdd__HHmmss").format(new Date());
File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = null;
try {
image = File.createTempFile(name,".jpg", storageDir);
} catch (IOException e){
Log.d("mylog", "Excep : " + e.toString());
}
return image;
}
}
AndroidMainifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fixmyphysics">
<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.CAMERA" />
<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="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
</provider>
</application>
</manifest>
Try this one.
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />`enter code here`

onActivityResult is not getting called in MainActivity.Java

I am trying to make an app which shows a user selected image which can be set by double-clicking on the button. The app does ask me for an image (which is good) but I don't know how to set it on ImageView if this onActivityResult is not getting called.
MainActivity:
package com.forever.bobby.cheater20;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.tomerrosenfeld.customanalogclockview.CustomAnalogClock;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE = 100;
Button hiddenOnClickListener;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = findViewById(R.id.imageView);
CustomAnalogClock customAnalogClock = (CustomAnalogClock) findViewById(R.id.analog_clock);
customAnalogClock.setAutoUpdate(true);
hiddenOnClickListener = (Button) findViewById(R.id.touchButtonHidden);
hiddenOnClickListener.setOnClickListener(new DoubleClickListener() {
#Override
public void onSingleClick(View v) {
Log.e ("mPressesOnce -_-","..");
}
#Override
public void onDoubleClick(View v) {
Log.e ("mPressesTwice -_-","..");
openGallery();
}
});
}
private void openGallery () {
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, 0);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode,data);
Log.e ("SHould Be Steeted","");
if (requestCode == 0) {
Uri imgUri;
imgUri = data.getData();
// img.setImageURI(imgUri);
}
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.forever.bobby.cheater20">
<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>
</manifest>
Any Kind of help is appreciated as I am a newbie
With android sdk >= 23, some permissions e.g. WRITE_EXTERNAL_STORE, READ_EXTERNAL_STORE, etc. you must request it in java code.
Therefore, when user starts using feature need permission, android will show a dialog and user can grant or cancel a permission. You can read more about it on developer.android.com.

I have created an android app for blocking the number from calling when a button is pressed

I have added the ITelephony.aidl file in the src folder with the package name as package com.android.internal.telephony. The below code is the PhoneCallStateListener.java
package com.broad.sowmy.blockingcall;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import java.lang.reflect.Method;
import com.android.internal.telephony.ITelephony;
/**
* Created by sowmy on 24-10-2016.
*/
public class PhoneCallStateListener extends PhoneStateListener {
private Context context;
String block_num;
SharedPreferences shared;
public PhoneCallStateListener(Context context){
this.context = context;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
shared=context.getSharedPreferences("get",Context.MODE_PRIVATE);
block_num=shared.getString("number",null);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamMute(AudioManager.STREAM_RING, true);
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Toast.makeText(context, block_num, Toast.LENGTH_SHORT).show();
Class clazz = Class.forName(tm.getClass().getName());
Method method = clazz.getDeclaredMethod("getITelephony");
method.setAccessible(true);
ITelephony telephonyService = (ITelephony) method.invoke(tm);
System.out.println("Call " + block_num);
if (incomingNumber.equalsIgnoreCase("+91" + block_num)) {
telephonyService = (ITelephony) method.invoke(tm);
telephonyService.silenceRinger();
System.out.println(" in " + block_number);
telephonyService.endCall();
}
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
//Turn OFF the mute
audioManager.setStreamMute(AudioManager.STREAM_RING, false);
break;
case PhoneStateListener.LISTEN_CALL_STATE:
}
super.onCallStateChanged(state, incomingNumber);
}
}
PhoneCallReceiver.java is below
package com.broad.sowmy.blockingcall;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
/**
* Created by sowmy on 24-10-2016.
*/
public class PhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneCallStateListener phoneCallStateListener=new PhoneCallStateListener(context);
tm.listen(phoneCallStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
Mainfest file is as below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broad.sowmy.blockingcall">
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE">
</uses-permission>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"></uses-permission>
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<receiver android:name=".PhoneCallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
</application>
</manifest>
And in ITelephony.aidl
package com.android.internal.telephony;
public interface ITelephony {
boolean endCall();
void answerRingingCall();
void silenceRinger();
}
Make com/android/internal/telephony folder structure inside src folder and put ITelephony.aidl file inside the telephony folder.

how to give sharing option to the grid images

i am creating an application which i want share images to any social platform.
i used a grid view successfully, which shows all the images and can be viewed in specific full image activity to show the user selected image.
i want to add a social share function to the applications which get the image location and share to the social platform.
Here is my MainActivity.java
package com.jai.desimeme;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
with my activity_main.XML
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:gravity="center"
android:horizontalSpacing="5dp"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp" >
</GridView>
i used the FullImageActivity.java for the preview of image selected //here i want to add the sharing link.
package com.jai.desimeme;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.MenuItem;
import android.widget.ImageView;
#SuppressLint("SdCardPath")
public class FullImageActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
File sd = Environment.getExternalStorageDirectory();
String fileName = "test.png";
File dest = new File(sd, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch (item.getItemId()) {
case R.id.item:
Uri uri = Uri.fromFile(dest);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
for above code i used this full_image.xml activity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/full_image_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ImageView android:id="#+id/full_image_view"
android:layout_width="100dp" android:layout_height="100dp"
android:src="#drawable/image_border"
style="#style/myImageView" />
</LinearLayout>
in here i created ImageAdapter.java to store the image files.
package com.jai.desimeme;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.rage_0001,
...
R.drawable.rage_178,
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
and here is my AndroidManifest.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jai.desimeme"
android:versionCode="1"
android:versionName="1.1.3" android:installLocation="auto">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:permission="android.permission.WRITE_EXTERNAL_STORAGE">
<activity
android:name="com.jai.desimeme.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<!-- FullImageActivity -->
<activity android:name=".FullImageActivity"></activity>
<activity android:name=".About" android:theme="#android:style/Theme.Dialog"> </activity>
</application>
guide me how to add sharing link to this application, i tried so many ways but end up in errors.
You can use this on any click event of your UI element.
BitmapDrawable bm = (BitmapDrawable) yourImageView.getDrawable();
Bitmap mysharebmp = bm.getBitmap();
String path = Images.Media.insertImage(getContentResolver(),
mysharebmp, "MyImage", null);
Uri uri = Uri.parse(path);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent,
"Share image using"));

Android NFC not opening correct class on tap

I have an app with 2 classes, I need my app to open the second class CardActivity when the NFC tag tapped/swiped. The app opens fine, but MainActivity is run, instead of CardActivity.
I would hazard a guess that this is an issue with my manifest, but it looks correct. Here it is regardless:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spotsofmagic.spotsofmagic"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<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>
<activity
android:name=".CardActivity"
android:label="#string/app_name" >
<!-- Handle a collectable card NDEF record -->
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<data android:mimeType="application/vnd.spotsofmagic.spotsofmagic"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
I'm confident the tag itself is correct, as I have opened it in another app to view it's contents.
Below are the two classes.
CardActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.bluetooth.*;
public class CardActivity extends Activity implements OnClickListener {
private static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.card_activity);
// see if app was started from a tag and show game console
Intent intent = getIntent();
Log.e(TAG, "Hello world. Intent Type: "+ intent.getType());
if(intent.getType() != null && intent.getType().equals(MimeType.NFC_DEMO)) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
NdefRecord cardRecord = msg.getRecords()[0];
String payload = new String(cardRecord.getPayload());
turnBluetoothOn(payload);
}
}
private void turnBluetoothOn(String payload) {
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Alert Dialog");
builder.setMessage(payload);
builder.setIcon(android.R.drawable.ic_dialog_alert);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
android.os.Process.killProcess(android.os.Process.myPid());
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
MainActivity:
package com.spotsofmagic.spotsofmagic;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "Activity...";
private NfcAdapter mAdapter;
private TextView mTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// grab our NFC Adapter
mAdapter = NfcAdapter.getDefaultAdapter(this);
// TextView that we'll use to output messages to screen
mTextView = (TextView)findViewById(R.id.text_view);
displayMessage("Loading payload...");
}
private void displayMessage(String message) {
mTextView.setText(message);
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Here is the code I used to write the tag. This is done on a different app incidentally:
NdefRecord appRecord = NdefRecord.createApplicationRecord("com.spotsofmagic.spotsofmagic");
// record that contains our custom "retro console" game data, using custom MIME_TYPE
byte[] payload = getPayload().getBytes();
byte[] mimeBytes = MimeType.NFC_DEMO.getBytes(Charset.forName("US-ASCII"));
NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes,
new byte[0], payload);
NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord, appRecord});
// Some code here removed for readability
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
ndef.writeNdefMessage(message);
Does the NDEF message on the tag contain an Android Application Record? That could explain how MainActivity is launched. However, that can only be the cause if the AAR is the first record of the NDEF message on the tag or if the first record does not match the intent filter.

Categories

Resources