i am trying to integrate qr code scanner in my application in android, i am using zxing library BarcodeEye.
i have implemented below piece of code
Intent intent = new Intent("com.github.barcodeeye.scan.CaptureActivity");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
but i am getting a RuntimeException saying that unable to start activity component : android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.github.barcodeeye.scan}
can any one help me where i am going wrong
Thanks & Regards.
Nagendra
You will need to register CaptureActivity Activity in the AndroidManifest.xml
<activity
android:name="com.github.barcodeeye.scan.CaptureActivity"
android:clearTaskOnLaunch="true"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="landscape"
android:stateNotNeeded="true"
android:theme="#style/CaptureTheme"
android:windowSoftInputMode="stateAlwaysHidden" >
<intent-filter>
<action android:name="com.github.barcodeeye.SCAN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Here is how I use BarCodeEye:
private void startScanActivityForResult(Bundle extras)
{
Intent intentScan = new Intent("com.github.barcodeeye.SCAN");
intentScan.setPackage("com.github.barcodeeye");
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intentScan.putExtras(extras);
intentScan.putExtra("SCAN_MODE", "QR_CODE_MODE");
intentScan.putExtra("RESULT_DISPLAY_DURATION_MS", 1000L);
intentScan.putExtra("SAVE_HISTORY", false);
intentScan.putExtra("PROMPT_MESSAGE", "QR scan http://user:pass#server");
WtcLog.info(TAG, "startScanActivityForResult: startActivityForResult(intentScan=" + intentScan + ", REQUEST_SCAN)");
startActivityForResult(intentScan, REQUEST_SCAN);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
WtcLog.info(TAG, "onActivityResult data=" + WtcUtilsPlatform.toString(data));
Bundle extras = null;
if (data != null)
{
extras = data.getExtras();
}
switch (requestCode)
{
case REQUEST_SCAN:
{
WtcLog.info(TAG, "onActivityResult: REQUEST_SCAN");
if (resultCode == RESULT_OK)
{
WtcLog.info(TAG, "onActivityResult: resultCode == RESULT_OK");
String result = data.getStringExtra("SCAN_RESULT");
extras = validateScan(result);
/// your logic here
}
else
{
WtcLog.warn(TAG, "onActivityResult: resultCode != RESULT_OK; exiting");
// your logic here
finish();
}
break;
}
}
}
private Bundle validateScan(String result)
{
Bundle extras = new Bundle();
String[] userpass;
try
{
URI uri = new URI(result);
String userinfo = uri.getRawUserInfo();
if (WtcString.isNullOrEmpty(userinfo))
{
throw new URISyntaxException(result, "");
}
userpass = userinfo.split(":", 2);
if (userpass.length != 2)
{
throw new URISyntaxException(result, "");
}
String server = uri.getHost();
if (WtcString.isNullOrEmpty(server))
{
throw new URISyntaxException(result, "");
}
extras.putString("server", server);
}
catch (URISyntaxException e)
{
WtcLog.error(TAG, "validateScan: EXCEPTION", e);
extras.putString("error", "uri must be in format \"http://username:password#server\"");
return extras;
}
try
{
String username = URLDecoder.decode(userpass[0], "UTF-8");
extras.putString("username", username);
String password = URLDecoder.decode(userpass[1], "UTF-8");
extras.putString("password", password);
}
catch (UnsupportedEncodingException e)
{
WtcLog.error(TAG, "validateScan: EXCEPTION", e);
extras.putString("error", "username and password must be UTF-8");
return extras;
}
return extras;
}
Related
I'm creating a mobile application using Xamarin forms, As part of my implementation, I have a requirement to to show file chooser on clicking on camera icon which is loaded in webView and load the image to webView. currently file chooser is being shown, but image is not getting added.
public override bool OnShowFileChooser(Android.Webkit.WebView webView, Android.Webkit.IValueCallback filePathCallback, FileChooserParams fileChooserParams) {
Intent takePictureIntent = new Intent(MediaStore.ActionImageCapture);
if (takePictureIntent.ResolveActivity(mContext.PackageManager) != null) {
Java.IO.File photoFile = null;
try {
string folder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
photoFile = new Java.IO.File(folder, "image" + DateTime.Now.Millisecond + ".png");
takePictureIntent.PutExtra("PhotoPath", mCameraPhotoPath);
//photoFile = createImageFile();
//takePictureIntent.PutExtra("PhotoPath", mCameraPhotoPath);
} catch (Exception e) {
Console.WriteLine("catch the Exception" + e);
}
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.AbsolutePath;
//pictureUri = FileProvider.GetUriForFile(mContext, "asdasd", photoFile);
takePictureIntent.PutExtra(Android.Provider.MediaStore.ExtraOutput, photoFile);
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ActionGetContent);
contentSelectionIntent.AddCategory(Intent.CategoryOpenable);
contentSelectionIntent.SetType(file_type);
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[] {
takePictureIntent
};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ActionChooser);
chooserIntent.PutExtra(Intent.ExtraIntent, contentSelectionIntent);
chooserIntent.PutExtra(Intent.ExtraTitle, "File chooser");
chooserIntent.PutExtra(Intent.ExtraInitialIntents, intentArray);
//mContext.StartActivity(chooserIntent);
mContext.StartActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
private Java.IO.File createImageFile() {
// Create an image file name
string timeStamp = Android.OS.SystemClock.CurrentThreadTimeMillis().ToString();
string imageFileName = "JPEG_" + timeStamp + "_";
Java.IO.File storageDir;
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Gingerbread) {
storageDir = mContext.CacheDir;
} else {
storageDir = mContext.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures);
}
//new Java.IO.File(mContext.GetExternalFilesDir(null).AbsolutePath);
Java.IO.File imageFile = Java.IO.File.CreateTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
At first, please add the following code into the AndroidManifest.xml to declare the permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.Read_EXTERNAL_STORAGE" />
And then request the permission in the MainActivity's construction method.
var read = await Permissions.RequestAsync<Permissions.StorageRead>();
var write = await Permissions.RequestAsync<Permissions.StorageWrite>();
Finally, please override the OnActivityResult method of the Mainactivity:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (data != null)
{
if (requestCode == INPUT_FILE_REQUEST_CODE)// the value of the INPUT_FILE_REQUEST_CODE
{
if (null == this.message)
{
return;
}
this.message.OnReceiveValue(WebChromeClient.FileChooserParams.ParseResult((int)resultCode, data));
this.message = null;
}
}
}
we have implement file chooser for web view. it works successfully when attachment is selected, but fails when cancelled without file specification. The file chooser just stops to react on click
any help is appreciated. Thanks
we use chrome client. it works fine if in all cases, file selection is listed. but even from the first file selection is cancelled, no longer file chooser will work. It is Xamarin.Android app based fully on webview
Our code is:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == _mUploadMessage)
return;
// Check that the response is a good one
if (resultCode == Result.Ok)
{
Android.Net.Uri[] results = null;
if (intent == null)
{
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null)
{
results = new Android.Net.Uri[] { Android.Net.Uri.Parse(mCameraPhotoPath) };
}
}
else
{
if (intent.DataString != null)
{
results = new Android.Net.Uri[] { Android.Net.Uri.Parse(intent.DataString) };
}
}
_mUploadMessage.OnReceiveValue(results);
_mUploadMessage = null;
}
}
}
Chrome client:
var chrome = new FileChooserWebChromeClient((uploadMsg) =>
{
_mUploadMessage = uploadMsg;
mCameraPhotoPath = null;
Intent takePictureIntent = new Intent(Android.Provider.MediaStore.ActionImageCapture);
//Create the File where the photo should go
File photoFile = null;
try
{
string folder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
photoFile = new File(folder, "image" + DateTime.Now.Millisecond + ".png");
takePictureIntent.PutExtra("PhotoPath", mCameraPhotoPath);
}
catch (IOException ex)
{
// Error occurred while creating the File
System.Console.WriteLine("" + ex.ToString());
}
// Continue only if the File was successfully created
if (photoFile != null)
{
mCameraPhotoPath = "file:" + photoFile.AbsolutePath;
takePictureIntent.PutExtra(Android.Provider.MediaStore.ExtraOutput,
Android.Net.Uri.FromFile(photoFile));
}
else
{
takePictureIntent = null;
}
Intent contentSelectionIntent = new Intent(Intent.ActionGetContent);
contentSelectionIntent.AddCategory(Intent.CategoryOpenable);
contentSelectionIntent.SetType("image/*");
Intent[] intentArray;
if (takePictureIntent != null)
{
intentArray = new Intent[] { takePictureIntent };
}
else
{
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ActionChooser);
chooserIntent.PutExtra(Intent.ExtraIntent, contentSelectionIntent);
chooserIntent.PutExtra(Intent.ExtraTitle, this.GetStringFromResource(Resource.String.chose_photo));
chooserIntent.PutExtra(Intent.ExtraInitialIntents, intentArray);
base.StartActivityForResult(chooserIntent, HarmonyAndroid.AndroidMainActivity.FILECHOOSER_RESULTCODE);
});
return chrome;
Part 2
class FileChooserWebChromeClient : WebChromeClient
{
Action<IValueCallback> callback;
public FileChooserWebChromeClient(Action<IValueCallback> callback)
{
this.callback = callback;
}
public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
callback(filePathCallback);
return true;
}
public override void OnCloseWindow(WebView window)
{
base.OnCloseWindow(window);
}
}
Part 3
webView.ImprovePerformance();
webView.SetWebViewClient(new HomeWebViewClient(customWebViewClientListener, clientId));
webView.SetWebChromeClient(chrome);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.DomStorageEnabled = true;
webView.SetDownloadListener(new CustomDownloadListener(activity, customDownloadListener));
webView.AddJavascriptInterface(new JavaScriptToCSharpCommunication(activity, javaScriptToCSharpCommunicationListener), Constants.JS_CSHARP_COMMUNICATOR_NAME);
Try to give a null object to the uri callback, when the resultCode is not RESULT_OK.
add in your OnActivityResult method:
if (resultCode != Result.Ok)
{
_mUploadMessage.OnReceiveValue(null);
_mUploadMessage = null;
return;
}
since I updated targetSdkVersion to 29 I am facing many troubles, this one realted to downloading - installing - updating my app. The apk with the new version is downloaded successfully (because I find it through the file explorer in my phone) but I do not think is installed properly. Once the process finishes it looks like the screen is restarted because it blinks, but the app is not updated (and I know it because in the main screen it shows the version). My code is:
public static boolean openFile(String intentAction) { // in this case it is Intent.ACTION_INSTALL_PACKAGE
try {
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "myApp.apk");
if (file.exists()) {
Uri uri;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
uri = Uri.fromFile(file);
} else {
uri = FileProvider.getUriForFile(appContext, appContext.getPackageName() + ".provider", file);
}
return installPackage(file, uri);
}
} catch (Exception e) {
generateExceptionLog(e);
}
return false;
}
private static boolean installPackage(File file, Uri uri) {
PackageInstaller packageInstaller = appContext.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
params.setAppPackageName(file.getAbsolutePath());
try {
int sessionId = packageInstaller.createSession(params);
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
OutputStream packageInSession = session.openWrite("package", 0, -1);
InputStream input;
input = appContext.getContentResolver().openInputStream(uri);
if (input != null) {
generateInfoLog("input.available: " + input.available());
byte[] buffer = new byte[16384];
int n;
while ((n = input.read(buffer)) >= 0) {
packageInSession.write(buffer, 0, n);
}
} else {
generateExceptionLog("INSTALLATION FAILED");
}
packageInSession.close();
input.close();
//Intent intent2 = new Intent(appContext, ActMain.class);
Intent intent2 = new Intent(appContext, LauncherReceiver.class);
intent2.setAction(ACTION_PACKAGE_INSTALED);
//intent.setAction(Intent.PACKAGE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
appContext,
sessionId,
intent2,
PendingIntent.FLAG_UPDATE_CURRENT);
IntentSender statusReceiver = pendingIntent.getIntentSender();
session.commit(statusReceiver);
} catch (Exception e) {
generateExceptionLog(e);
return false;
}
return true;
}
My Receiver:
public class LauncherReceiver extends BroadcastReceiver {
public static final String ACTION_PACKAGE_INSTALED = "com.gim.androidv2.action.PACKAGE_INSTALED";
#Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, ActMain.class);
intent.setAction(ACTION_PACKAGE_INSTALED);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(startIntent);
}
}
And the manifest:
<receiver android:name=".LauncherReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.aaa.aaa.action.START"></action>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
I have an forms app where i need to pick "1 to many" images from the phone storage.
For this i use the dependency injection system.
My problem is the somewhere i get an Android.netUri that resolves to a file that do not exist... and to a file name that i have never seen before.
The kicker is that if i pick pictures that was takes within the last couple of hours this code works...
Im am at the end of my hoap, i really hope someone can point me to something that i'm doing wrong.
i start the Picker activity with:
[assembly: Dependency(typeof(ImagePickerService))]
namespace MyApp.Droid
{
public class ImagePickerService : Java.Lang.Object, IImagePickerService
{
public async Task OpenGallery()
{
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (status != PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
{
Toast.MakeText(CrossCurrentActivity.Current.Activity, "Need Storage permission to access to your photos.", ToastLength.Long).Show();
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Storage });
status = results[Permission.Storage];
}
if (status == PermissionStatus.Granted)
{
Toast.MakeText(CrossCurrentActivity.Current.Activity, "Pick max 20 images", ToastLength.Long).Show();
var imageIntent = new Intent(Intent.ActionPick);
imageIntent.SetType("image/*");
imageIntent.PutExtra(Intent.ExtraAllowMultiple, true);
imageIntent.SetAction(Intent.ActionPick);
CrossCurrentActivity.Current.Activity.StartActivityForResult(Intent.CreateChooser(imageIntent, "Pick pictures"), 100);
}
else if (status != PermissionStatus.Unknown)
{
Toast.MakeText(CrossCurrentActivity.Current.Activity, "Permission Denied. Can not continue, try again.", ToastLength.Long).Show();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Toast.MakeText(CrossCurrentActivity.Current.Activity, "Error. Can not continue, try again.", ToastLength.Long).Show();
}
}
}
then in my MainActivity.cs i have the OnActivityResult
I have tried to use the ContentResolver.OpenInputStream to get the image bytes with no luck, so this is commented out atm.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == OPENGALLERYCODE && resultCode == Result.Ok)
{
List<string> images = new List<string>();
if (data != null)
{
ClipData clipData = data.ClipData;
if (clipData != null)
{
for (int i = 0; i < clipData.ItemCount; i++)
{
ClipData.Item item = clipData.GetItemAt(i);
/*
var stream = ContentResolver.OpenInputStream(item.Uri); //This throws "FileNotFound"
byte[] byteArray;
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
byteArray = memoryStream.ToArray();
stream.Close();
stream = null;
}
stream = ContentResolver.OpenInputStream(item.Uri);
var exif = new ExifInterface(stream);
stream.Close();
*/
Android.Net.Uri uri = item.Uri;
var path = GetActualPathFromFile(uri);
if (path != null)
{
var tmpImgPath = RotateToOriginalDimention(path);
images.Add(tmpImgPath);
}
}
}
else
{
Android.Net.Uri uri = data.Data;
var path = GetActualPathFromFile(uri);
if (path != null)
{
var tmpImgPath = RotateToOriginalDimention(path);
images.Add(tmpImgPath);
}
}
MessagingCenter.Send<App, List<string>>((App)Xamarin.Forms.Application.Current, "ImagesSelected", images);
}
}
}
And the GetActualPathFromFile (also in my MainActivity.cs)
The hole func is below but i hit this part of the code and get at "FileNotFound"
(...)
else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
{
var retval2 = getDataColumn(this, uri, null, null);
if (File.Exists(retval2)) //<----------------------- This returns "false"
{
return retval2;
}
else
{
throw new Exception("file not found " + retval2);
}
}
(...)
The Hole GetActualPathFromFile
private string GetActualPathFromFile(Android.Net.Uri uri)
{
bool isKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat;
if (isKitKat && DocumentsContract.IsDocumentUri(this, uri))
{
// ExternalStorageProvider
if (isExternalStorageDocument(uri))
{
string docId = DocumentsContract.GetDocumentId(uri);
char[] chars = { ':' };
string[] split = docId.Split(chars);
string type = split[0];
if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase))
{
var retval = Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
if (File.Exists(retval))
{
return retval;
}
else
{
throw new Exception("file not found " + retval);
}
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri))
{
string id = DocumentsContract.GetDocumentId(uri);
Android.Net.Uri contentUri = ContentUris.WithAppendedId(
Android.Net.Uri.Parse("content://downloads/public_downloads"), long.Parse(id));
//System.Diagnostics.Debug.WriteLine(contentUri.ToString());
var retval = getDataColumn(this, contentUri, null, null);
if (File.Exists(retval))
{
return retval;
}
else
{
throw new Exception("file not found " + retval);
}
}
// MediaProvider
else if (isMediaDocument(uri))
{
String docId = DocumentsContract.GetDocumentId(uri);
char[] chars = { ':' };
String[] split = docId.Split(chars);
String type = split[0];
Android.Net.Uri contentUri = null;
if ("image".Equals(type))
{
contentUri = MediaStore.Images.Media.ExternalContentUri;
}
else if ("video".Equals(type))
{
contentUri = MediaStore.Video.Media.ExternalContentUri;
}
else if ("audio".Equals(type))
{
contentUri = MediaStore.Audio.Media.ExternalContentUri;
}
String selection = "_id=?";
String[] selectionArgs = new String[]
{
split[1]
};
var retval = getDataColumn(this, contentUri, selection, selectionArgs);
if (File.Exists(retval))
{
return retval;
}
else
{
throw new Exception("file not found " + retval);
}
}
}
// MediaStore (and general)
else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
{
// Return the remote address
if (isGooglePhotosUri(uri))
{
var retval = uri.LastPathSegment;
if (File.Exists(retval))
{
return retval;
}
else
{
throw new Exception("file not found " + retval);
}
}
var retval2 = getDataColumn(this, uri, null, null);
if (File.Exists(retval2))
{
return retval2;
}
else
{
throw new Exception("file not found " + retval2);
}
}
// File
else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase))
{
var retval = uri.Path;
if (File.Exists(retval))
{
return retval;
}
else
{
throw new Exception("file not found " + retval);
}
}
throw new Exception("file not found ");
}
public static String getDataColumn(Context context, Android.Net.Uri uri, String selection, String[] selectionArgs)
{
ICursor cursor = null;
String column = "_data";
String[] projection =
{
column
};
try
{
cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.MoveToFirst())
{
int index = cursor.GetColumnIndexOrThrow(column);
return cursor.GetString(index);
}
}
finally
{
if (cursor != null)
cursor.Close();
}
return null;
}
//Whether the Uri authority is ExternalStorageProvider.
public static bool isExternalStorageDocument(Android.Net.Uri uri)
{
return "com.android.externalstorage.documents".Equals(uri.Authority);
}
//Whether the Uri authority is DownloadsProvider.
public static bool isDownloadsDocument(Android.Net.Uri uri)
{
return "com.android.providers.downloads.documents".Equals(uri.Authority);
}
//Whether the Uri authority is MediaProvider.
public static bool isMediaDocument(Android.Net.Uri uri)
{
return "com.android.providers.media.documents".Equals(uri.Authority);
}
//Whether the Uri authority is Google Photos.
public static bool isGooglePhotosUri(Android.Net.Uri uri)
{
return "com.google.android.apps.photos.content".Equals(uri.Authority);
}
Found out that the real problem was that Google Photos App was not updating and was still showing images that were deleted.
After 2x reboot of the phone, Google Photos app finally updated.
So this looks more like a cache problem with Google Foto than a xamarin problem.
I make the HttpURLConnection to get data from MySQL (android+jsp+MySQL) in my android's AsyncTask.
when I start 'A activity', the first is OK. I can start doInBackground. but when I start the 'A activity' next, I can't start doInBackgound when I start 'A activity' repeatedly.
I want to start doInBackground whenever I start the 'A activity' repeatedly.
because I get data from MySQL in doInBackground.
I used to "task.cancel(true)" but this not working.
I'm nuwbe in android, please tell me how to start doInBackground repeatedly.
thank advance.
behind is my code.
oncreate code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_inventory);
...........
connectJSP = new getInventoryFromMySQL();
connectJSP.execute();
...........
}
onBackPressed code
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
connectJSP.cancel(true);
super.onBackPressed();
}
}
AsyncTask code
private class getInventoryFromMySQL extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... sId) {
String sResult = "Error";
try {
//URL setting and access
URL url = new URL("http://-----.com/*****.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//setting
conn.setRequestMethod("POST");
// connection values
String sendBicycleName = bicycleName;
String sendBicycleYear = bicycleYear;
//StringBuffer
StringBuffer buffer = new StringBuffer();
buffer.append("sendBicycleName").append("=").append(sendBicycleName).append("&");
buffer.append("sendBicycleYear").append("=").append(sendBicycleYear);
//put data into JSP
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
osw.write(buffer.toString());
osw.flush();
//get data from JSP
InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(tmp);
String str;
//fit the order with JSP(garbage values)
reader.readLine(); reader.readLine(); reader.readLine(); reader.readLine();
//get data from JSP
for(;;) {
if((str = reader.readLine()) != null && (str != "") && (str != " ") && (str != "null")) {
mysqlStoreId[countInventory] = str;
for(int c=0; c<5; c++) {
for(int s=0; s<8; s++) {
str = reader.readLine();
mysqlInventory[countInventory][c][s] = Integer.parseInt(str);
}
}
countInventory++;
} else if(str == null && str == "null") {
//finish for if values equals null
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sResult;
}
}
I find the answer. I check all code's log.
the problem is that 'doInBackground' have an error. there is no an else in 'for(;;)' so AsyncTack make 'onCancelled()'. but I'm not write the 'onCancelled()' code.
when I add onCancelled(), I can cancel(true) and re-start the Asynctask.
Thank!