Activity cannot be cast to another activity - android

From a Fragment I am calling another fragment that reads barcodes using the camera.
This is how am I calling the scan fragment:
public void scanNow(View view){
// add fragment
ScanFragment firstFragment = new ScanFragment();
((MainActivityDriver)getActivity()).getSupportFragmentManager().beginTransaction()
.add(R.id.frame, firstFragment).commit();
}
public void scanResultData(String codeFormat, String codeContent){
// display it on screen
txtCode.setText("CONTENT: " + codeContent);
}
public void scanResultData(NoScanResultException noScanData) {
Toast toast = Toast.makeText(getActivity(),noScanData.getMessage(), Toast.LENGTH_SHORT);
toast.show();
}
The camera is working fine and scans the barcode, but then I am getting an exception at onactivityresult method at fragment scanfragment:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
ScanResultReceiver parentActivity = (ScanResultReceiver) this.getActivity();
if (scanningResult != null) {
//we have a result
codeContent = scanningResult.getContents();
codeFormat = scanningResult.getFormatName();
// send received data
parentActivity.scanResultData(codeFormat,codeContent);
}else{
// send exception
parentActivity.scanResultData(new NoScanResultException(noResultErrorMsg));
}
}
at line:
ScanResultReceiver parentActivity = (ScanResultReceiver) this.getActivity();
This is the error:
Caused by: java.lang.ClassCastException: com.juarezserver.sdocksdriver.activity.MainActivityDriver cannot be cast to com.juarezserver.sdocksdriver.fragment.ScanResultReceiver
ScanResultReceiver is as follows:
public interface ScanResultReceiver {
/**
* function to receive scanresult
* #param codeFormat format of the barcode scanned
* #param codeContent data of the barcode scanned
*/
public void scanResultData(String codeFormat, String codeContent);
public void scanResultData(NoScanResultException noScanData);
}
How could I get it working?

You need to implement the interface ScanResultReceiver in MainActivityDriver
public static class MainActivityDriver extends Activity
implements ScanResultReceiver{
...
public void scanResultData(String codeFormat, String codeContent) {
//handle result
}
public void scanResultData(NoScanResultException noScanData) {
//handle exception
}
}
Also, I will recommend using a global callback variable in your fragment to avoid NullPointerException,
public class ScanFragment{
ScanResultReceiver resultCallback;
public interface ScanResultReceiver {
public void scanResultData(String codeFormat, String codeContent);
public void scanResultData(NoScanResultException noScanData);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
resultCallback = (ScanResultReceiver) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ScanResultReceiver");
}
}
...
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
codeContent = scanningResult.getContents();
codeFormat = scanningResult.getFormatName();
// send received data
resultCallback.scanResultData(codeFormat,codeContent);
}else{
// send exception
resultCallback.scanResultData(new NoScanResultException(noResultErrorMsg));
}
}
}

Related

Android: How to resolve Google API connection fail from a Service?

here is the code provided by the official guide, while this is a snippet causing problems.
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GooglePlayServicesUtil.getErrorDialog()
mResolvingError = true;
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, REQUEST_RESOLVE_ERROR)
.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mResolvingError = false;
}
});
}
}
If I use it in a Service, when you read the variable this passed as argument to those functions, they expect an Activity type.
How should I do? It's a Service.
For the same reason I can't get activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
This answer assumes your service is a "started" service. If it is a bound service or intent service, indicate that in a comment and I'll update the description and code included here.
The solution I suggest is to implement the activity shown below to handle the resolution UI. Replace the onConnectionFailed() method in your service with this code to hand off the resolution processing to the ResolverActivity:
#Override
public void onConnectionFailed(ConnectionResult result) {
Intent i = new Intent(this, ResolverActivity.class);
i.putExtra(ResolverActivity.CONNECT_RESULT_KEY, result);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
Add the activity shown below to your app. When the connection request in your service fails, the connection result, which is a Parcelable, is passed to the activity. The activity handles the resolution UI and when finished, returns the status to the service as an intent extra. You will need to modify the code in your service's onStartCommand() to examine the extras in the intent to determine if it is being called to start the service for the first time, or to receive resolution status from the ResolverActivity.
An enhancement to this approach would be to post a notification with a PendingIntent for ResolverActivity instead of launching the activity immediately. That would give the user the option of deferring resolution of the connection failure.
public class ResolverActivity extends AppCompatActivity {
public static final String TAG = "ResolverActivity";
public static final String CONNECT_RESULT_KEY = "connectResult";
public static final String CONN_STATUS_KEY = "connectionStatus";
public static final int CONN_SUCCESS = 1;
public static final int CONN_FAILED = 2;
public static final int CONN_CANCELLED = 3;
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1111;
private static final String ERROR_CODE_KEY = "errorCode";
private static final String DIALOG_FRAG_TAG = "errorDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate()");
// No content needed.
//setContentView(R.layout.activity_main);
Intent i = getIntent();
ConnectionResult result = i.getParcelableExtra(CONNECT_RESULT_KEY);
if (result.hasResolution()) {
try {
Log.i(TAG, "Starting error resolution...");
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent.
sendStatusToService(CONN_FAILED);
finish();
}
} else {
// Show dialog using GooglePlayServicesUtil.getErrorDialog()
ErrorDialogFragment.newInstance(result.getErrorCode())
.show(getSupportFragmentManager(), DIALOG_FRAG_TAG);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
if (resultCode == RESULT_OK) {
Log.i(TAG, "onActivityResult(): Connection problem resolved");
sendStatusToService(CONN_SUCCESS);
} else {
sendStatusToService(CONN_CANCELLED);
Log.w(TAG, "onActivityResult(): Resolution cancelled");
}
// Nothing more to do in this activity
finish();
}
}
private void sendStatusToService(int status) {
Intent i = new Intent(this, MyGoogleApiService.class);
i.putExtra(CONN_STATUS_KEY, status);
startService(i);
}
// Fragment to display an error dialog
public static class ErrorDialogFragment extends DialogFragment {
public static ErrorDialogFragment newInstance(int errorCode) {
ErrorDialogFragment f = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(ERROR_CODE_KEY, errorCode);
f.setArguments(args);
return f;
}
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = getArguments().getInt(ERROR_CODE_KEY);
return GooglePlayServicesUtil.getErrorDialog(
errorCode, getActivity(), REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
Log.i(TAG, "Dialog dismissed");
}
}
}

Fragment onActivityResult returns null

In the app I'm developing, the user can define an image on his profile. The first time the app is executed, an intro activity is shown where the user can choose between selecting a photo from the galery or taking a new one with the camera.
This works fine. After the user sets a profile pic, I save it in the app folder and I can use that pic inside the app later.
My app is based on the Navigation Drawer (support) so it is composed by fragments. One of this fragments is for the user's profile where the profile pic is shown. here, the user has te chance to change this pic again. An here is where I'm getting troubles.
To select a new pic, I'm using the same code I used to get the pic in the intro activity, just adapting some things to the fragment (putting getActivity()). But it seems that is not returning the image to the fragment and it's throwing a NPE.
This is how the pic is selectect from gallery in SettingsFragment:
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST_FRAG);
And here is the onActivityResult in SettingsFragment too:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_IMAGE_REQUEST_FRAG:
if (resultCode == getActivity().RESULT_OK && data != null) {
/*We get the image URI*/
Uri selectedImageUri = data.getData();
Bitmap srcBmp = null;
try {
srcBmp = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
} catch (FileNotFoundException e) {
Log.e("GET_IMAGE", e.getMessage(), e);
} catch (IOException e) {
Log.e("GET_IMAGE", e.getMessage(), e);
}
/*Transform the original image to landscape to use it as profile background*/
Bitmap landBmp = null;
if (srcBmp.getWidth() <= srcBmp.getHeight()) {
landBmp = Bitmap.createBitmap(
srcBmp,
0,
srcBmp.getHeight()/2 - srcBmp.getWidth()/2, //srcBmp.getHeight()/4 ?
srcBmp.getWidth(),
srcBmp.getWidth() /2
);
}
/*Scale the bitmap*/
int originalWidth = srcBmp.getWidth();
int originalHeight = srcBmp.getHeight();
int newWidth = 400;
int newHeight = (originalHeight*newWidth)/originalWidth;
Bitmap fullbitmap = Bitmap.createScaledBitmap(landBmp, newWidth, newHeight, true);
/*Save the bitmap in app-folder*/
ContextWrapper cw1 = new ContextWrapper(getActivity().getApplicationContext());
File directory1 = cw1.getDir("profile", Context.MODE_PRIVATE);
if (!directory1.exists()) {
directory1.mkdir();
}
File filepath1 = new File(directory1, "profile_pic.png");
FileOutputStream fos1 = null;
try {
fos1 = new FileOutputStream(filepath1);
fullbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos1);
fos1.close();
} catch (Exception e) {
Log.e("SAVE_FULL_IMAGE", e.getMessage(), e);
}
/*Show background profile pic*/
Drawable drawable = new BitmapDrawable(getResources(), fullbitmap);
header_container.setBackgroundDrawable(drawable);
}
break;
But as said, the app crashes an this is what logcat tells:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131073, result=-1,
data=Intent { dat=content://media/external/images/media/204 flg=0x1 }}
to activity {com.myproject.executer/com.myproject.executer.MainActivity}:
java.lang.NullPointerException at android.app.ActivityThread.deliverResults(ActivityThread.java:3389)
Caused by: java.lang.NullPointerException at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:590)
at com.myproject.executer.SettingsFragment.onActivityResult(SettingsFragment.java:275)
Where line 275 is Bitmap fullbitmap = Bitmap.createScaledBitmap(landBmp, newWidth, newHeight, true);
So, I don't understand well what is happening, because it says something that is failing to deviler the result to MainActivity , and it has to deliver the result to SettingsFragment.
If the onActivityResult() method doesn't complete and return, the system counts it as the delivery having failed, which is why the errors start with that message.
In your code, it would seem that landBmp is null, because the condition srcBmp.getWidth() <= srcBmp.getHeight() is false, and you don't initialize landBmp in that case. This is throwing the NullPointerException, and halting execution before onActivityResult() returns.
you can reading :http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en?fb_action_ids=780839882030502&fb_action_types=og.comments
Create ActivityResultEvent.java
import android.content.Intent;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultEvent {
private int requestCode;
private int resultCode;
private Intent data;
public ActivityResultEvent(int requestCode, int resultCode, Intent data) {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
}
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public Intent getData() {
return data;
}
public void setData(Intent data) {
this.data = data;
}
}
Create ActivityResultBus.java
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultBus extends Bus {
private static ActivityResultBus instance;
public static ActivityResultBus getInstance() {
if (instance == null)
instance = new ActivityResultBus();
return instance;
}
private Handler mHandler = new Handler(Looper.getMainLooper());
public void postQueue(final Object obj) {
mHandler.post(new Runnable() {
#Override
public void run() {
ActivityResultBus.getInstance().post(obj);
}
});
}
}
// >>>>>>>>>>>>>> override onActivityResult on Activity
public class MainActivity extends ActionBarActivity {
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResultBus.getInstance().postQueue(
new ActivityResultEvent(requestCode, resultCode, data));
}
...
}
In fragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Don't forget to check requestCode before continuing your job
if (requestCode == 12345) {
// Do your job
tvResult.setText("Result Code = " + resultCode);
}
}
#Override
public void onStart() {
super.onStart();
ActivityResultBus.getInstance().register(mActivityResultSubscriber);
}
#Override
public void onStop() {
super.onStop();
ActivityResultBus.getInstance().unregister(mActivityResultSubscriber);
}
private Object mActivityResultSubscriber = new Object() {
#Subscribe
public void onActivityResultReceived(ActivityResultEvent event) {
int requestCode = event.getRequestCode();
int resultCode = event.getResultCode();
Intent data = event.getData();
onActivityResult(requestCode, resultCode, data);
}
};

I just tried to use the onActivitiResult of other activities

Google Login connect Error
Android Code..
public class GooglePlusPlugin implements ConnectionCallbacks,
OnConnectionFailedListener{
Activity resultactivity;
private Activity activity;// activity is Unity3D currentActivity
public void init(String objName, String CallbackName) {
callbackName = CallbackName;
unityObjectName = objName;
mApiClient = new GoogleApiClient.Builder(activity, this, this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addScope(Plus.SCOPE_PLUS_PROFILE).build();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
resultactivity = new ResultActivity();
mConnectionProgressDialog = new ProgressDialog(activity);
mConnectionProgressDialog.setMessage("Signing in...");
}
});
}
#Override
public void onConnectionFailed(final ConnectionResult result) {
if (!mConnectionProgressDialog.isShowing()) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(resultactivity,
result.getErrorCode());
return;
} catch (SendIntentException e) {
mApiClient.connect();
}
}
}
}
}
startResolutionForResult a call to onActivityResult
I try to use onActivityResult other activities, because not extends the activity in GooglePlusPlugin
public class ResultActivity extends FragmentActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLVE_ERR
&& resultCode == RESULT_OK) {
GooglePlusPlugin.getInstance().reconnect(requestCode, resultCode);
finish();
}
}
but failed...
error is
Caused by: java.lang.NullPointerException
at android.app.Activity.startIntentSenderForResultInner(Activity.java:3560)
at android.app.Activity.startIntentSenderForResult(Activity.java:3536)
at android.app.Activity.startIntentSenderForResult(Activity.java:3503)
at com.google.android.gms.common.ConnectionResult.startResolutionForResult(Unknown Source)
at kr.co.crooz.plugin.googleplus.GooglePlusPlugin.onConnectionFailed(GooglePlusPlugin.java:212)
Why startIntentSenderForResult need, I do not know how to use it.
How to solve?
Thanks for reading long code
private Activity activity; Activity has already been taken from another part.
I like long content. The part that is not.
try {
this.unityPlayerClass = Class
.forName("com.unity3d.player.UnityPlayer");
this.unityPlayerActivityField = this.unityPlayerClass
.getField("currentActivity");
this.unitySendMessageMethod = this.unityPlayerClass.getMethod(
"UnitySendMessage", new Class[] { String.class,
String.class, String.class });
this.activity = getActivity();
}
private Activity getActivity() {
if (this.unityPlayerActivityField != null) {
try {
Activity activity = (Activity) this.unityPlayerActivityField
.get(this.unityPlayerClass);
if (activity == null) {
Log.d(TAG,
"Something has gone terribly wrong. The Unity Activity does not exist. This could be due to a low memory situation");
}
return activity;
} catch (Exception e) {
Log.d(TAG, "error getting currentActivity: " + e.getMessage());
}
}
return this.activity;
}
your Activity is null
private Activity activity;// activity is Unity3D currentActivity
you declare it here but you never grab the activity from unity3D as i guess you trying to do, this will result that you activity is null and will throw nullpointerexeption

Null pointer exception when calling startActivityForResult()

I'm having a problem (Null Pointer Exception) when calling startActivityForResult() from class inside another class, here is the code :
public class OCRActivity extends Activity {
public OCRActivity(String operator)
{
this.operator = operator;
}
public void startCameraActivity() {
final Intent capture_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(capture_intent, 1); // I get the Null pointer Exception here
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == 1){
//get the Uri for the captured image
picUri = data.getData();
//carry out the crop operation
performCrop();
}
}
and here is where I call startCameraActivity()
public class WayToFillActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.way_to_fill);
CAMERA_BTN = (Button) findViewById(R.id.camera_btn);
CAMERA_BTN.setOnClickListener(this);
Intent operator_intent = getIntent();
OPERATOR = operator_intent.getStringExtra("operator");
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.camera_btn)
{
OCRActivity ocr = new OCRActivity(OPERATOR);
ocr.startCameraActivity();
}
}
So please tell me if I'm doing something wrong !!
The Logcat
01-13 16:22:26.583: E/AndroidRuntime(32425): java.lang.NullPointerException
01-13 16:22:26.583: E/AndroidRuntime(32425): at android.app.Activity.startActivityForResult(Activity.java:3190)
01-13 16:22:26.583: E/AndroidRuntime(32425): at com.almannaa.EasyRecharge.OCRActivity.startCameraActivity(OCRActivity.java:176)
You are treating OCRActivity as an ordinary Java class, and not like another Activity. Due to this, when you call startActivityForResult() you get a NPE as the Activity's onCreate() has not been called, which means that its current instance is not valid for calling startActivityForResult()
Instead, try using:
public class WayToFillActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.way_to_fill);
CAMERA_BTN = (Button) findViewById(R.id.camera_btn);
CAMERA_BTN.setOnClickListener(this);
Intent operator_intent = getIntent();
OPERATOR = operator_intent.getStringExtra("operator");
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.camera_btn)
{
OCRActivity ocr = new OCRActivity(OPERATOR);
ocr.startCameraActivity();
}
}
public void startCameraActivity() {
final Intent capture_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(capture_intent, 1); // I get the Null pointer Exception here
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == 1){
//get the Uri for the captured image
picUri = data.getData();
//carry out the crop operation
performCrop();
}
}
}
You should probably move functions like performCrop() (and any other functions that don't really need to be in the activity itself, and can work by receiving data as parameters and returning it) into a separate class (call it Utility or whatever).
Maybe you should check if the data is not null.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && data != null) {
if(resultCode == RESULT_OK){
//get the Uri for the captured image
picUri = data.getData();
//carry out the crop operation
performCrop();
} }

Trying to read barcodes with Zxing, but it seems the onActivityResult is not beeing called

as the title says, I'm trying to scan 1D barcodes, so far I have thet following code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void test(View view){
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "1D_CODE_MODE");
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
IntentResult intentResult =
IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null) {
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
TextView uno = (TextView) findViewById(R.id.textView1);
uno.setText(contents);
Toast.makeText(this, "Numero: " + contents, Toast.LENGTH_LONG).show();
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
}
And of course, I have both IntentResult and IntentIntegrator added to the project.
So, the scanner is beeing called correctly when a button is pressed and it seems to scan the code perfectly (it says "Text found" after it scans it), but it seems that the onActivityResult is not called, since the TextView is not beeing updated and the Toast is not appearing.
Any idea on what the mistake could be?
Thanks in advance!
Your first mistake is not using IntentIntegrator.initiateScan(), replacing it with your own hand-rolled call to startActivityForResult().
Your second mistake is in assuming that IntentIntegrator.REQUEST_CODE is 0. It is not.
Hence, with your current code, you are sending out a request with request code of 0, which is coming back to onActivityResult() with request code of 0, which you are ignoring, because you are only looking for IntentIntegrator.REQUEST_CODE.
Simply replace the body of your test() method with a call to initiateScan(), and you should be in better shape. Here is a sample project that demonstrates the use of IntentIntegrator.
I resolve your same problem so.
public class MainActivity extends Activity {
private TextView tvStatus, tvResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.tvStatus = (TextView) findViewById(R.id.tvStatus);
this.tvResult = (TextView) findViewById(R.id.tvResult);
Button scanBtn = (Button) findViewById(R.id.btnScan);
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_FORMATS", "QR_CODE_MODE");
startActivityForResult(intent,
IntentIntegrator.REQUEST_CODE);
} catch (Exception e) {
Log.e("BARCODE_ERROR", e.getMessage());
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent);
if (scanResult != null) {
this.tvStatus.setText(scanResult.getContents());
this.tvResult.setText(scanResult.getFormatName());
}
}
}
The onActivityResault function must be overridden. just add an #Override before the function declaration and it will be solved.

Categories

Resources