Android onActivityResult() returning NullPointerException on image capture - java

I'm having trouble with receiving the data capture from a Camera intent I have developed. I have used the code present in the android API guides. Can anyone tell where I am going wrong? I can see that the who=null and data=null parameters present in the LogCat printout are probably causing the error but I'm unsure as to why that is.
Camera Activity
//ESSENTIAL VARIABLES - DD - 29/04/2013
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
MenuItem item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snap_camera);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
/**
* Gets the OutputMediaFileUri and accepts media type as a parameter
* #param type
* #return
*/
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* Method taking media type as a parameter and will save images taken to a public directory on users' device.
* #param type
* #return
*/
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CrowdSnapCymru");
if(!mediaStorageDir.exists()){
if(! mediaStorageDir.mkdirs()){
Log.d("CrowdSnapCymru", "failed to create photo directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if(type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
}
else{
return null;
}
return mediaFile;
}
/**
* Receives the result of Camera intent.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if(resultCode == RESULT_OK){
Toast.makeText(this, "Image saved to: \n" + data.getData() , Toast.LENGTH_LONG).show();
}
else if(resultCode == RESULT_CANCELED){
Toast.makeText(this, "User canceled the image capture", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "Image capture failed. Please try again", Toast.LENGTH_LONG).show();
}
}
}
The code loads the Camera application and will produce the successful result if I cancel the application but if I accept the image or RESULT_OKAY the NullPointerException is produced.
LogCat Printout
05-01 09:57:48.894: E/AndroidRuntime(974): FATAL EXCEPTION: main
05-01 09:57:48.894: E/AndroidRuntime(974): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {rcahmw.prototype.crowdsnapcymru/rcahmw.prototype.crowdsnapcymru.SnapCamera}: java.lang.NullPointerException
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.deliverResults(ActivityThread.java:3319)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3362)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.os.Looper.loop(Looper.java:137)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 09:57:48.894: E/AndroidRuntime(974): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 09:57:48.894: E/AndroidRuntime(974): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 09:57:48.894: E/AndroidRuntime(974): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 09:57:48.894: E/AndroidRuntime(974): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 09:57:48.894: E/AndroidRuntime(974): at dalvik.system.NativeStart.main(Native Method)
05-01 09:57:48.894: E/AndroidRuntime(974): Caused by: java.lang.NullPointerException
05-01 09:57:48.894: E/AndroidRuntime(974): at rcahmw.prototype.crowdsnapcymru.SnapCamera.onActivityResult(SnapCamera.java:84)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.Activity.dispatchActivityResult(Activity.java:5293)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
Any advice would be brilliant. Pretty new to using Camera application in android.

Save your fileUri variable somewhere and use it in onActivityResult instead of data.getData

Try passing Following File URI as EXTRA_OUTPUT as follow. Your onCreate would look like :
Uri picUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snap_camera);
String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture.jpg";
File imageFile = new File(imageFilePath);
picUri = Uri.fromFile(imageFile); // convert path to Uri
intent.putExtra( MediaStore.EXTRA_OUTPUT, picUri );
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
Then onActivityResult use picUri to access image. Declare picUri as a instance variable in your activity. So it will be available in onActivityResult

Related

NullPointerException when use getLaunchIntentForPackage

I'm trying to start a third party app(here is Launcher) by using this code:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String currentHomePackage = resolveInfo.activityInfo.packageName;
openApp(getApplicationContext(),currentHomePackage);
openApp:
public static boolean openApp(Context context, String packageName) {
PackageManager manager = context.getPackageManager();
try {
Intent i = manager.getLaunchIntentForPackage(packageName);
if (i == null) {
return false;
//throw new PackageManager.NameNotFoundException();
}
i.addCategory(Intent.CATEGORY_LAUNCHER);
context.startActivity(i);
return true;
} catch (Exception e) {
return false;
}
}
but I get a NullPointerException! This code gets my launcher package name correctly, but I can't open it! Help me please and don't get me negative points!
logcat:
07-30 18:59:47.206 16079-16079/ir.whiteapp.keepme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at ir.whiteapp.keepme.AlertBox.openApp(AlertBox.java:80)
at ir.whiteapp.keepme.AlertBox$1.onClick(AlertBox.java:52)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
There is no requirement that getLaunchIntentForPackage() return anything. Quoting the documentation:
Returns: A fully-qualified Intent that can be used to launch the main activity in the package. Returns null if the package does not contain such an activity, or if packageName is not recognized.
In particular, a home screen implementation does not need a launch Intent (ACTION_MAIN/CATEGORY_LAUNCHER), as normally it is not launched by other home screen implementations.

How do I solve IabHelper Error

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."));
}
}

Android ListView with 2 TextViews and 1 Button

I'm trying to create a ListView with 2 TextViews and 1 Button. When the users click in the button the activity will finish(); and pass the result to another view. I followed this tutorial . But for some reason when i click to start that activity my application crashes! Here is the 3 files from my app that are relevant.
List Structure Data:
public class formulasListData {
private String formulasName;
private String formulasDefinition;
public formulasListData(String formulasName, String formulasDefinition) {
super();
this.formulasName = formulasName;
this.formulasDefinition = formulasDefinition;
}
public String getFormulasName() {
return formulasName;
}
public void setFormulasName(String formulasName) {
this.formulasName = formulasName;
}
public String getFormulasDefinition() {
return formulasDefinition;
}
public void setFormulasDefinition(String formulasDefinition) {
this.formulasDefinition = formulasDefinition;
}
}
The List Adapter:
public class formulasListAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<formulasListData> formulasList;
public formulasListAdapter(Context context, List<formulasListData> formulasList) {
this.context = context;
this.formulasList = formulasList;
}
#Override
public int getCount() {
return formulasList.size();
}
#Override
public Object getItem(int position) {
return formulasList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View rowView, ViewGroup parent) {
formulasListData entry = formulasList.get(position);
if(rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.formulas_row, null);
}
TextView formulasName = (TextView) rowView.findViewById(R.id.formulas_name);
formulasName.setText(entry.getFormulasName());
TextView formulasDefinition = (TextView) rowView.findViewById(R.id.formulas_definition);
formulasDefinition.setText(entry.getFormulasDefinition());
Button btnSelect = (Button) rowView.findViewById(R.id.selectFormula);
btnSelect.setFocusableInTouchMode(false);
btnSelect.setFocusable(false);
btnSelect.setOnClickListener(this);
btnSelect.setTag(entry);
return rowView;
}
#Override
public void onClick(View view) {
formulasListData entry = (formulasListData) view.getTag();
}
}
And the activity that should display the list.
public class FormulasList extends Activity {
private static final int FORMULA_0 = 0;
private static final int FORMULA_1 = 1;
private static final int FORMULA_2 = 2;
private static final int FORMULA_3 = 3;
private static final int FORMULA_4 = 4;
private static final int FORMULA_5 = 5;
private static final int FORMULA_6 = 6;
// private static final int FORMULA_7 = 7;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
ListView formulasListView = (ListView) findViewById(R.id.formulas_list);
formulasListView.setClickable(true);
final List<formulasListData> formulasList = new ArrayList<formulasListData>();
final String[] formulasName = new String[] {"Circunference of a Circle:",
"Area of a Circle:",
"Volume of a Sphere:",
"Area Triangle:",
"Area Square:",
"Volume of a Cube:",
"Pithagorean Theorem:"};
final String[] formulasDefinition = new String[] {"2 × π × r",
"π × r²",
"(4/3) × π × r³",
"(b × h)/2",
"side²",
"side³",
"a² + b² = c²"};
// formulasList.add(new formulasListData(formulasName, formulasDefinition));
formulasList.add(new formulasListData(formulasName[0], formulasDefinition[0]));
formulasList.add(new formulasListData(formulasName[1], formulasDefinition[1]));
formulasList.add(new formulasListData(formulasName[2], formulasDefinition[2]));
formulasList.add(new formulasListData(formulasName[3], formulasDefinition[3]));
formulasList.add(new formulasListData(formulasName[4], formulasDefinition[4]));
formulasList.add(new formulasListData(formulasName[5], formulasDefinition[5]));
formulasList.add(new formulasListData(formulasName[6], formulasDefinition[6]));
SharedPreferences settings = getSharedPreferences(SettingsActivity.PREF_NAME, MODE_PRIVATE);
SettingsActivity.newTheme = settings.getInt("themeCustom", 0);
if(SettingsActivity.newTheme == SettingsActivity.THEME_DARK) {
setTheme(R.style.DarkTheme);
} else if(SettingsActivity.newTheme == SettingsActivity.THEME_LIGHT){
setTheme(R.style.LightTheme);
} else if(SettingsActivity.newTheme == SettingsActivity.THEME_COLORS) {
setTheme(R.style.ColorsTheme);
} else {
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_formulas);
formulasListAdapter adapter = new formulasListAdapter(this, formulasList);
formulasListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long index) {
Intent intent= getIntent();
Bundle b = new Bundle();
switch (position) {
case FORMULA_0:
b.putString("key0", formulasDefinition[0]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_1:
b.putString("key0", formulasDefinition[1]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_2:
b.putString("key0", formulasDefinition[2]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_3:
b.putString("key0", formulasDefinition[3]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_4:
b.putString("key0", formulasDefinition[4]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_5:
b.putString("key0", formulasDefinition[5]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
case FORMULA_6:
b.putString("key0", formulasDefinition[6]);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
break;
default:
break;
}
}
});
formulasListView.setAdapter(adapter);
}
}
Thank you very much!!
EDIT: Here is the LogCat
05-01 20:06:54.436: D/libEGL(4820): loaded /system/lib/egl/libEGL_tegra.so
05-01 20:06:54.456: D/libEGL(4820): loaded /system/lib/egl/libGLESv1_CM_tegra.so
05-01 20:06:54.466: D/libEGL(4820): loaded /system/lib/egl/libGLESv2_tegra.so
05-01 20:06:54.486: D/OpenGLRenderer(4820): Enabling debug mode 0
05-01 20:06:54.536: D/dalvikvm(4820): GC_CONCURRENT freed 170K, 4% free 7509K/7808K, paused 4ms+10ms, total 38ms
05-01 20:06:59.976: D/AndroidRuntime(4820): Shutting down VM
05-01 20:06:59.976: W/dalvikvm(4820): threadid=1: thread exiting with uncaught exception (group=0x40cde930)
05-01 20:06:59.976: E/AndroidRuntime(4820): FATAL EXCEPTION: main
05-01 20:06:59.976: E/AndroidRuntime(4820): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabilheri.marcuscalculatorv2/com.gabilheri.marcuscalculatorv2.FormulasList}: java.lang.NullPointerException
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.os.Looper.loop(Looper.java:137)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 20:06:59.976: E/AndroidRuntime(4820): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 20:06:59.976: E/AndroidRuntime(4820): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 20:06:59.976: E/AndroidRuntime(4820): at dalvik.system.NativeStart.main(Native Method)
05-01 20:06:59.976: E/AndroidRuntime(4820): Caused by: java.lang.NullPointerException
05-01 20:06:59.976: E/AndroidRuntime(4820): at com.gabilheri.marcuscalculatorv2.FormulasList.onCreate(FormulasList.java:30)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.Activity.performCreate(Activity.java:5104)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-01 20:06:59.976: E/AndroidRuntime(4820): ... 11 more
Try moving
setContentView(R.layout.activity_formulas);
To the start of the method. Right after the super call.
You are trying to use gui controls before initializing the activity layout

Activity closes when trying to asyncronously connect to twitter

I have been trying to program a twitter client for Android (using twitter4j). So far the idea is to have a simple GUI, and if there is not a file with the OAuth token in the SD Card, connect to the Twitter API using AsyncTask, get the URL for the authorization and open the default browser. However, the browser never runs. Depending on the different modifications I have made trying to fix this, either the Activity starts normally but the browser never starts or the Activity crashes. I have come to a point of a a little of frustation and confussion. Can someone point out what's wrong with my code?
public class StatusActivity extends Activity {
private static final String TAG = "StatusActivity";
EditText editText;
Button updateButton;
File oauthfile = null;
public Context context = getApplicationContext();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
Log.d(TAG, "started");
// Find views
editText = (EditText) findViewById(R.id.editText); //
updateButton = (Button) findViewById(R.id.buttonUpdate);
oauthfile = new File("sdcard/auth_file.txt");
//Check if the file with the keys exist
if (oauthfile.exists()==false){
Log.d(TAG, "file not created");
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "file not created.", Toast.LENGTH_SHORT);
toast.show();
new Authorization(context).execute();
}
}
public void openBrowser (View v){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
Log.d(TAG, "onclick");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, menu);
return true;
}
}
class Authorization extends AsyncTask <String, Integer, String>{
String url = null;
private Context context;
Authorization(Context context) {
this.context = context.getApplicationContext();
}
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
}
#Override
public String doInBackground(String... params) {
ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true)
//I have eliminated the keys from the question :)
.setOAuthConsumerKey("XXXXXXXXXXXXXX")
.setOAuthConsumerSecret("XXXXXXXXXXXXXXX");
Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
RequestToken requestToken = null;
AccessToken accessToken = null;
do{
try {
requestToken = OAuthTwitter.getOAuthRequestToken();
url = requestToken.getAuthorizationURL();
}
catch (TwitterException ex) {
ex.printStackTrace();
}
}
while (accessToken==null);
return url;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(context, "Opening browser.", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_ALL_APPS, Uri.parse(url));
context.startActivity(browserIntent);
}
}
I know that at least checks if the file for the tokens exists because the toast "file not created" appears, and that the activity is able to run the browser if I press the button. The app has permissions to write in the SD card and use the Internet. Thanks in advance.
Logcat Trace:
03-28 19:02:32.816: E/AndroidRuntime(278): FATAL EXCEPTION: main
03-28 19:02:32.816: E/AndroidRuntime(278): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.versec.pardinus/com.versec.pardinus.StatusActivity}: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Looper.loop(Looper.java:123)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invoke(Method.java:521)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-28 19:02:32.816: E/AndroidRuntime(278): at dalvik.system.NativeStart.main(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): Caused by: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.versec.pardinus.StatusActivity.<init>(StatusActivity.java:30)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstanceImpl(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstance(Class.java:1429)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
03-28 19:02:32.816: E/AndroidRuntime(278): ... 11 more
This is what is causing your crash.
public Context context = getApplicationContext();
You're not even using it when you need it, so you can just get rid of this line.
Btw, something else I noticed while looking at your code is this:
oauthfile = new File("sdcard/auth_file.txt");
Don't take the "sdcard/" path for granted. Use this instead:
File dir = Environment.getExternalStorageDirectory();
File oauthfile = new File(dir, "auth_file.txt");

Android image resize after camera intent callback

my first question here! I have a problem with a piece of code that starts a camera intent with the extra output options and then on activity result tries to resize that image. what is happening is that a nullpointer exception gets thrown in the resize function at the callback.
The original large picture is still saved on the file system, as I can access that from the filesystem.
The original camera jpeg is 2560x1920 in size and the phone in use is a google nexus one.
I have no clear idea asto why the resize is not working, anyone have any insight?
Here's some code:
The takePicture function that also creates the dummy file:
public boolean takePicture( ) {
Log.e(TAG, "takePicture interface function");
String FileUri = Environment.getExternalStorageDirectory() + "/samples/";
File file = new File(FileUri,"picture"+ pictureNumber +".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
Log.e(TAG, "intent started");
return true;
}
The on activity result callback function:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle the camera request returns and handle back button in camera.
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_CANCELED ) {
Toast toast = Toast.makeText(this,"Canceled, no picture taken.", 1000);
toast.show();
return;
}
else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK ) {
Log.e(TAG, "Camera intent return");
Bitmap scaledphoto = null;
int height = 300;
int width = 300;
Bitmap photo = BitmapFactory.decodeFile( APP_DATA_PATH + "/samples/picture" + pictureNumber + ".jpg" );
Log.e(TAG, "Picture fetched");
scaledphoto = Bitmap.createScaledBitmap(photo, height, width, true);
Log.e(TAG, "Picture scaled");
saveImageToFile(scaledphoto, "picture" + pictureNumber + ".jpg");
Log.e(TAG, "Scaled picture saved");
myWebView.loadUrl("javascript:pictureTaken(\""+ pictureLoc + "\")");
pictureNumber++;
And here's the LogCat:
06-21 14:59:13.496: E/AndroidRuntime(6130): FATAL EXCEPTION: main
06-21 14:59:13.496: E/AndroidRuntime(6130): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {test.test/test.test.CameraIntentTestActivity}: java.lang.NullPointerException
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread.deliverResults(ActivityThread.java:2980)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3023)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread.access$1100(ActivityThread.java:123)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1177)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.os.Handler.dispatchMessage(Handler.java:99)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.os.Looper.loop(Looper.java:137)
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.app.ActivityThread.main(ActivityThread.java:4424)
06-21 14:59:13.496: E/AndroidRuntime(6130): at java.lang.reflect.Method.invokeNative(Native Method)
06-21 14:59:13.496: E/AndroidRuntime(6130): at java.lang.reflect.Method.invoke(Method.java:511)
06-21 14:59:13.496: E/AndroidRuntime(6130): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-21 14:59:13.496: E/AndroidRuntime(6130): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-21 14:59:13.496: E/AndroidRuntime(6130): at dalvik.system.NativeStart.main(Native Method)
06-21 14:59:13.496: E/AndroidRuntime(6130): Caused by: java.lang.NullPointerException
06-21 14:59:13.496: E/AndroidRuntime(6130): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:432)
Change
Bitmap photo = BitmapFactory.decodeFile( APP_DATA_PATH + "/samples/picture" + pictureNumber + ".jpg" );
To
Bitmap photo = (Bitmap) data.getExtras().get("data");

Categories