I am trying to pass a BItmap[] from one activity to other using Intent.But, it is not getting passed,which in result is causing a Null Pointer Exception I guess. I am taking upto four images with the camera and storing them in a Bitmap[] ,which I am trying to pass to another activity.The logcat says the error is at line 94,which is where the passed Bitmap is used. Here's the code (only the relevant parts). Kindly help,Thanks in advance !
Take Pic.java :
the onCreateMethod:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.takepic);
initializeVar();
storeInArray(images);
}
The onActivity result for the four imageViews (which start the Camera activity) :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
photo1 = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(photo1);
} if(requestCode == 2 && resultCode == RESULT_OK) {
photo2 = (Bitmap) data.getExtras().get("data");
imageView2.setImageBitmap(photo2);
} if(requestCode == 3 && resultCode == RESULT_OK) {
photo3 = (Bitmap) data.getExtras().get("data");
imageView3.setImageBitmap(photo3);
} if(requestCode == 4 && resultCode == RESULT_OK) {
photo4 = (Bitmap) data.getExtras().get("data");
imageView4.setImageBitmap(photo4);
}
}
The method to store the individual bitmaps in the array :
private Bitmap[] storeInArray(Bitmap[] bitmap) {
// TODO Auto-generated method stub
if(photo1 != null){
bitmap[i]= photo1;
i++;
}if(photo2 != null){
bitmap[i]= photo2;
i++;
}if(photo3 != null){
bitmap[i]= photo3;
i++;
}if(photo4 != null){
bitmap[i]= photo4;
i++;
}
return bitmap;
}
And finally, the onClickListener for the button :
bCamEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(TakePic.this,NewEmail.class);
i.putExtra("Image",images);
startActivity(i);
}
});
And in the other Class:
extras = getIntent().getExtras();
if(extras!=null)
receive = (Bitmap[]) extras.getParcelableArray("Image");
and for the send email button :
newSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
convertEditTextToString();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,"seemaswain.09#gmail.com");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,newSubject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,newContent);
newUris = new ArrayList<Uri>();
for(String file : images) {
File fileIn = new File(file);
Uri u = Uri.fromFile(fileIn);
newUris.add(u);
}
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, newUris);
startActivity(emailIntent);
}
});
}
public String[] BitMapToString(Bitmap bitmap[]){
int i=0;
String[] temp= new String[2000];
while(bitmap[i] !=null){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap[i].compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
temp[i]=Base64.encodeToString(b, Base64.DEFAULT);
i++;
}
return temp;
}
Finally, the logcat :
12-05 13:34:04.207: W/dalvikvm(3846): threadid=1: thread exiting with uncaught exception (group=0x40e62498)
12-05 13:34:04.207: E/test(3846): Exception
12-05 13:34:04.227: E/AndroidRuntime(3846): FATAL EXCEPTION: main
12-05 13:34:04.227: E/AndroidRuntime(3846): java.lang.NullPointerException
12-05 13:34:04.227: E/AndroidRuntime(3846): at com.example.bethechange.NewEmail$1.onClick(NewEmail.java:94)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.view.View.performClick(View.java:4106)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.view.View$PerformClick.run(View.java:17150)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.os.Handler.handleCallback(Handler.java:615)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.os.Handler.dispatchMessage(Handler.java:92)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.os.Looper.loop(Looper.java:137)
12-05 13:34:04.227: E/AndroidRuntime(3846): at android.app.ActivityThread.main(ActivityThread.java:4792)
12-05 13:34:04.227: E/AndroidRuntime(3846): at java.lang.reflect.Method.invokeNative(Native Method)
12-05 13:34:04.227: E/AndroidRuntime(3846): at java.lang.reflect.Method.invoke(Method.java:511)
12-05 13:34:04.227: E/AndroidRuntime(3846): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
12-05 13:34:04.227: E/AndroidRuntime(3846): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
12-05 13:34:04.227: E/AndroidRuntime(3846): at dalvik.system.NativeStart.main(Native Method)
Do not pass bitmap array to another activity by intent.
Bitmap maybe is big file.It will cause "TransactionTooLargeException"
You have 2 ways to fix this :
1: Use a global singleton(If bitmaps are temp data not exist in files)
2: Pass bitmap file path
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
try {
photo = (Bitmap) data.getExtras().get("data");
} catch (Exception e) {
// TODO: handle exception
}
}
}
Related
I have an app where the user can add music files by selecting a file or adding all the files in a selected directory into a ListView. When adding a single file, everything is fine, but for directories I'm getting Unsupported Uri. Problem is not related to permissions:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dibo.testapp, PID: 12226
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65579, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/tree/raw:/storage/emulated/0/Download/2006 A Good Year flg=0xc3 }} to activity {com.example.dibo.testapp/com.example.dibo.testapp.MainActivity}: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2F2006%20A%20Good%20Year
at android.app.ActivityThread.deliverResults(ActivityThread.java:4360)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2F2006%20A%20Good%20Year
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:418)
at android.content.ContentResolver.query(ContentResolver.java:802)
at android.content.ContentResolver.query(ContentResolver.java:752)
at android.content.ContentResolver.query(ContentResolver.java:710)
at com.example.dibo.testapp.PlaylistFragment.addFolder(PlaylistFragment.java:380)
at com.example.dibo.testapp.PlaylistFragment.onActivityResult(PlaylistFragment.java:346)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:160)
at com.example.dibo.testapp.MainActivity.onActivityResult(MainActivity.java:152)
at android.app.Activity.dispatchActivityResult(Activity.java:7454)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4353)
This is intent request:*
private void selectDirectory() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_FOLDER);
}
Result handler:
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == REQUEST_FILE && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
addFile(resultData.getData());
}
}
if (requestCode == REQUEST_FOLDER && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
addFolder(resultData.getData());
}
}
}
private void addFolder(Uri uri) {
ContentResolver contentResolver = getActivity().getContentResolver();
if (contentResolver==null) {
return;
}
Cursor cursor = contentResolver.query(
uri, // Uri
null,
null,
null,
null
);
if (cursor != null && cursor.moveToFirst()) {
int Title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
do {
String SongTitle = cursor.getString(Title);
Log.d("addFolder", SongTitle);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
}
Exception is raised in contentResolver.query. Note that everything is in Fragment Class, not in Activity.
You need first do magic thing:
Uri docUriTree = DocumentsContract.buildDocumentUriUsingTree(treeUri, DocumentsContract.getTreeDocumentId(treeUri));
Then you can read DocumentsContract.Document values from your Uri.
My goal is to make last chosen image to stay in ImageView after an app was closed (destroyed) and then re-opened.
I tried to load to save bitmap in SharedPreference "(How can I store images using sharedpreference in android?), then I tried to store path to bitmap in SharedPreferences and load it using Picasso: (Picasso Load image from filesystem), and tried to load it by passing the value to BitmapFactory.decodeFile(completePath); as you can see in my code.
Anyway the output is always the same; I'm getting an NullPointerException.
I'm new to Android and programming in general so forgive my messy code.
private String picturePass;
private ImageView imageView;
private Bitmap picBitmap;
private boolean yes;
private static final int SELECT_PICTURE = 1;
private static final String SAVE_NAME = "MyFile";)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_page);
if (savedInstanceState != null) {
savedInstanceState.get("path");
}
//loading
SharedPreferences preferences = getSharedPreferences(SAVE_NAME, MODE_PRIVATE);
//boolean to check if Image was chosen
yes = preferences.getBoolean("yes", true);
if(yes){
picturePass = preferences.getString("path", null);
String completePath = picturePass;
//just to check the content
Toast.makeText(this, completePath, Toast.LENGTH_LONG).show();
File file = new File(completePath);
if (file.exists()) {
picBitmap = BitmapFactory.decodeFile(completePath);
imageView.setImageBitmap(picBitmap);
}
}
}
//Choosing a picture from gallery
public void onClickImage(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_PICTURE);
yes = true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data) {
//The only way I maneged to get the file path, that's a messy part
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
//Setting picture in imageView
if (selectedImage != null) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
picBitmap = bitmap;
//Tried to use Environment.getExternalStorageDirectory().getAbsolutePath() + imageName with no success
//File f = new File(picturePath);
//String imageName = f.getName();
//picturePass = imageName;
picturePass = picturePath;
//Saving image path
//just too check the content
Toast.makeText(this, picturePath, Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences(SAVE_NAME, MODE_PRIVATE).edit();
editor.putString("path", picturePass);
editor.putBoolean("yes", true);
editor.commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("path", picturePass);
}
}
08-29 19:05:46.263 16436-16436/com.amberapply.vitaliy.iloveyou E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amberapply.vitaliy.iloveyou, PID: 16436
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amberapply.vitaliy.iloveyou/com.amberapply.vitaliy.iloveyou.MainActivityPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5258)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:735)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
at com.amberapply.vitaliy.iloveyou.MainActivityPage.onCreate(MainActivityPage.java:60)
at android.app.Activity.performCreate(Activity.java:6005)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5258)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:735)
#Nikunj Sardhara solution should work
if you fix the npe : in onCreate there is no imageView = (ImageView) findViewById(R.id.imageView); before `imageView.setImageBitmap(picBitmap);
First of all storing an image in SharedPreferences would be a very bad idea.
You should store path of image in SharedPreferences and you can read that image when your app loads for the first time, read the SharedPreferences, get your image path, read it from storage and show it in your ImageView.
So, that was the procedure and that is simple, It does't require writing this much code.
Now you don't really need to store boolean in SharedPreferences, you can use contains() method :
https://developer.android.com/reference/android/content/SharedPreferences.html
And about NullPointerException, i would say please check logcat and if possible then copy your logcat at the time of NullPointerException and post your logcat here, that would be more helpful.
Here's how you can get logcat : https://developer.android.com/studio/debug/am-logcat.html
I am android beginner, my aim is select image and display on my ImageView, I use below code but in fragment onActivity result return null pointer exception.
This is my fragmentA.java
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == getActivity().RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
Log.v("imageUri", imageUri.toString());
final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
initImage();
break;
}
}
I used below code for call gallery intent
image.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if( Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT )
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent.createChooser(intent,"Select Picture"), SELECT_PHOTO);
}
else
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
}
});
This is my error report ..
java.lang.RuntimeException: Unable to resume activity {citycenter.caneda.com.citycenter/com.caneda.citycenter.myaccount.AccountMainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://media/external/images/media/506 }} to activity {citycenter.caneda.com.citycenter/com.caneda.citycenter.myaccount.AccountMainActivity}: java.lang.NullPointerException
Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://media/external/images/media/506 }} to activity {citycenter.caneda.com.citycenter/com.caneda.citycenter.myaccount.AccountMainActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at com.caneda.citycenter.myaccount.FragmentTabProfile.onActivityResult(FragmentTabProfile.java:217)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:163)
at com.caneda.citycenter.myaccount.AccountMainActivity.onActivityResult(AccountMainActivity.java:102)
at android.app.Activity.dispatchActivityResult(Activity.java:5305)
I think the line
resultCode == getActivity().RESULT_OK
is causing the problem
USE
resultCode == Activity.RESULT_OK
because RESULT_OK is static
However you can debug to test which code is causing NullPointerException
Actully answer is really silly, I have initialize
conditional based
if(saveInstaceState == null) { ivUpload = (ImageView) }
It should be outside of condition.
That's why it cause nullPointerException by ivUpload.
Thanks you so much for you support.
I have an error on 264 and 163 of two file but in editor it's look fine
line 264 :
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
line 163 :
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
I can't find why my activity unable to start
Logcat:
1266-1266/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidHTML/com.company.clipboard.AndroidHTMLActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.company.clipboard.util.IabHelper.startSetup(IabHelper.java:264)
at com.company.clipboard.AndroidHTMLActivity.onCreate(AndroidHTMLActivity.java:163)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at android.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is the whole block of payment that contain line 163:
//=====================================================
String base64EncodedPublicKey = "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDtUWVdLt6clZldCQGZxcyyWeeBp8vF/6qm7qCKuQPdXg6HB71hVu8lmcEO0VcyS2xpzXt03iW7LhKXRtDsxi5H9wHLESfY9SQUc0ugPD+n5nE+I6zCiB/RB2WscvZFa3JCiYRbmsvez+DwaQSHfq6CNUawl0fbz4NfJntZHKYHanm6PtjquO9JSj+Pa9PV38C3o5Y3ALCvPMCAwEAAQ==";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
else {
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
if (mIsPremium){
MasrafSeke(inventory.getPurchase(SKU_PREMIUM));
}
// update UI accordingly
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_PREMIUM)) {
// give user access to premium content and update the UI
Toast.makeText(AndroidHTMLActivity.this,"خرید موفق",Toast.LENGTH_SHORT).show();
MasrafSeke(purchase);
}
}
};
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
Seems an issue of IabHelper. The method queryIntentServices returns a null, instead an empty list.
Try to update the code from this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
to this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
List<ResolveInfo> intentServices = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (intentServices != null && intentServices.isEmpty() == false) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
First of all, sorry for my bad English !
I have an Activity ( say MainActivity.java ) and a class ( say AsynkTaskClass.java ).
AsynkTaskClass.java contains an AsynkTask. I am calling this AsynkTask from MainActivity.java.
Before calling this AsynkTask, I am saving some data using SharedPreferences.
From the onPostExecute function of AsynkTask, I am calling a normal function ( say displaySharedData() )which defined in MainActivity.java. There I am trying to retrieve the data I stored using SharedPreferences. Then It shows a NullPointerException. But I can access the Shared data from anywhere other than this displaySharedData() function.
This is the Log Output:
W/dalvikvm(3896): threadid=1: thread exiting with uncaught exception
E/AndroidRuntime(3896): FATAL EXCEPTION: main
E/AndroidRuntime(3896): java.lang.NullPointerExceptionE/AndroidRuntime(3896): at com.samApp.project.samApp.ui.MainActivity.displaySharedData(MainActivity.java:52)
E/AndroidRuntime(3896): at com.samApp.project.samApp.s3.AsynkTaskClass$UploadImage.onPostExecute(AsynkTaskClass.java:264)
E/AndroidRuntime(3896): at com.samApp.project.samApp.s3.AsynkTaskClass$UploadImage.onPostExecute(AsynkTaskClass.java:1)
E/AndroidRuntime(3896): at android.os.AsyncTask.finish(AsyncTask.java:417)
E/AndroidRuntime(3896): at android.os.AsyncTask.access$300(AsyncTask.java:127)
E/AndroidRuntime(3896): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
E/AndroidRuntime(3896): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(3896): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(3896): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime(3896): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(3896): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(3896): at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
public class MainActivity extends Activity implements TextView.OnEditorActionListener {
public SharedPreferences myData;
public String mySharedData="com.samApp.project.samApp.ui";
public SharedPreferences.Editor editor;
protected void onCreate(Bundle savedBundle) {
super.onCreate(savedBundle);
myData = PreferenceManager.getDefaultSharedPreferences(this);
editor = myData.edit();
editor.commit();
attachfileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PHOTO_SELECTED);
}
});
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case PHOTO_SELECTED:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Log.d("URIsssss", String.valueOf(selectedImage));
AsynkTaskClass obj = new AsynkTaskClass ();
AsynkTaskClass.s3context=this;
obj.new UploadImage().execute(selectedImage);
}
}
}
}
protected void onResume() {
super.onResume();
editor.putString("name", "MeSSi");
editor.commit();
}
public void displaySharedData()
{
Log.d("SharedData",myData.getString("name","")); // line No : 52
}
}
AsynkTaskClass.java
public class AsynkTaskClass {
MainActivity mainActvtyObj = new MainActivity();
public static Context s3context;
protected void onPostExecute(S3TaskResult result) {
if(dialog != null)
dialog.dismiss();
if (result.getErrorMessage() != null) {
displayErrorAlert(
AsynkTaskClass.s3context.getString(R.string.upload_failure_title),
result.getErrorMessage());
}
mainActvtyObj.displaySharedData();
}
}
So, Any Help ??
MainActivity mainActvtyObj = new MainActivity();
Never instantiate activity classes with new.
For example, their lifecycle callbacks such as onCreate() are not run. You init your myData in onCreate() and it remains null in this activity instance.
Instead, pass a reference to your activity object to the async task as a parameter.
Finally I got a working solution.
I don't know whether It is perfect! But it works well..
I replaced the displaySharedData() calling statement i.e. mainActvtyObj.displaySharedData(); to the following :
((MainActivity) s3context).displaySharedData();
Now It Works Great !!