I got stuck on a project; and unable to understand the error. Kindly help me on that. I am getting Case Expressions Must be Constant Expressions on my every R.id , I am sharing the code here.
I am getting this error on every Case R.id ; kindly suggest
public void onClick(View v) {
int currentBgColor = PreferencesUtils.getBgColor(this);
switch (v.getId()) {
case R.id.btn_home:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
dismissMainCling(v);
toggle();
break;
case R.id.btn_bookmark:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
boolean isBookmarked = false;
for (Bookmark bm : mBookmarkList) {
if (bm.partId == mCurrentPart && bm.chapId == mCurrentChap) {
isBookmarked = true;
break;
}
}
if (isBookmarked) {
showUnBookmarkDialog(mCurrentPart, mCurrentChap);
} else {
showSaveBookmarkDialog(mCurrentPart, mCurrentChap);
}
break;
case R.id.btn_bm_list:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
// toggleSecondary();
break;
case R.id.btn_background:
if (!isShowBgSelect) {
showBgSelector();
isShowBgSelect = true;
} else {
hideBgSelector(true);
isShowBgSelect = false;
}
mBtnBgSelect.setEnabled(false);
mBtnBgSelect.setSelected(true);
break;
case R.id.btn_fullscreen:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
if (isFullScreen) {
showController();
mFullScreenButton.setEnabled(false);
isFullScreen = false;
} else {
hideController();
isFullScreen = true;
}
break;
case R.id.btn_home_slidingmenu_left:
toggle();
break;
case R.id.btn_home_slidingmenu_right:
// toggleSecondary();
break;
case R.id.btn_bg_white:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
if (currentBgColor != Constants.BG_COLOR_WHITE) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_WHITE);
loadPart(mCurrentPart, mCurrentChap);
}
break;
case R.id.btn_bg_khaki:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
if (currentBgColor != Constants.BG_COLOR_KHAKI) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_KHAKI);
loadPart(mCurrentPart, mCurrentChap);
}
break;
case R.id.btn_bg_sepia:
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
if (currentBgColor != Constants.BG_COLOR_SEPIA) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_SEPIA);
loadPart(mCurrentPart, mCurrentChap);
}
break;
case R.id.btn_about:
showAboutDialog();
break;
case R.id.tv_contact_us:
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { getResources()
.getString(R.string.dialog_about_email) });
email.putExtra(Intent.EXTRA_SUBJECT,
getText(R.string.contact_prefix) + " "
+ getText(R.string.app_name));
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
getText(R.string.contact_chooser)));
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int currentBgColor = PreferencesUtils.getBgColor(this);
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
case R.id.menu_bookmark:
boolean isBookmarked = false;
for (Bookmark bm : mBookmarkList) {
if (bm.partId == mCurrentPart && bm.chapId == mCurrentChap) {
isBookmarked = true;
break;
}
}
if (isBookmarked) {
showUnBookmarkDialog(mCurrentPart, mCurrentChap);
} else {
showSaveBookmarkDialog(mCurrentPart, mCurrentChap);
}
return true;
case R.id.menu_bookmarked_chap:
// toggleSecondary();
return true;
case R.id.menu_bg_white:
if (currentBgColor != Constants.BG_COLOR_WHITE) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_WHITE);
loadPart(mCurrentPart, mCurrentChap);
}
return true;
case R.id.menu_bg_khaki:
if (currentBgColor != Constants.BG_COLOR_KHAKI) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_KHAKI);
loadPart(mCurrentPart, mCurrentChap);
}
return true;
case R.id.menu_bg_sepia:
if (currentBgColor != Constants.BG_COLOR_SEPIA) {
PreferencesUtils.saveBgColor(this, Constants.BG_COLOR_SEPIA);
loadPart(mCurrentPart, mCurrentChap);
}
return true;
case R.id.menu_about:
showAboutDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
if (isShowBgSelect) {
hideBgSelector(false);
isShowBgSelect = false;
}
return super.onPrepareOptionsMenu(menu);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
Related
public class EEmployeeApplication extends Application {
public void onCreate() {
super.onCreate();
try {
mContext = getApplicationContext();
dbHandler = new DataBaseModule(this);
dbHandler.getReadableDatabase();
dbHandler.close();
dbHandler = getDbHandler();
curUser = dbHandler.getActiveUserInfo();
eEMPSharedPreference = new eEmployeeSharedPreference();
DataSyncStartAlarm newAlarm = new DataSyncStartAlarm();
newAlarm.startDataSyncAlarm(mContext, null);
} catch (Exception e) {
Log.d("eEmp/Application ", e.toString());
}
}
#Override
public void onTerminate() {
try {
} catch (Exception e) {
Log.d("eEmp/Application ", e.toString());
}
super.onTerminate();
}
public static boolean isNetAvailable() {
try {
ConnectivityManager connectivity = (ConnectivityManager)
mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
{
NetworkInfo netInfo = connectivity.getActiveNetworkInfo();
if (netInfo != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if ((info == null) || (!netInfo.isConnectedOrConnecting())) {
return false;
} else {
return true;
}
}
}
return false;
} catch (Exception e) {
Log.d("eEmp/Application", e.toString());
return false;
}
}
public DataBaseModule getDbHandler() {
return dbHandler;
}
public void checkUserAvailability(Activity activity) {
try {
if (curUser == null) // No Employee registered in local DB
{
activity.finish();
Intent loginScreen = new Intent(mContext, Login_Activity.class);
loginScreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
loginScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(loginScreen);
} else {
activity.finish();
List<EmpZonesResponseDTO> empZonesResponseDTOS ;
empZonesResponseDTOS = eEMPSharedPreference.getZones(mContext);
if (empZonesResponseDTOS == null){
Intent dashboardAct = new Intent(mContext, Login_Activity.class);
dashboardAct.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
dashboardAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dashboardAct);
}else {
Intent dashboardAct = new Intent(mContext, NavigationActivity.class);
dashboardAct.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
dashboardAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dashboardAct);
}
}
} catch (Exception except) {
Log.d("eEmp/LoginActivity", except.toString());
}
}
public static Context getContext() {
return mContext;
}
public void SyncMasterData(NavigationActivity NavActivity) {
try{
if (isNetAvailable()) {
Log.d("eEmp/LoginCheck", "Internet is available");
SyncMasterDataDownloadTask SyncTask = new SyncMasterDataDownloadTask();
SyncTask.setContextandActivity(this,NavActivity);
SyncTask.execute();
} else
{
Log.d("eEmp/SyncMasterData", "Internet is not available");
NavActivity.DismissMasterDataDownload();
Snackbar
.make(NavActivity.navigationView,
"No Internet connection, Unable to Sync Account", Snackbar.LENGTH_LONG)
.show();
}
}catch (Exception e){
e.printStackTrace();
}
}
public String getActivityFragmentTag(EmpConstants.WorkType aSelectedWorkType) {
String selectedTag;
switch (aSelectedWorkType) {
case Dashboard:
selectedTag = EmpConstants.DashBoard_Info_Tag;
break;
case Profile:
selectedTag = EmpConstants.Personal_Info_Tag;
break;
case Entry:
selectedTag = EmpConstants.Entry_Info_Tag;
break;
case Plan:
selectedTag = EmpConstants.Plan_Info_Tag;
break;
case Report:
selectedTag = EmpConstants.Report_Info_Tag;
break;
case QR:
selectedTag = EmpConstants.QR_Info_Tag;
break;
case Miscellaneous:
selectedTag = EmpConstants.Miscellaneous_Info_Tag;
break;
case Nothing:
selectedTag = "";
break;
default:
selectedTag = "";
break;
}
return selectedTag;
}
// Location Method
public GpsLocationListener getGpsLocationListener() {
try {
if (gpsLocationListener == null) {
gpsLocationListener = new GpsLocationListener();
gpsLocationListener.getGPSCordinates();
//Log.d("eEmp/getGPSLocationList","Location Listener Created");
}
} catch (Exception gpsLocationExp) {
Log.d("eEmp/getGPSLocationList", "Error raised due to " + gpsLocationExp.toString());
}
return gpsLocationListener;
}
public String getEmpImageDirPath() {
try {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()
+ EmpConstants.appDir;
} catch (Exception e) {
Log.d("eEmp/ImgDir", e.toString());
return "";
}
}
public String getEmpThumbImageDirPath() {
try {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()
+ EmpConstants.thumbnailDir;
} catch (Exception e) {
Log.d("eEmp/ThumbImgDir", e.toString());
return "";
}
}
public Bitmap loadFromFile(String filename) {
try {
File f = new File(filename);
if (!f.exists()) {
return null;
}
final int width = EmpConstants.DisplayWidth;//mDisplay.widthPixels;
final int height = EmpConstants.DisplayHeight;//mDisplay.heightPixels;
Bitmap tmp = decodeSampledBitmapFromResource(filename, width, height);
return tmp;
} catch (Exception e) {
return null;
}
}
public static Bitmap decodeSampledBitmapFromResource(String imgFile,
int reqWidth, int reqHeight) {
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgFile, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imgFile, options);
} catch (Exception sampleBitmapConvExp) {
Log.d("eEmp/sampleBMPConv", "Error raised due to " + sampleBitmapConvExp.toString());
return null;
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public void checkImageDirectories() {
try {
File eEmpPhotosDir = new File(getEmpImageDirPath());
if (!eEmpPhotosDir.exists()) {
eEmpPhotosDir.mkdir();
}
File eEmpThumbPhotosDir = new File(getEmpThumbImageDirPath());
if (!eEmpThumbPhotosDir.exists())
eEmpThumbPhotosDir.mkdir();
} catch (Exception e) {
Log.d("eEmp/CheckDir", e.toString());
}
}
public void showFullImage(Context context, String curImgFile) {
try {
if (curImgFile.length() != 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
final Dialog nagDialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
nagDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
nagDialog.setCancelable(false);
nagDialog.setContentView(R.layout.preview_image);
Button btnClose = (Button) nagDialog.findViewById(R.id.btnIvClose);
ImageView ivPreview = (ImageView) nagDialog.findViewById(R.id.iv_preview_image);
TextView tvLoading = (TextView) nagDialog.findViewById(R.id.tvImgLoading);
ivPreview.setTag(tvLoading);
ImageRequest imgOrgReq = new ImageRequest();
imgOrgReq.imgView = ivPreview;
imgOrgReq.ImgType = EmpConstants.ImageLoadingType.OriginalImage;
imgOrgReq.context = (EEmployeeApplication) mContext;
BitmapWorkerTask statusImg = new BitmapWorkerTask(imgOrgReq);
statusImg.execute(curImgFile);
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
nagDialog.dismiss();
}
});
nagDialog.show();
}
} catch (Exception e) {
Log.d("eEmp/ShowFullImg", e.getLocalizedMessage());
}
}
// delete selected image from external storage
public void deleteSelImgFromStorage(String imgPath, Context context) {
try {
File imgFile = new File(imgPath);
if (imgPath.contains(EmpConstants.appName)) {
if (imgFile.exists()) {
imgFile.delete();
}
MediaScannerConnection.scanFile(context, new String[]{imgPath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
}
} catch (Exception e) {
Log.i("Delete image", e.toString());
}
}
// For Marshmallow
// To Check permissions for Marshmallow
public List<String> askPermissions(ArrayList<EmpConstants.PermissionsList> ReqPermnsList) {
List<String> permissionsNeeded = new ArrayList<String>();
for (EmpConstants.PermissionsList perm : ReqPermnsList) {
switch (perm) {
case PhonePerm:
if (addPermission(Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
break;
case External_StoragePerm:
if (addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
permissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (addPermission(Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
break;
case LocationPerm:
if (addPermission(Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
if (addPermission(Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
break;
case CameraPerm:
if (addPermission(Manifest.permission.CAMERA))
permissionsNeeded.add(Manifest.permission.CAMERA);
break;
}
}
return permissionsNeeded;
}
public boolean addPermission(String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
return true;
}
}
return false;
}
public boolean isAnyPermissionRequired(ArrayList<EmpConstants.PermissionsList> ReqPermnsList) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
if (ReqPermnsList.size() == 0) {
return false;
} else {
for (EmpConstants.PermissionsList perm : ReqPermnsList) {
switch (perm) {
case PhonePerm:
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED) {
return true;
}
break;
case External_StoragePerm:
if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
|| (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)) {
return true;
}
break;
case LocationPerm:
if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED)
|| (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED)) {
return true;
}
break;
case CameraPerm:
if ((checkSelfPermission(Manifest.permission.CAMERA)== PackageManager.PERMISSION_DENIED)){
return true;
}
break;
default:
return false;
}
}
return false;
}
} catch (Exception checkPermExpt) {
Log.d("eEmp/CheckPerms", "Exception due to " + checkPermExpt.toString());
}
}
return false;
}
public void getNetworkProvideLocation() {
try {
if (longitude_Value == 0 || latitude_Value == 0) {
LocationManager locationManager = (LocationManager) EEmployeeApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnable) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location lastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (lastLocation != null) {
longitude_Value = lastLocation.getLongitude();
latitude_Value = lastLocation.getLatitude();
Log.d("eEmp/getNwValues", "Network Coordinates Updated" );
}
} else {
return;
}
}
} catch (Exception networkLocExp) {
Log.d("eEmp/getNwValues", "Exception due to " + networkLocExp.toString());
}
public int isValidUser() {
try {
if (isNetAvailable()) {
HTTPCommunication loginHTTPRequest;
EEmployeeHTTPResponse result;
if (curUser != null) {
Log.d("eEmp/ValLogin", "Validating User in Background");
loginHTTPRequest = new HTTPCommunication();
EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);
loginInfo.EMPID = curUser.getEMPID();
loginInfo.Password = curUser.getPassword();
result = loginHTTPRequest.SendHTTPRequest(loginInfo);
if (result != null) {
if (result.HTTPStatusCode == 200) {
if (result.Data != null) {
return result.Data.ResponseCode;
}
}
}
}
}
return 0; // Invalid User
} catch (Exception e) {
Log.d("eEmp/ValLoginError", e.toString());
return 0;
}
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
LaunchingActivity.java
public class LaunchingActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, OnTaskStateChange {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_launching);
context = (EEmployeeApplication) EEmployeeApplication.getContext();
if (EEmployeeApplication.isNetAvailable()){
// Read IMEI Number
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ArrayList<EmpConstants.PermissionsList> reqPermissionsList = new ArrayList<>();
if ((context.eEMPSharedPreference != null) && (context.eEMPSharedPreference.getIMEI().isEmpty())) {
reqPermissionsList.add(EmpConstants.PermissionsList.PhonePerm);
}
reqPermissionsList.add(EmpConstants.PermissionsList.External_StoragePerm);
reqPermissionsList.add(EmpConstants.PermissionsList.LocationPerm);
reqPermissionsList.add(EmpConstants.PermissionsList.CameraPerm);
// Check All Permissions
if (context.isAnyPermissionRequired(reqPermissionsList)) {
requestPermission(context.askPermissions(reqPermissionsList));
} else {
readIMEINumber();
}
} else {
readIMEINumber();
}
int x = BuildConfig.VERSION_CODE;
AppVersionTask mTask = new AppVersionTask();
mTask.setListener(this);
APPVERREQ aRequest = new APPVERREQ();
aRequest.requestType = EmpConstants.HTTPRequestType.App_Ver;
APP_VERSION loginInfo = new APP_VERSION();
loginInfo.APP_VER = BuildConfig.VERSION_NAME;
aRequest.RequestObj = loginInfo;
mTask.execute(aRequest);
}
try {
Log.d("eEmp/Test", "MasterdataTaskStarted");
MasterDataLoadTask masterDataLoadTask = new MasterDataLoadTask();
masterDataLoadTask.setContextandActivity(context, this);
masterDataLoadTask.execute();
} catch (Exception MasterDataExcept) {
Log.d("eEmp/MstrDataTask", "Exception Occurred due to " + MasterDataExcept.toString());
context.checkUserAvailability(this);
}
Log.d("eEmp/LaunchCreate", "Launching Created");
} catch (Exception e) {
Log.d("eEmp/LaunchActvty", e.toString());
}
}
#Override
protected void onStart() {
super.onStart();
if ((mGoogleApiClient != null) && (!mGoogleApiClient.isConnected())) {
mGoogleApiClient.connect();
}
Log.d("eEMP/LaunchOnStart", "Launch OnStart");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
// For Marshmallow
// To Check permissions for Marshmallow
public void requestPermission(List<String> permissionsNeeded) {
if (permissionsNeeded.size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]),
EmpConstants.REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
readIMEINumber();
}
// The callback for the management of the user settings regarding location
private ResultCallback<LocationSettingsResult> mResultCallbackFromSettings = new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// GPS is already in On State
initiateLocationRequest();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
LaunchingActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
default:
context.checkUserAvailability(LaunchingActivity.this);
Log.e("eEmp/Location", "Settings change unavailable. We have no way to fix the settings so we won't show the dialog.");
break;
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
try {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
if (mGoogleApiClient.isConnected()) {
initiateLocationRequest();
}
break;
case Activity.RESULT_CANCELED:
context.checkUserAvailability(this);
break;
default:
break;
}
break;
}
} catch (Exception expt) {
Log.d("eEmp/AcvtResult", "Exception occurred due to " + expt.toString());
}
}
public void readIMEINumber() {
try {
if ((context.eEMPSharedPreference != null) && (context.eEMPSharedPreference.getIMEI().isEmpty())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
context.eEMPSharedPreference.setIMEI(telephonyManager.getDeviceId());
}
} else {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
context.eEMPSharedPreference.setIMEI(telephonyManager.getDeviceId());
}
}
if (!checkGPSStatus()) {
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (checkPlayServices()) {
LocationSettingsRequest.Builder locationSettingsRequestBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
locationSettingsRequestBuilder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, locationSettingsRequestBuilder.build());
result.setResultCallback(mResultCallbackFromSettings);
} else {
context.checkUserAvailability(this);
}
} else {
initiateLocationRequest();
}
} catch (Exception IMEIExp) {
Log.d("eEmp/IMEIGet", "Unable to get IMEI number due to " + IMEIExp.toString());
}
}
private boolean checkGPSStatus() {
try {
locationManager = (LocationManager) EEmployeeApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return true;
} else {
return false;
}
} catch (Exception chkGPSExpt) {
Log.d("eEmp/chkGPS", " Exception Raised due to " + chkGPSExpt.toString());
return false;
}
}
#Override
protected void onDestroy() {
Log.d("eEmp/Launching", "onDestroy Called");
super.onDestroy();
}
#Override
public void onTaskStateChange(EmpConstants.TaskState State, String Msg, EEmployeeHTTPResponse result) {
switch (State){
case RequestStarted:
break;
case ResponseRecvd:
break;
case ResponseProcessing:
break;
case ResponseProcessed:
if (result != null) {
if (result.HTTPStatusCode == 200) {
if (result.Data != null) {
APP_VERSION_RESPONSE aResponse = (APP_VERSION_RESPONSE) result.Data.ActionResult;
if (aResponse!= null){
if (aResponse.APP_VER.equals(BuildConfig.VERSION_NAME)){
try{
System.out.print("Yes");
}catch (Exception e){
Log.d("/eEmp","/Excp due to"+e.toString());
}
}
}
}
}
}
}
}
}
In my android app, I am asking for permissions at launching of application.
Actually What I want is after launching application, it should ask for permissions and take user input whether accepted or denied then only should move to login page.
But after launching, it is asked for permissions and it is not waiting for user input means permissions dialog is opening and after 5 to 10 seconds login page is opening even though user not responding to permissions dialog.
Why it is happening like this?
Any help would be appreciated.
Your assumption that the android framework should take care of the permission handling process and should hold on to loading the UI components until the user has interacted with the permission is wrong. You need to handle to permission interaction with the user yourself.
Here's how your flow should be :
Ask the user for permission.
Wait for the user to interact with the dialog box.
Read the interaction response and evaluate if the permission was granted.
If the permission was granted, load the UI components.
In other words, you need to make sure that you hold on to doing anything that requires the permissions until the permissions are actually there.
I need help with my code on Android, I've been trying and searching for 3 hours and no luck
so what I've is a library that call MediaPlayerSDK, I'm using it in my application to play videos. The library is using SurfaceView to play video. Now, I've to include getSurfaceView().setZOrderOnTop(true) to the player so I can show the video otherwise it will not be shown ( only audio). But, when I'm using getSurfaceView().setZOrderOnTop(true) I cannot put any view on top of player. I want to build a controllers to the player but I couldn't. I've tired getSurfaceView().setZOrderMediaOverlay(true) and same problem the video is not shown.
The XML code for Activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent">
<FrameLayout
android:id="#+id/playerViewLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:text="...."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ChTitle"
android:textColor="#color/white"
android:textStyle="bold"
android:layout_marginLeft="5dp"/>
<veg.mediaplayer.sdk.MediaPlayer
android:id="#+id/playerView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</FrameLayout>
</RelativeLayout>
And the java code is
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.MediaPlayerCallback {
private static final String TAG = "Tag";
private boolean playing = false;
private MediaPlayer player = null;
private enum PlayerStates
{
Busy,
ReadyForUse
};
private enum PlayerConnectType
{
Normal,
Reconnecting
};
private PlayerStates player_state = PlayerStates.ReadyForUse;
private PlayerConnectType reconnect_type = PlayerConnectType.Normal;
private int mOldMsg = 0;
// Event handler
private Handler handler = new Handler()
{
String strText = "Connecting";
String sText;
String sCode;
#Override
public void handleMessage(Message msg)
{
MediaPlayer.PlayerNotifyCodes status = (MediaPlayer.PlayerNotifyCodes) msg.obj;
switch (status)
{
case CP_CONNECT_STARTING:
if (reconnect_type == PlayerConnectType.Reconnecting)
strText = "Reconnecting";
else
strText = "Connecting";
player_state = PlayerStates.Busy;
//showStatusView();
reconnect_type = PlayerConnectType.Normal;
break;
case PLP_BUILD_SUCCESSFUL:
sText = player.getPropString(MediaPlayer.PlayerProperties.PP_PROPERTY_PLP_RESPONSE_TEXT);
sCode = player.getPropString(MediaPlayer.PlayerProperties.PP_PROPERTY_PLP_RESPONSE_CODE);
Log.i(TAG, "=Status PLP_BUILD_SUCCESSFUL: Response sText="+sText+" sCode="+sCode);
break;
case VRP_NEED_SURFACE:
player_state = PlayerStates.Busy;
//showVideoView();
break;
case PLP_PLAY_SUCCESSFUL:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
break;
case PLP_CLOSE_STARTING:
player_state = PlayerStates.Busy;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case PLP_CLOSE_SUCCESSFUL:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
System.gc();
setUIDisconnected();
break;
case PLP_CLOSE_FAILED:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case CP_CONNECT_FAILED:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case PLP_BUILD_FAILED:
sText = player.getPropString(MediaPlayer.PlayerProperties.PP_PROPERTY_PLP_RESPONSE_TEXT);
sCode = player.getPropString(MediaPlayer.PlayerProperties.PP_PROPERTY_PLP_RESPONSE_CODE);
Log.i(TAG, "=Status PLP_BUILD_FAILED: Response sText="+sText+" sCode="+sCode);
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case PLP_PLAY_FAILED:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case PLP_ERROR:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case CP_INTERRUPTED:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case CP_RECORD_STARTED:
Log.v(TAG, "=handleMessage CP_RECORD_STARTED");
{
String sFile = player.RecordGetFileName(1);
Toast.makeText(getApplicationContext(),"Record Started. File "+sFile, Toast.LENGTH_LONG).show();
}
break;
case CP_RECORD_STOPPED:
Log.v(TAG, "=handleMessage CP_RECORD_STOPPED");
{
String sFile = player.RecordGetFileName(0);
Toast.makeText(getApplicationContext(),"Record Stopped. File "+sFile, Toast.LENGTH_LONG).show();
}
break;
//case CONTENT_PROVIDER_ERROR_DISCONNECTED:
case CP_STOPPED:
case VDP_STOPPED:
case VRP_STOPPED:
case ADP_STOPPED:
case ARP_STOPPED:
if (player_state != PlayerStates.Busy)
{
//stopProgressTask();
player_state = PlayerStates.Busy;
player.Close();
//showStatusView();
player_state = PlayerStates.ReadyForUse;
setUIDisconnected();
}
break;
case CP_ERROR_DISCONNECTED:
if (player_state != PlayerStates.Busy)
{
player_state = PlayerStates.Busy;
player.Close();
//showStatusView();
player_state = PlayerStates.ReadyForUse;
setUIDisconnected();
Toast.makeText(getApplicationContext(), "Demo Version!",
Toast.LENGTH_SHORT).show();
}
break;
default:
player_state = PlayerStates.Busy;
}
}
};
// callback from Native Player
#Override
public int OnReceiveData(ByteBuffer buffer, int size, long pts)
{
Log.e(TAG, "Form Native Player OnReceiveData: size: " + size + ", pts: " + pts);
return 0;
}
// All event are sent to event handlers
#Override
public int Status(int arg)
{
MediaPlayer.PlayerNotifyCodes status = MediaPlayer.PlayerNotifyCodes.forValue(arg);
if (handler == null || status == null)
return 0;
Log.e(TAG, "Form Native Player status: " + arg);
switch (MediaPlayer.PlayerNotifyCodes.forValue(arg))
{
default:
Message msg = new Message();
msg.obj = status;
handler.removeMessages(mOldMsg);
mOldMsg = msg.what;
handler.sendMessage(msg);
}
return 0;
}
Intent getI;
String Title, Path = TEST_URL;
TextView ChannelTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myplayer);
getI = getIntent();
// Create Player instance
player = (MediaPlayer)findViewById(R.id.playerView);
ChannelTitle = (TextView) findViewById(R.id.ChTitle);
Title = getI.getStringExtra("title");
Path = getI.getStringExtra("path");
ChannelTitle.setText(Title);
player.getSurfaceView().setZOrderMediaOverlay(true); // necessary
SurfaceHolder sfhTrackHolder = player.getSurfaceView().getHolder();
sfhTrackHolder.setFormat(PixelFormat.TRANSPARENT);
player.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View view, MotionEvent motionEvent)
{
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
{
if (player.getState() == MediaPlayer.PlayerState.Paused)
player.Play();
else
if (player.getState() == MediaPlayer.PlayerState.Started)
player.Pause();
}
}
return true;
}
});
if (player != null)
{
player.getConfig().setConnectionUrl(Path);
if (player.getConfig().getConnectionUrl().isEmpty())
return;
//player_record.Close();
player.Close();
PlayerSettings sett = new PlayerSettings();
boolean bPort = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
int aspect = bPort ? 1 : sett.rendererEnableAspectRatio;
MediaPlayerConfig conf = new MediaPlayerConfig();
player.setVisibility(View.INVISIBLE);
conf.setConnectionUrl(player.getConfig().getConnectionUrl());
conf.setConnectionNetworkProtocol(sett.connectionProtocol);
conf.setConnectionDetectionTime(sett.connectionDetectionTime);
conf.setConnectionBufferingTime(sett.connectionBufferingTime);
conf.setDecodingType(sett.decoderType);
conf.setRendererType(sett.rendererType);
conf.setSynchroEnable(sett.synchroEnable);
conf.setSynchroNeedDropVideoFrames(sett.synchroNeedDropVideoFrames);
conf.setEnableColorVideo(sett.rendererEnableColorVideo);
conf.setEnableAspectRatio(aspect);
conf.setDataReceiveTimeout(30000);
conf.setNumberOfCPUCores(0);
// Open Player
player.Open(conf, this);
//record only
//conf.setMode(MediaPlayer.PlayerModes.PP_MODE_RECORD);
//conf.setRecordTrimPosStart(10000); //from 10th sec
//conf.setRecordTrimPosEnd(20000); //to 20th sec
/*player_record.Open(conf, new MediaPlayerCallback(){
#Override
public int Status(int arg) {
Log.i(TAG, "=player_record Status arg="+arg);
return 0;
}
#Override
public int OnReceiveData(ByteBuffer buffer, int size,
long pts) {
// TODO Auto-generated method stub
return 0;
}
});*/
playing = true;
}
}
private int[] mColorSwapBuf = null; // used by saveFrame()
public Bitmap getFrameAsBitmap(ByteBuffer frame, int width, int height)
{
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(frame);
return bmp;
}
protected void onPause()
{
Log.e("SDL", "onPause()");
super.onPause();
if (player != null)
player.onPause();
}
#Override
protected void onResume()
{
Log.e("SDL", "onResume()");
super.onResume();
if (player != null)
player.onResume();
}
#Override
protected void onStart()
{
Log.e("SDL", "onStart()");
super.onStart();
if (player != null)
player.onStart();
}
#Override
protected void onStop()
{
Log.e("SDL", "onStop()");
super.onStop();
if (player != null)
player.onStop();
}
#Override
public void onBackPressed() {
player.Close();
setUIDisconnected();
if (!playing)
{
super.onBackPressed();
return;
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
Log.e("SDL", "onWindowFocusChanged(): " + hasFocus);
super.onWindowFocusChanged(hasFocus);
if (player != null)
player.onWindowFocusChanged(hasFocus);
}
#Override
public void onLowMemory()
{
Log.e("SDL", "onLowMemory()");
super.onLowMemory();
if (player != null)
player.onLowMemory();
}
#Override
protected void onDestroy()
{
Log.e("SDL", "onDestroy()");
if (player != null)
player.onDestroy();
System.gc();
super.onDestroy();
}
protected void setUIDisconnected()
{
playing = false;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
Please I need help on that
Thank you
public void showDialog(Activity activity) {
final CharSequence[] items = {" No timer ", " 1 minute ", " 3 minute ", " 5 minute ", "10 minute"};
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(AutumnForest.this);
builder.setTitle("Set timer duration");
builder.setSingleChoiceItems(items, selection, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int item) {
switch (item) {
case 0:
if (isRunning) {
count_down_timer.cancel();
_tv.setVisibility(View.INVISIBLE);
gong_imageview.setVisibility(View.INVISIBLE);
timer_imageview.setImageResource(R.drawable.time_icon);
}
dialog.dismiss();
break;
case 1:
// if timer is running somewhere
if (!isRunning) {
isRunning = true;
countDownTimer(item);
levelDialog.dismiss();
} else {
count_down_timer.cancel();
countDownTimer(item);
levelDialog.dismiss();
}
break;
case 2:
if (!isRunning) {
isRunning = true;
countDownTimer(item);
levelDialog.dismiss();
} else {
count_down_timer.cancel();
countDownTimer(item);
levelDialog.dismiss();
}
break;
case 3:
if (!isRunning) {
isRunning = true;
countDownTimer(item);
} else {
count_down_timer.cancel();
countDownTimer(item);
levelDialog.dismiss();
}
break;
case 4:
if (!isRunning) {
isRunning = true;
countDownTimer(item);
} else {
count_down_timer.cancel();
countDownTimer(item);
levelDialog.dismiss();
}
break;
case 5:
if (!isRunning) {
isRunning = true;
countDownTimer(item);
} else {
count_down_timer.cancel();
countDownTimer(item);
levelDialog.dismiss();
}
break;
default:
Toast.makeText(AutumnForest.this, "Something went wrong please try again", Toast.LENGTH_SHORT).show();
}
}
});
levelDialog = builder.create();
levelDialog.show();
}
code working well but when click happen it stays to case 1 instead of clicked item.
i want that the if i clicked on case 3 or 4 something like that it should be setchecked = true and other else setchecked = false but it is not showing.
here is the output which i am getting.
Try using:
switch (item) {
case item[0]:
case item[1]:
...........
I followed Epson SDK and used sample code... To print Receipts
So over there from samples I got that I can print Text, Image and both Ways...
By using this... to print Text and Images..
public class MainActivity extends Activity implements View.OnClickListener, ReceiveListener {
private Context mContext = null;
private EditText mEditTarget = null;
private Spinner mSpnSeries = null;
private Spinner mSpnLang = null;
private Printer mPrinter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
int[] target = {
R.id.btnDiscovery,
R.id.btnSampleReceipt,
};
for (int i = 0; i < target.length; i++) {
Button button = (Button)findViewById(target[i]);
button.setOnClickListener(this);
}
mSpnSeries = (Spinner)findViewById(R.id.spnModel);
ArrayAdapter<SpnModelsItem> seriesAdapter = new ArrayAdapter<SpnModelsItem>(this, android.R.layout.simple_spinner_item);
seriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
seriesAdapter.add(new SpnModelsItem(getString(R.string.printerseries_t20), Printer.TM_T20));
mSpnSeries.setAdapter(seriesAdapter);
mSpnSeries.setSelection(0);
try {
Log.setLogSettings(mContext, Log.PERIOD_TEMPORARY, Log.OUTPUT_STORAGE, null, 0, 1, Log.LOGLEVEL_LOW);
}
catch (Exception e) {
ShowMsg.showException(e, "setLogSettings", mContext);
}
mEditTarget = (EditText)findViewById(R.id.edtTarget);
}
#Override
protected void onActivityResult(int requestCode, final int resultCode, final Intent data) {
if (data != null && resultCode == RESULT_OK) {
String target = data.getStringExtra(getString(R.string.title_target));
if (target != null) {
EditText mEdtTarget = (EditText)findViewById(R.id.edtTarget);
mEdtTarget.setText(target);
}
}
}
#Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.btnDiscovery:
intent = new Intent(this, DiscoveryActivity.class);
startActivityForResult(intent, 0);
break;
case R.id.btnSampleReceipt:
updateButtonState(false);
if (!runPrintReceiptSequence()) {
updateButtonState(true);
}
break;
case R.id.btnSampleCoupon:
updateButtonState(false);
if (!runPrintCouponSequence()) {
updateButtonState(true);
}
break;
default:
// Do nothing
break;
}
}
private boolean runPrintReceiptSequence() {
if (!initializeObject()) {
return false;
}
if (!createReceiptData()) {
finalizeObject();
return false;
}
if (!printData()) {
finalizeObject();
return false;
}
return true;
}
private boolean createReceiptData() {
String method = "";
Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.store);
StringBuilder textData = new StringBuilder();
final int barcodeWidth = 2;
final int barcodeHeight = 100;
if (mPrinter == null) {
return false;
}
try {
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_CENTER);
method = "addImage";
mPrinter.addImage(logoData, 0, 0,
logoData.getWidth(),
logoData.getHeight(),
Printer.COLOR_1,
Printer.MODE_MONO,
Printer.HALFTONE_DITHER,
Printer.PARAM_DEFAULT,
Printer.COMPRESS_AUTO);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("EPSON PRINT DEMO TEST - \n");
textData.append("STORE DIRECTOR – XYZ\n");
textData.append("\n");
textData.append("28/06/16 05:15 012 0154 0225\n");
textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("524 5 GREEN TEA 19.99 R\n");
textData.append("003 2 LEMON TEA 59.99 R\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("SUBTOTAL 79.98\n");
textData.append("TAX 15.00\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addTextSize";
mPrinter.addTextSize(2, 2);
method = "addText";
mPrinter.addText("TOTAL 94.98.41\n");
method = "addTextSize";
mPrinter.addTextSize(1, 1);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("CASH 100.00\n");
textData.append("CHANGE 5.02\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("Purchased item total number\n");
textData.append("Sign Up and Save !\n");
textData.append("With Preferred Saving Card\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addFeedLine";
mPrinter.addFeedLine(2);
method = "addCut";
mPrinter.addCut(Printer.CUT_FEED);
}
catch (Exception e) {
ShowMsg.showException(e, method, mContext);
return false;
}
textData = null;
return true;
}
private boolean runPrintCouponSequence() {
if (!initializeObject()) {
return false;
}
if (!createCouponData()) {
finalizeObject();
return false;
}
if (!printData()) {
finalizeObject();
return false;
}
return true;
}
private boolean printData() {
if (mPrinter == null) {
return false;
}
if (!connectPrinter()) {
return false;
}
PrinterStatusInfo status = mPrinter.getStatus();
dispPrinterWarnings(status);
if (!isPrintable(status)) {
ShowMsg.showMsg(makeErrorMessage(status), mContext);
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
try {
mPrinter.sendData(Printer.PARAM_DEFAULT);
}
catch (Exception e) {
ShowMsg.showException(e, "sendData", mContext);
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
return true;
}
private boolean initializeObject() {
try {
mPrinter = new Printer(((SpnModelsItem) mSpnSeries.getSelectedItem()).getModelConstant(),
((SpnModelsItem) mSpnLang.getSelectedItem()).getModelConstant(),
mContext);
}
catch (Exception e) {
ShowMsg.showException(e, "Printer", mContext);
return false;
}
mPrinter.setReceiveEventListener(this);
return true;
}
private void finalizeObject() {
if (mPrinter == null) {
return;
}
mPrinter.clearCommandBuffer();
mPrinter.setReceiveEventListener(null);
mPrinter = null;
}
private boolean connectPrinter() {
boolean isBeginTransaction = false;
if (mPrinter == null) {
return false;
}
try {
mPrinter.connect(mEditTarget.getText().toString(), Printer.PARAM_DEFAULT);
}
catch (Exception e) {
ShowMsg.showException(e, "connect", mContext);
return false;
}
try {
mPrinter.beginTransaction();
isBeginTransaction = true;
}
catch (Exception e) {
ShowMsg.showException(e, "beginTransaction", mContext);
}
if (isBeginTransaction == false) {
try {
mPrinter.disconnect();
}
catch (Epos2Exception e) {
// Do nothing
return false;
}
}
return true;
}
private void disconnectPrinter() {
if (mPrinter == null) {
return;
}
try {
mPrinter.endTransaction();
}
catch (final Exception e) {
runOnUiThread(new Runnable() {
#Override
public synchronized void run() {
ShowMsg.showException(e, "endTransaction", mContext);
}
});
}
try {
mPrinter.disconnect();
}
catch (final Exception e) {
runOnUiThread(new Runnable() {
#Override
public synchronized void run() {
ShowMsg.showException(e, "disconnect", mContext);
}
});
}
finalizeObject();
}
private boolean isPrintable(PrinterStatusInfo status) {
if (status == null) {
return false;
}
if (status.getConnection() == Printer.FALSE) {
return false;
}
else if (status.getOnline() == Printer.FALSE) {
return false;
}
else {
;//print available
}
return true;
}
private String makeErrorMessage(PrinterStatusInfo status) {
String msg = "";
if (status.getBatteryLevel() == Printer.BATTERY_LEVEL_0) {
msg += getString(R.string.handlingmsg_err_battery_real_end);
}
return msg;
}
private void dispPrinterWarnings(PrinterStatusInfo status) {
EditText edtWarnings = (EditText)findViewById(R.id.edtWarnings);
String warningsMsg = "";
if (status == null) {
return;
}
if (status.getPaper() == Printer.PAPER_NEAR_END) {
warningsMsg += getString(R.string.handlingmsg_warn_receipt_near_end);
}
if (status.getBatteryLevel() == Printer.BATTERY_LEVEL_1) {
warningsMsg += getString(R.string.handlingmsg_warn_battery_near_end);
}
edtWarnings.setText(warningsMsg);
}
private void updateButtonState(boolean state) {
Button btnReceipt = (Button)findViewById(R.id.btnSampleReceipt);
Button btnCoupon = (Button)findViewById(R.id.btnSampleCoupon);
btnReceipt.setEnabled(state);
btnCoupon.setEnabled(state);
}
#Override
public void onPtrReceive(final Printer printerObj, final int code, final PrinterStatusInfo status, final String printJobId) {
runOnUiThread(new Runnable() {
#Override
public synchronized void run() {
ShowMsg.showResult(code, makeErrorMessage(status), mContext);
dispPrinterWarnings(status);
updateButtonState(true);
new Thread(new Runnable() {
#Override
public void run() {
disconnectPrinter();
}
}).start();
}
});
}
}
In the same way I want to print PDF. Is this Possible without any library?
Or else is it possible to print PDF in thermal Printer?
Can anyone suggest me how to print PDF in a thermal printer?
Here I have this to print a Image/bitmap
Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.store);
StringBuilder textData = new StringBuilder();
final int barcodeWidth = 2;
final int barcodeHeight = 100;
with addimage.. and for text I am giving plain text... with addtext....
Can Any one suggest Me How to add a PDF to this...
I followed May tutorials,... But Nothing Found related to PDF in thermal Printer(EPSON) Printer..
I am doing an application where i have to parse using XMLPullParser.
But i couldn't the value of temperature and humidity using getAttributeValue(null,"value") of XMLPullParser.
Code:
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
Log.i(" name:",name);
if(name.equals("country")){
country = text;
}
else if(name.equals("humidity")){
Log.i("humidity:",name);
humidity = myParser.getAttributeValue(null,"value");
}
else if(name.equals("pressure")){
pressure = myParser.getAttributeValue(null,"value");
}
else if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
else{
}
break;
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
}
The first answer solve the problem to humidity, pressure and temperature, but cause the country field be blank.
The code below solve this :
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
if ( !name.equals("country"))
text = myParser.getText();
if(name.equals("humidity")){
humidity = myParser.getAttributeValue(null,"value");
}
else if(name.equals("pressure")){
pressure = myParser.getAttributeValue(null,"value");
}
else if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
else{
}
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("country")){
country = text;
}
else {
}
break;
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
}