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);
Related
I'm trying to get a screenshot from a fragment, but seems that when I do
bitmap = view.getDrawingCache(); it returns null. Does anyone knows why is this happening and how can I fix this?
here is my code:
public void takeScreenshot(View view) {
OutputStream output;
view = view.getRootView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath + "/"
+ getString(R.string.app_name) + "/");
dir.mkdirs();
File file = new File(dir, getString(R.string.app_name) + ".jpg");
bitmap = view.getDrawingCache();
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, output);
output.flush();
output.close();
Log.d(TAG, "screenshot saved");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and calling the method
takeScreenshot(getActivity().findViewById(R.id.fragment_container));
and here is the logCat output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.contractfit/com.contractfit.activities.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.contractfit.fragments.BaseFragment.takeScreenshot(BaseFragment.java:532)
at com.contractfit.fragments.MainFragment.init(MainFragment.java:211)
at com.contractfit.fragments.MainFragment.onCreateView(MainFragment.java:116)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5461)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
Consider doing this like Instrumentation test cases do it, your code is close but differs a bit.
From https://android.googlesource.com/platform/external/droiddriver/+/367267b/src/io/appium/droiddriver/instrumentation/InstrumentationUiDevice.java
Get root view (if it's public):
context.getDriver().getRootElement().getRawElement()));
Take screenshot
public Bitmap call() {
Bitmap screenshot;
rootView.destroyDrawingCache();
rootView.buildDrawingCache(false);
Bitmap drawingCache = rootView.getDrawingCache();
int[] xy = new int[2];
rootView.getLocationOnScreen(xy);
if (xy[0] == 0 && xy[1] == 0) {
screenshot = Bitmap.createBitmap(drawingCache);
} else {
Canvas canvas = new Canvas();
Rect rect = new Rect(0, 0, drawingCache.getWidth(), drawingCache.getHeight());
rect.offset(xy[0], xy[1]);
screenshot =
Bitmap.createBitmap(rect.width() + xy[0], rect.height() + xy[1], Config.ARGB_8888);
canvas.setBitmap(screenshot);
canvas.drawBitmap(drawingCache, null, new RectF(rect), null);
canvas.setBitmap(null);
}
rootView.destroyDrawingCache();
return screenshot;
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.
i was implmenting a pdf reader in my project when i got the following error..
E/AndroidRuntime(1495): FATAL EXCEPTION: main
E/AndroidRuntime(1495): Process: com.example.testqstn, PID: 1495
E/AndroidRuntime(1495): java.lang.NoClassDefFoundError: com.questionpoint.pdf.Pdf
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.openPdfIntent(Question_Point_Main.java:272)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.CopyReadAssets(Question_Point_Main.java:266)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.pdfSelection(Question_Point_Main.java:128)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main$2.onClick(Question_Point_Main.java:104)
E/AndroidRuntime(1495): at android.view.View.performClick(View.java:4438)
E/AndroidRuntime(1495): at android.view.View$PerformClick.run(View.java:18422)
E/AndroidRuntime(1495): at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime(1495): at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(1495): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1495): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1495): at dalvik.system.NativeStart.main(Native Method)
I/Process(1495): Sending signal. PID: 1495 SIG: 9
i had imported a project to my code.. my library file is named libs, and i have repeatedly cleaned my project.. but still the error persists.. Thanks in advance..
The code that leads to error
public void CopyReadAssets(String url) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), url);
try {
in = assetManager.open(url);
out = openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getFilesDir() + "/"+url;
openPdfIntent(path);
}
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Try these steps:
Step 1: Create a folder "lib", and copy all third-party jars here;
Step 2: Add these jars to build path;
Step 3: Use the folder as Source Folder(shown below).
Maybe you just forgot the underscore and you meant com.question_point.pdf.Pdf?
It would be easier to tell if you could post the relevant code where you make the call that leads to the Exception.
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!