So I'm making a soundboard app and I'm trying to implement saving sounds as notifications. The problem, however, is that the app crashes as soon as the user confirms saving as notification.
Heres what I have so far:
private OnItemLongClickListener longClickListener = new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v,
final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
CharSequence[] menu = new CharSequence[1];
menu[0] = "Notification";
// menu[1] = "Ringtone";
builder.setTitle("Save As...").setItems(menu,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
if (saveAsNotification(getSounds()
.get(position))) {
Toast.makeText(getActivity(),
"Saved as Notification",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),
"Failed to Save Notification",
Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
});
builder.create().show();
return true;
}
};
public boolean saveAsNotification(Sound sound) {
byte[] buffer = null;
InputStream fIn = getActivity().getBaseContext().getResources()
.openRawResource(sound.getSoundResourceId());
int size = 0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
String path = Environment.getExternalStorageDirectory().getPath()
+ "/media/audio/notifications/";
String filename = sound.getDescription() + ".ogg";
boolean exists = (new File(path)).exists();
if (!exists) {
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path + filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.parse("file://" + path + filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, sound.getDescription());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "soundboarder");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
// Insert it into the database
getActivity().getContentResolver()
.insert(MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath()), values);
return true;
}
Here's the logcat output when it crashes:
10-21 18:56:54.315: W/ResourceType(19905): No known package when getting value for resource number 0xffffffff
10-21 18:56:54.315: D/AndroidRuntime(19905): Shutting down VM
10-21 18:56:54.315: W/dalvikvm(19905): threadid=1: thread exiting with uncaught exception (group=0x41510ba8)
10-21 18:56:54.315: E/AndroidRuntime(19905): FATAL EXCEPTION: main
10-21 18:56:54.315: E/AndroidRuntime(19905): Process: com.metrico.trailerparkboyssoundboard, PID: 19905
10-21 18:56:54.315: E/AndroidRuntime(19905): android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.getValue(Resources.java:1123)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.openRawResource(Resources.java:1038)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.openRawResource(Resources.java:1015)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.metrico.trailerparkboyssoundboard.fragments.SoundboardFragment.saveAsNotification(SoundboardFragment.java:130)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.metrico.trailerparkboyssoundboard.fragments.SoundboardFragment$1$1.onClick(SoundboardFragment.java:106)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:941)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView$3.run(AbsListView.java:3638)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Handler.handleCallback(Handler.java:733)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Handler.dispatchMessage(Handler.java:95)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Looper.loop(Looper.java:136)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-21 18:56:54.315: E/AndroidRuntime(19905): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 18:56:54.315: E/AndroidRuntime(19905): at java.lang.reflect.Method.invoke(Method.java:515)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-21 18:56:54.315: E/AndroidRuntime(19905): at dalvik.system.NativeStart.main(Native Method)
The dialogue box pops of fine, but as soon as I click on "save as notification", the app crashes.
I think that this part of the code causes the error
InputStream fIn = getActivity().getBaseContext().getResources().openRawResource(sound.getSoundResourceId());
The error message says you are trying to open the resource with the ID -1, make sure getSoundResourceId() returns the correct ID number.
Related
After my tablet update to 4.4.2 my app crashes.
My log says at com.example.androidhive.EditProductActivity$6.onClick(EditProductActivity.java:344)
and the line is
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
This is a part off my code (the bitmap code)
#Override
public void onClick(View v) {
btn_shoot.setVisibility(View.INVISIBLE);
View view = findViewById(R.id.relativelayout);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setBackgroundDrawable(bitmapDrawable);
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//we check if external storage is available, otherwise display an error message to the user
File sdCard = Environment.getExternalStorageDirectory();
// .getExternalStorageDirectory() + "/Indflyt/ "+ inputNr.getText().toString() + ".pdf";
File directory = new File (sdCard.getAbsolutePath() + "/Indflyt");
directory.mkdirs();
String filename = inputNr.getText().toString() + "-"+ txtetDate.getText().toString() +".jpg";
File yourFile = new File(directory, filename);
while (yourFile.exists()) {
i++;
filename = "screenshot" + i + ".jpg";
yourFile = new File(directory, filename);
}
if (!yourFile.exists()) {
if (directory.canWrite())
{
try {
FileOutputStream out = new FileOutputStream(yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(EditProductActivity.this, "Billede gemt i /sdcard/Indflyt/" + inputNr.getText().toString() + "-" + txtetDate.getText().toString() + ".jpg", Toast.LENGTH_SHORT).show();
i++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
else
{
Toast.makeText(EditProductActivity.this, "SD Card not available!", Toast.LENGTH_SHORT).show();
}
}
});
and my log
11-26 11:43:33.413: E/AndroidRuntime(24275): FATAL EXCEPTION: main
11-26 11:43:33.413: E/AndroidRuntime(24275): Process: com.example.androidhive, PID: 24275
11-26 11:43:33.413: E/AndroidRuntime(24275): java.lang.NullPointerException
11-26 11:43:33.413: E/AndroidRuntime(24275): at com.example.androidhive.EditProductActivity$6.onClick(EditProductActivity.java:344)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.view.View.performClick(View.java:4630)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.view.View$PerformClick.run(View.java:19340)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.os.Handler.handleCallback(Handler.java:733)
11-26 11:43:33.413: E/AndroidRuntime(24275): at andrid.os.Handler.dispatchMessage(Handler.java:95)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.os.Looper.loop(Looper.java:157)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.app.ActivityThread.main(ActivityThread.java:5377)
11-26 11:43:33.413: E/AndroidRuntime(24275): at java.lang.reflect.Method.invokeNative(Native Method)
11-26 11:43:33.413: E/AndroidRuntime(24275): at java.lang.reflect.Method.invoke(Method.java:515)
11-26 11:43:33.413: E/AndroidRuntime(24275): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
11-26 11:43:33.413: E/AndroidRuntime(24275): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
11-26 11:43:33.413: E/AndroidRuntime(24275): at dalvik.system.NativeStart.main(Native Method)
Any help?
Update
View view = findViewById(R.id.relativelayout);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
ImageView iv = (ImageView) findViewById(R.id.imageView1);
Drawable bitmapDrawable = null;
iv.setBackground(bitmapDrawable);
I want to create a simple database for my android application in sqlite. I just want to add my values to the table.
This is my code but this is not working for me because the table is not shown at DDMS.
public class QuickSubmitContext extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "submitManager";
private static final String TABLE_CONTACTS = "submit";
private static final String KEY_ID = "id";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_DNCA = "donotca";
private static final String KEY_CA = "callagain";
private static final String KEY_NOTE = "note";
public QuickSubmitContext(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_PH_NO + " TEXT,"
+ KEY_DNCA + " TEXT," + KEY_CA + " TEXT," + KEY_NOTE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
}
Logcat
10-21 04:39:00.230: E/AndroidRuntime(835): FATAL EXCEPTION: main
10-21 04:39:00.230: E/AndroidRuntime(835): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aspeage.quikw/com.aspeage.quikw.FragmentLayout}: java.lang.NullPointerException
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.os.Handler.dispatchMessage(Handler.java:99)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.os.Looper.loop(Looper.java:137)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-21 04:39:00.230: E/AndroidRuntime(835): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 04:39:00.230: E/AndroidRuntime(835): at java.lang.reflect.Method.invoke(Method.java:511)
10-21 04:39:00.230: E/AndroidRuntime(835): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-21 04:39:00.230: E/AndroidRuntime(835): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-21 04:39:00.230: E/AndroidRuntime(835): at dalvik.system.NativeStart.main(Native Method)
10-21 04:39:00.230: E/AndroidRuntime(835): Caused by: java.lang.NullPointerException
10-21 04:39:00.230: E/AndroidRuntime(835): at com.aspeage.quikw.FragmentLayout.onCreate(FragmentLayout.java:79)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.Activity.performCreate(Activity.java:5104)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-21 04:39:00.230: E/AndroidRuntime(835): ... 11 more
10-21 04:39:07.090: I/Process(835): Sending signal. PID: 835 SIG: 9
10-21 04:39:13.050: E/Trace(866): error opening trace file: No such file or directory (2)
The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database. For example:
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
Here are instructions. http://developer.android.com/guide/topics/data/data-storage.html#db
i am trying to upload selected image to dropbox from gallery.I am being stuck up from days because i am getting unable to resume Runtime Exception
My onActivityResult() is
if(requestCode == PIC_UPLOAD) {
System.out.println("Reahced 1");
Uri selectedImage = data.getData();
String[] filePathColumn ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null); cursor.moveToFirst();
System.out.println("Reahced 2");
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Uri imageUri=data.getData();
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("image", imageUri.getPath()));
System.out.println("Reahced 3");
/* String outPath = imageUri.toString(); File outFile = new
File(outPath); FileInputStream fis = new FileInputStream(outFile);
mDBApi.putFileOverwriteRequest("/Pic1", fis, outFile.length(),null);
*/
Uri photoUri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA };
Cursor actualimagecursor = managedQuery(photoUri, proj,null, null, null);
int actual_image_column_index =
actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path =actualimagecursor.getString(actual_image_column_index);
System.out.println("Image location: " + img_path);
System.out.println("Reached 1");
uploadDropbox(img_path);
}
And uploadDropbox body is:
private void uploadDropbox(String URL) {
// TODO Auto-generated method stub
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
System.out.println(URL);
System.out.println("Reahced 4");
mDBApi.getSession().startAuthentication(MyCamActivity.this);
System.out.println("Reahced 5");
// AccessTokenPair access = getStoredKeys();
// mDBApi.getSession().setAccessTokenPair(access);
FileInputStream inputStream = null;
try {
File file = new File(URL.toString());
inputStream = new FileInputStream(file);
com.dropbox.client2.DropboxAPI.Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
}
onResume method body:
protected void onResume() {
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// MANDATORY call to complete auth.
// Sets the access token on the session
mDBApi.getSession().finishAuthentication();
AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair();
// Provide your own storeKeys to persist the access token pair
// A typical way to store tokens is using SharedPreferences
storeKeys(tokens.key, tokens.secret);
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
private AccessTokenPair getStoredKeys() {
// TODO Auto-generated method stub
return mDBApi.getSession().getAccessTokenPair();
}
private void storeKeys(String key, String secret) {
// TODO Auto-generated method stub
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
AndroidManifest.xml
<activity
android:name="com.dropbox.client2.android.AuthActivity"
android:launchMode="singleTask"
android:configChanges="orientation|keyboard">
<intent-filter>
<!-- Change this to be db- followed by your app key -->
<data android:scheme="db-MyKey" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MyCamActivity"
android:label="#string/app_name"
android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"
android:uiOptions="splitActionBarWhenNarrow"
android:clearTaskOnLaunch="true"
>
Error**:
01-23 14:58:00.855: D/dalvikvm(4238): GC_FOR_ALLOC freed 104K, 2% free 12729K/12935K, paused 16ms
01-23 14:58:00.894: I/System.out(4238): Its not null
01-23 14:58:00.901: D/AndroidRuntime(4238): Shutting down VM
01-23 14:58:00.901: W/dalvikvm(4238): threadid=1: thread exiting with uncaught exception (group=0x40a511f8)
01-23 14:58:00.901: E/AndroidRuntime(4238): FATAL EXCEPTION: main
01-23 14:58:00.901: E/AndroidRuntime(4238): java.lang.RuntimeException: Unable to resume activity {cam.pack/cam.pack.MyCamActivity}: java.lang.NullPointerException
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2444)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2472)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.os.Looper.loop(Looper.java:137)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-23 14:58:00.901: E/AndroidRuntime(4238): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:58:00.901: E/AndroidRuntime(4238): at java.lang.reflect.Method.invoke(Method.java:511)
01-23 14:58:00.901: E/AndroidRuntime(4238): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-23 14:58:00.901: E/AndroidRuntime(4238): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-23 14:58:00.901: E/AndroidRuntime(4238): at dalvik.system.NativeStart.main(Native Method)
01-23 14:58:00.901: E/AndroidRuntime(4238): Caused by: java.lang.NullPointerException
01-23 14:58:00.901: E/AndroidRuntime(4238): at cam.pack.MyCamActivity.onResume(MyCamActivity.java:571)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1154)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.Activity.performResume(Activity.java:4539)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2434)
01-23 14:58:00.901: E/AndroidRuntime(4238): ... 12 more
I have made a mistake, i have put dropbox session in my own defined function uploadDropbox(), and thats a an error causes NullPointerException, because if i print mDBApi so its NULL. Its not been intialized. We have to put these lines in onCreate() and now its working, images are uploading in CameraUploads folder in Dropbox.
Thanks for comments.
Thanks to the replies on NFC and a few certain things, I've understood and managed to compile a code in which the users will be able to read a tag, and if the tag contains a string that is similar to my code, a coupon will be added (image changes) and an integer goes up by 1. This integer will be saved by SharedPreferences and it is used to determine how many coupons the users have collected and show it onResume.
However, after compiling, when I try to run it, my application stops immediately. Can someone help me check on what I may have go wrong? I know it's kinda long but I really have no idea what went wrong.
#TargetApi(10)
//I have to use this line of code because I'm targetted to code at API 8 but some NFC functionalities that I use requires API 10.
public class CouponManager extends Activity {
private static final String TAG = "NFCReadTag";
private NfcAdapter mNfcAdapter;
private IntentFilter[] mNdefExchangeFilters;
private PendingIntent mNfcPendingIntent;
public static final String PREF_FILE_NAME = "PrefFile";
private int[] images = new int[10];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coupon_layout);
//List of images
images[0]=R.drawable.cp0;
images[1]=R.drawable.cp1;
images[2]=R.drawable.cp2;
images[3]=R.drawable.cp3;
images[4]=R.drawable.cp4;
images[5]=R.drawable.cp5;
images[6]=R.drawable.cp6;
images[7]=R.drawable.cp7;
images[8]=R.drawable.cp8;
images[9]=R.drawable.cp9;
images[10]=R.drawable.cp10;
//Restore preferences
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
//Image to use depending on coupon collected
final ImageView img = new ImageView(this);
if(storedPreference!=10)
{
img.setImageResource(images[storedPreference]);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
}
});
}
//Check and send Intent from NFC tag discovered
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
IntentFilter coupontag = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
coupontag.addDataScheme("http");
coupontag.addDataAuthority("www.ichatime.com", null);
coupontag.addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);
mNdefExchangeFilters = new IntentFilter[] { coupontag };
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
if(mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,
mNdefExchangeFilters, null);
} else {
Toast.makeText(getApplicationContext(), "Sorry, No NFC Adapter found.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onPause();
if(mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this);
}
#Override
protected void onStop() {
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] messages = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
messages = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
messages[i] = (NdefMessage) rawMsgs[i];
}
}
if(messages[0] != null) {
String result="";
byte[] payload = messages[0].getRecords()[0].getPayload();
// this assumes that we get back am SOH followed by host/code
for (int b = 1; b<payload.length; b++) { // skip SOH
result += (char) payload[b];
}
if (result == "ichatime.com")
{
final ImageView img = new ImageView(this);
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
if (storedPreference!=10)
{
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
img.setImageResource(images[storedPreference]);
}
if (storedPreference==10)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
}
});
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 10);
img.setImageResource(images[10]);
}}
else
{
Toast.makeText(getApplicationContext(), "Wrong tag detected!", Toast.LENGTH_SHORT).show();
}
//Debugging Mode to see what is contained in the tags.
// Toast.makeText(getApplicationContext(), "Tag Contains " + result, Toast.LENGTH_SHORT).show();
}
}
}
}
Logcat errors:
>11-26 01:16:11.869: D/AndroidRuntime(550): Shutting down VM
>
11-26 01:16:11.869: W/dalvikvm(550): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
>
11-26 01:16:11.929: I/dalvikvm(550): threadid=3: reacting to signal 3
>
11-26 01:16:11.979: E/AndroidRuntime(550): FATAL EXCEPTION: main
>
**11-26 01:16:11.979: E/AndroidRuntime(550): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.MainActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.CouponManager}: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10**
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.access$600(ActivityThread.java:123)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.os.Handler.dispatchMessage(Handler.java:99)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.os.Looper.loop(Looper.java:137)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.main(ActivityThread.java:4424)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at java.lang.reflect.Method.invokeNative(Native Method)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at java.lang.reflect.Method.invoke(Method.java:511)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at dalvik.system.NativeStart.main(Native Method)
>
11-26 01:16:11.979: E/AndroidRuntime(550): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.CouponManager}: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1797)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:682)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost.setCurrentTab(TabHost.java:346)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost.addTab(TabHost.java:236)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.example.ponpon.MainActivity.onCreate(MainActivity.java:37)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Activity.performCreate(Activity.java:4465)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
>
11-26 01:16:11.979: E/AndroidRuntime(550): ... 11 more
>
11-26 01:16:11.979: E/AndroidRuntime(550): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.example.ponpon.CouponManager.onCreate(CouponManager.java:53)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Activity.performCreate(Activity.java:4465)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
>
11-26 01:16:11.979: E/AndroidRuntime(550): ... 21 more
What did I do wrong with my arrays? Thanks for the clarification guys!
Your logcat is printing an ArrayOutOfBounds exception on your onCreate method.
The problem is that you are declaring a 10 items sized array, and then trying to put 11 items on it.
You have to declare a new int[11] array.
I seem to have solved the problem by adding the array count by 1. What I don't understand is, I want to keep 11 items in the array so isn't
private int[] images = new int[10] enough?
Cause from what I understand, int[0] keeps the first value, hence int[10] will keep the eleventh value? Thank you guys!
Getting java.lang.RuntimeException: Failure delivering result ResultInfo from a NPE apparently resulting from a call in my getRealPathFromURI function.
Video capture works fine, but image capture throws the NPE. Both image and video work fine on my Evo.
03-30 09:34:25.725 D/ZoorniApp( 2509): Handling activity result. requestCode:12345 resultCode:-1
03-30 09:34:25.733 D/AndroidRuntime( 2509): Shutting down VM
03-30 09:34:25.733 W/dalvikvm( 2509): threadid=3: thread exiting with uncaught exception (group=0x4001e2e0)
03-30 09:34:25.733 E/AndroidRuntime( 2509): Uncaught handler: thread main exiting due to uncaught exception
03-30 09:34:25.741 E/AndroidRuntime( 2509): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=12345, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.mobile.zoorni/com.mobile.zoorni.ZoorniMobile}: java.lang.NullPointerException
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.deliverResults(ActivityThread.java:3391)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3433)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.access$2900(ActivityThread.java:121)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.os.Handler.dispatchMessage(Handler.java:99)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.os.Looper.loop(Looper.java:136)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.main(ActivityThread.java:4425)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at java.lang.reflect.Method.invokeNative(Native Method)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at java.lang.reflect.Method.invoke(Method.java:521)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at dalvik.system.NativeStart.main(Native Method)
03-30 09:34:25.741 E/AndroidRuntime( 2509): Caused by: java.lang.NullPointerException
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.content.ContentResolver.acquireProvider(ContentResolver.java:757)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.content.ContentResolver.query(ContentResolver.java:200)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.Activity.managedQuery(Activity.java:1495)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at com.mobile.zoorni.ZoorniMobile.getRealPathFromURI(ZoorniMobile.java:287)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at com.mobile.zoorni.ZoorniMobile.onActivityResult(ZoorniMobile.java:251)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.Activity.dispatchActivityResult(Activity.java:3828)
03-30 09:34:25.741 E/AndroidRuntime( 2509): at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
Here's the relevant function:
public String getRealPathFromURI(Uri contentUri) {
String column;
column = "";
if (fileType == "picture") {
column = MediaStore.Images.Media.DATA;
}
if (fileType == "video") {
column = MediaStore.Video.Media.DATA;
}
String[] proj = { column };
Cursor cursor = managedQuery(contentUri, proj, null, null, null); // here lies the exception!
int column_index = cursor.getColumnIndex( column );
if (column_index == -1) {
alert("Path missing", "Could not locate the file requested", this);
return "";
}
cursor.moveToFirst();
return cursor.getString(column_index);
}
Here's sanitized relevant code (just removed client info)
/*
* Call the camera activity for video or picture
*/
protected void startCaptureIntent(String actionCode, int requestCode, int media) {
Intent i = new Intent(actionCode);
if (media == MEDIA_VIDEO) {
i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
}
startActivityForResult(i, requestCode);
}
/*
* Handle the activity result
*
* #see android.app.Activity#onActivityResult(int, int,
* android.content.Intent)
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//super.onActivityResult(requestCode, resultCode, intent);
Log.d("MYDEBUGGING", "Handling activity result. requestCode:" + requestCode + " resultCode:" + resultCode);
if (resultCode == Activity.RESULT_CANCELED) {
pic_upload_button.setEnabled(true);
video_upload_button.setEnabled(true);
fileType = "none";
showToast(this, "Request canceled, Touch the picture or image button to try again");
return;
}
switch (requestCode) {
case CAMERA_PIC_REQUEST:
switch (resultCode) {
case Activity.RESULT_OK:
postType = requestCode;
fileType = "picture";
// Seems that this is the only way to be sure I end up with an actual file.
filePath = getRealPathFromURI(intent.getData());
if (filePath != null) {
showToast(this, "Image ready to be shared");
} else {
showToast(this, "Something went wrong. Image could not be captured.");
}
break;
default:
alert("Activity failed", "Could not create picture file", this);
}
break;
case CAMERA_VID_REQUEST:
switch (resultCode) {
case Activity.RESULT_OK:
postType = requestCode;
fileType = "video";
// Seems that this is the only way to be sure I end up with a video file.
filePath = getRealPathFromURI(intent.getData());
if (filePath != null) {
showToast(this, "Video ready to be shared");
} else {
showToast(this, "Something went wrong. Video could not be captured.");
}
break;
default:
alert("Activity failed", "Could not create video file", this);
}
break;
}
}
fileType and postType are global to the class and are used to indicate to the http uploader what type of file to send. actionCode is either MediaStore.ACTION_VIDEO_CAPTURE or MediaStore.ACTION_IMAGE_CAPTURE depending on user selection.
Any thoughts?
My guess is that the contentUri or filetype values aren't correct, so the managedQuery call fails.