My program is running fine in most of the andriod phone. But recently it found errors in some particular andriod phones. I found the error should be caused by the AsyncTask. The onPostExecute is not called. Please help. Thanks a lot!!
public void onCreate(Bundle savedInstanceState) {
this.setDebugTag(DEBUGTAG);
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
try {
final View v_splashLayout = findViewById(R.id.splashLayout);
if(v_splashLayout== null){
FunctionUtil.logD(DEBUGTAG, " v_splashLayout :");
}
v_splashLayout.post(new Runnable() {
#Override
public void run() {
Rect rect = new Rect();
Window win = getWindow(); // Get the Window
win.getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
}
});
} catch(Exception e) {
FunctionUtil.logE(DEBUGTAG,"v_splashLayout error", e);
}
// init circleProgressBar
pb1 = (ProgressBar) findViewById(R.id.circleProgressBar);
dbh = (DatabaseHelper) OpenHelperManager.getHelper(this, DatabaseHelper.class);
if (FunctionUtil.ISDEBUGGING) {
checkSystemConfig();
//checkdb
}
init_neutralButtonOnClickListener();
init_quitButtonOnClickListener();
uiHandler = new MainHandler();
callAsyncGetLatestUpdateWS();
} // END, onCreate
private void callAsyncGetLatestUpdateWS() {
// check internet connection
// if isOnline, check the local db version with the server version
// if there is update, download and update the local db
boolean isOnline = FunctionUtil.checkInternetConnection(this);
boolean isBackgroundEnabled = FunctionUtil.checkBackgroundData(this);
FunctionUtil.logD(DEBUGTAG, "callAsyncGetLatestUpdateWS - isOnline="+isOnline+" , isBackgroundEnabled="+isBackgroundEnabled);
if (isOnline && isBackgroundEnabled) {
try {
// call webservice and update status
// call async task to do
if (checkVersionTask==null) {
checkVersionTask = new CheckVersionFromWS_Task();
}
if (checkVersionTask.getStatus().equals(AsyncTask.Status.PENDING)) {
// AsyncTask.Status.PENDING
checkVersionTask.execute();
} else if (checkVersionTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
// AsyncTask.Status.FINISHED
checkVersionTask.cancel(true);
checkVersionTask = null;
checkVersionTask = new CheckVersionFromWS_Task();
checkVersionTask.execute();
} else {
// AsyncTask.Status.RUNNING
//checkVersionTask.cancel(true);
}
} catch(Exception e) {
FunctionUtil.logE(DEBUGTAG, "callAsyncGetLatestUpdateWS error:", e);
}
// 2. go to MainActivity, temp enable
//goNext();
} // END, if isOnline
else {
if (!isOnline) {
// no connection
//showDialog(Constant.DIALOG_NOCONNECTION);
AlertDialogFactory.show(SplashActivity.this, Constant.DIALOG_NOCONNECTION, neutralButtonOnClickListener, true);
} else if (!isBackgroundEnabled) {
//no background
//showDialog(Constant.DIALOG_NOBACKGROUNDDATA);
AlertDialogFactory.show(SplashActivity.this, Constant.DIALOG_NOBACKGROUNDDATA, neutralButtonOnClickListener, true);
}
}
} // END, callAsyncGetLatestUpdateWS
private class CheckVersionFromWS_Task extends AsyncTask<Void, Void, LatestUpdateResult> {
// task start
#Override
protected void onPreExecute() {
FunctionUtil.logD(DEBUGTAG,getClass().getSimpleName() + " onPreExecute");
if (pb1!=null) {
pb1.setIndeterminate(true);
pb1.setVisibility(View.VISIBLE);
} else {
pb1 = (ProgressBar) findViewById(R.id.circleProgressBar);
pb1.setIndeterminate(true);
pb1.setVisibility(View.VISIBLE);
}
isBigPromotionLoadingTimeout = false;
} // END, onPreExecute
#Override
protected LatestUpdateResult doInBackground(Void... arg0) {
FunctionUtil.logD(DEBUGTAG, getClass().getSimpleName()+" doInBackground");
LatestUpdateResult response = null;
if (!isCancelled()) {
response = Util.getLatestUpdateWS(SplashActivity.this);
if (response!=null && StatusCode.WS_SUCCESSFUL==response.getErrorCode()) {
try {
//load the DB data of Promotion
long st = System.currentTimeMillis();
boolean b = Util.callGetPromotionLinkWS(SplashActivity.this, dbh);
long et = System.currentTimeMillis();
FunctionUtil.logD(DEBUGTAG, getClass().getSimpleName()+" doInBackground : Util.callGetPromotionLinkWS : "+b+" , load time="+(et-st)+"ms");
if (b) {
preLoadBigBanner();
int sleepTime = 500;
int totalSleepTime = 0;
while(!isFinishLoadingBigPromotion && totalSleepTime < Constant.BIGPROMOTIONWAITTIME){
FunctionUtil.logD(DEBUGTAG, "SplashActivity wait isFinishLoadingBigPromotion: "+isFinishLoadingBigPromotion);
try {
FunctionUtil.logD(DEBUGTAG, "SplashActivity wait for bigpromotion loading time : "+totalSleepTime);
totalSleepTime = totalSleepTime+sleepTime;
SystemClock.sleep(sleepTime);
} catch(Exception ex){
totalSleepTime = Constant.BIGPROMOTIONWAITTIME;
FunctionUtil.logE(DEBUGTAG, "doInBackground loadingBigPromotion error:", ex);
break;
}
} // END, while
isBigPromotionLoadingTimeout = true;
} // END, if
} catch(Exception e) {
FunctionUtil.logE(DEBUGTAG, getClass().getSimpleName()+" doInBackground error:", e);
}
} // END, if
} // END, isCancelled
return response;
} // END, doInBackground
#Override
protected void onPostExecute(LatestUpdateResult result) {
FunctionUtil.logD(DEBUGTAG, getClass().getSimpleName() + " onPostExecute > result="+result);
if(pb1 != null) {
pb1.setVisibility(View.GONE);
}
if (result!=null) {
int statusCode = result.getErrorCode();
if (statusCode==StatusCode.WS_SUCCESSFUL) {
Intent i1 = null;
/***
**/
goNext();
}
}
Related
I followed Epson SDK for android to thermal print receipts...
So instead of the text I am given some Image which contains entire image..
at the part of Logoimage(the store).. Which is like below
Here the Store is the Logoimage Insted of that I have given My Recipt(Image) So I am getting like above.. Its not printing full size...
this is my code
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 - (HYD)\n");
textData.append("STORE DIRECTOR – MLN\n");
textData.append("\n");
textData.append("07/06/12 09:15 012 0191 134\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 3 CUP BLK TEAPOT 9.99 R\n");
textData.append("003 WESTGATE BLACK 25 59.99 R\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("SUBTOTAL 69.98\n");
textData.append("TAX 14.43\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addTextSize";
mPrinter.addTextSize(2, 2);
method = "addText";
mPrinter.addText("TOTAL 84.41\n");
method = "addTextSize";
mPrinter.addTextSize(1, 1);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("CASH 200.00\n");
textData.append("CHANGE 78.14\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();
}
});
}
}
can any one suggest me where do I adjust the size of the image so that I should print the page area instead of logo size...
this is Image content data
for Image
String method = "";
Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.store);
//I have given this Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.full);
and this is for image content..
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);
Please suggest how to print the image content at full size...
I am getting a side of page..
It should Print 80 mm of Size but its printing 40 mm can any one suggest me how to make it to full size or how to adjust the size of the Image to stretch it to max paper area...
Your question is a bit unclear.
I think your question is:
You are given the data for the image at some resolution as an Android BitMapFactory.
You want to print on some printer, with another DPI. The Android BitMapFactory for the image is already set.
You need to scale the BitMapFactory for your logo.
First, in your line of getting the logo data, you can try just exploring the option BitmapFactory.Options.inSampleSize to get about that right size. That would get you a better, but not perfect answer.
For perfect, you should scale the logo. You can use code here. See also the related questions here and here.
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..
Only a small portion of my users are getting this error and I can't for the life of me figure it out. I use GooglePlayServicesUtil.isGooglePlayServicesAvailable(downloadService) to test whether or not Play Services is available, and it always returns SUCCESS. I setup the channel to connect to the Chromecast, and everything works fine up until the point where I try to use RemoteMediaPlayer.load. The result is always SIGN_IN_REQUIRED for some users, with resolution: null. The status.toString() is Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}. I'm really not sure what I am supposed to with this or how to get rid of the error for my few users who are getting this.
I don't know what portion is related, so I am just posting my entire controller class:
public class ChromeCastController extends RemoteController {
private static final String TAG = ChromeCastController.class.getSimpleName();
private CastDevice castDevice;
private GoogleApiClient apiClient;
private ConnectionCallbacks connectionCallbacks;
private ConnectionFailedListener connectionFailedListener;
private Cast.Listener castClientListener;
private boolean applicationStarted = false;
private boolean waitingForReconnect = false;
private boolean error = false;
private boolean ignoreNextPaused = false;
private String sessionId;
private FileProxy proxy;
private String rootLocation;
private RemoteMediaPlayer mediaPlayer;
private double gain = 0.5;
public ChromeCastController(DownloadService downloadService, CastDevice castDevice) {
this.downloadService = downloadService;
this.castDevice = castDevice;
SharedPreferences prefs = Util.getPreferences(downloadService);
rootLocation = prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null);
}
#Override
public void create(boolean playing, int seconds) {
downloadService.setPlayerState(PlayerState.PREPARING);
connectionCallbacks = new ConnectionCallbacks(playing, seconds);
connectionFailedListener = new ConnectionFailedListener();
castClientListener = new Cast.Listener() {
#Override
public void onApplicationStatusChanged() {
if (apiClient != null && apiClient.isConnected()) {
Log.i(TAG, "onApplicationStatusChanged: " + Cast.CastApi.getApplicationStatus(apiClient));
}
}
#Override
public void onVolumeChanged() {
if (apiClient != null && applicationStarted) {
try {
gain = Cast.CastApi.getVolume(apiClient);
} catch(Exception e) {
Log.w(TAG, "Failed to get volume");
}
}
}
#Override
public void onApplicationDisconnected(int errorCode) {
shutdownInternal();
}
};
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions.builder(castDevice, castClientListener);
apiClient = new GoogleApiClient.Builder(downloadService)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(connectionCallbacks)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
apiClient.connect();
}
#Override
public void start() {
if(error) {
error = false;
Log.w(TAG, "Attempting to restart song");
startSong(downloadService.getCurrentPlaying(), true, 0);
return;
}
try {
mediaPlayer.play(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to start");
}
}
#Override
public void stop() {
try {
mediaPlayer.pause(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to pause");
}
}
#Override
public void shutdown() {
try {
if(mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
Log.e(TAG, "Failed to stop mediaPlayer", e);
}
try {
if(apiClient != null) {
Cast.CastApi.stopApplication(apiClient);
Cast.CastApi.removeMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace());
mediaPlayer = null;
applicationStarted = false;
}
} catch(Exception e) {
Log.e(TAG, "Failed to shutdown application", e);
}
if(apiClient != null && apiClient.isConnected()) {
apiClient.disconnect();
}
apiClient = null;
if(proxy != null) {
proxy.stop();
proxy = null;
}
}
private void shutdownInternal() {
// This will call this.shutdown() indirectly
downloadService.setRemoteEnabled(RemoteControlState.LOCAL, null);
}
#Override
public void updatePlaylist() {
if(downloadService.getCurrentPlaying() == null) {
startSong(null, false, 0);
}
}
#Override
public void changePosition(int seconds) {
try {
mediaPlayer.seek(apiClient, seconds * 1000L);
} catch(Exception e) {
Log.e(TAG, "FAiled to seek to " + seconds);
}
}
#Override
public void changeTrack(int index, DownloadFile song) {
startSong(song, true, 0);
}
#Override
public void setVolume(boolean up) {
double delta = up ? 0.1 : -0.1;
gain += delta;
gain = Math.max(gain, 0.0);
gain = Math.min(gain, 1.0);
getVolumeToast().setVolume((float) gain);
try {
Cast.CastApi.setVolume(apiClient, gain);
} catch(Exception e) {
Log.e(TAG, "Failed to the volume");
}
}
#Override
public int getRemotePosition() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getApproximateStreamPosition() / 1000L);
} else {
return 0;
}
}
#Override
public int getRemoteDuration() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getStreamDuration() / 1000L);
} else {
return 0;
}
}
void startSong(DownloadFile currentPlaying, boolean autoStart, int position) {
if(currentPlaying == null) {
try {
if (mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
// Just means it didn't need to be stopped
}
downloadService.setPlayerState(PlayerState.IDLE);
return;
}
downloadService.setPlayerState(PlayerState.PREPARING);
MusicDirectory.Entry song = currentPlaying.getSong();
try {
MusicService musicService = MusicServiceFactory.getMusicService(downloadService);
String url;
// Offline, use file proxy
if(Util.isOffline(downloadService) || song.getId().indexOf(rootLocation) != -1) {
if(proxy == null) {
proxy = new FileProxy(downloadService);
proxy.start();
}
url = proxy.getPublicAddress(song.getId());
} else {
if(proxy != null) {
proxy.stop();
proxy = null;
}
if(song.isVideo()) {
url = musicService.getHlsUrl(song.getId(), currentPlaying.getBitRate(), downloadService);
} else {
url = musicService.getMusicUrl(downloadService, song, currentPlaying.getBitRate());
}
url = fixURLs(url);
}
// Setup song/video information
MediaMetadata meta = new MediaMetadata(song.isVideo() ? MediaMetadata.MEDIA_TYPE_MOVIE : MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
meta.putString(MediaMetadata.KEY_TITLE, song.getTitle());
if(song.getTrack() != null) {
meta.putInt(MediaMetadata.KEY_TRACK_NUMBER, song.getTrack());
}
if(!song.isVideo()) {
meta.putString(MediaMetadata.KEY_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_TITLE, song.getAlbum());
String coverArt = "";
if(proxy == null) {
coverArt = musicService.getCoverArtUrl(downloadService, song);
coverArt = fixURLs(coverArt);
meta.addImage(new WebImage(Uri.parse(coverArt)));
} else {
File coverArtFile = FileUtil.getAlbumArtFile(downloadService, song);
if(coverArtFile != null && coverArtFile.exists()) {
coverArt = proxy.getPublicAddress(coverArtFile.getPath());
meta.addImage(new WebImage(Uri.parse(coverArt)));
}
}
}
String contentType;
if(song.isVideo()) {
contentType = "application/x-mpegURL";
}
else if(song.getTranscodedContentType() != null) {
contentType = song.getTranscodedContentType();
} else if(song.getContentType() != null) {
contentType = song.getContentType();
} else {
contentType = "audio/mpeg";
}
// Load it into a MediaInfo wrapper
MediaInfo mediaInfo = new MediaInfo.Builder(url)
.setContentType(contentType)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setMetadata(meta)
.build();
if(autoStart) {
ignoreNextPaused = true;
}
mediaPlayer.load(apiClient, mediaInfo, autoStart, position * 1000L).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
#Override
public void onResult(RemoteMediaPlayer.MediaChannelResult result) {
if (result.getStatus().isSuccess()) {
// Handled in other handler
} else if(result.getStatus().getStatusCode() != ConnectionResult.SIGN_IN_REQUIRED) {
Log.e(TAG, "Failed to load: " + result.getStatus().toString());
failedLoad();
}
}
});
} catch (IllegalStateException e) {
Log.e(TAG, "Problem occurred with media during loading", e);
failedLoad();
} catch (Exception e) {
Log.e(TAG, "Problem opening media during loading", e);
failedLoad();
}
}
private String fixURLs(String url) {
// Only change to internal when using https
if(url.indexOf("https") != -1) {
SharedPreferences prefs = Util.getPreferences(downloadService);
int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
String externalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_URL + instance, null);
String internalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance, null);
url = url.replace(internalUrl, externalUrl);
}
// Use separate profile for Chromecast so users can do ogg on phone, mp3 for CC
return url.replace(Constants.REST_CLIENT_ID, Constants.CHROMECAST_CLIENT_ID);
}
private void failedLoad() {
Util.toast(downloadService, downloadService.getResources().getString(R.string.download_failed_to_load));
downloadService.setPlayerState(PlayerState.STOPPED);
error = true;
}
private class ConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks {
private boolean isPlaying;
private int position;
private ResultCallback<Cast.ApplicationConnectionResult> resultCallback;
ConnectionCallbacks(boolean isPlaying, int position) {
this.isPlaying = isPlaying;
this.position = position;
resultCallback = new ResultCallback<Cast.ApplicationConnectionResult>() {
#Override
public void onResult(Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
ApplicationMetadata applicationMetadata = result.getApplicationMetadata();
sessionId = result.getSessionId();
String applicationStatus = result.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
applicationStarted = true;
setupChannel();
} else {
shutdownInternal();
}
}
};
}
#Override
public void onConnected(Bundle connectionHint) {
if (waitingForReconnect) {
Log.i(TAG, "Reconnecting");
reconnectApplication();
} else {
launchApplication();
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.w(TAG, "Connection suspended");
isPlaying = downloadService.getPlayerState() == PlayerState.STARTED;
position = getRemotePosition();
waitingForReconnect = true;
}
void launchApplication() {
try {
Cast.CastApi.launchApplication(apiClient, CastCompat.APPLICATION_ID, false).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to launch application", e);
}
}
void reconnectApplication() {
try {
Cast.CastApi.joinApplication(apiClient, CastCompat.APPLICATION_ID, sessionId).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to reconnect application", e);
}
}
void setupChannel() {
if(!waitingForReconnect) {
mediaPlayer = new RemoteMediaPlayer();
mediaPlayer.setOnStatusUpdatedListener(new RemoteMediaPlayer.OnStatusUpdatedListener() {
#Override
public void onStatusUpdated() {
MediaStatus mediaStatus = mediaPlayer.getMediaStatus();
if (mediaStatus == null) {
return;
}
switch (mediaStatus.getPlayerState()) {
case MediaStatus.PLAYER_STATE_PLAYING:
if (ignoreNextPaused) {
ignoreNextPaused = false;
}
downloadService.setPlayerState(PlayerState.STARTED);
break;
case MediaStatus.PLAYER_STATE_PAUSED:
if (!ignoreNextPaused) {
downloadService.setPlayerState(PlayerState.PAUSED);
}
break;
case MediaStatus.PLAYER_STATE_BUFFERING:
downloadService.setPlayerState(PlayerState.PREPARING);
break;
case MediaStatus.PLAYER_STATE_IDLE:
if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_FINISHED) {
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.onSongCompleted();
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_INTERRUPTED) {
if (downloadService.getPlayerState() != PlayerState.PREPARING) {
downloadService.setPlayerState(PlayerState.PREPARING);
}
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_ERROR) {
Log.e(TAG, "Idle due to unknown error");
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.next();
} else {
Log.w(TAG, "Idle reason: " + mediaStatus.getIdleReason());
downloadService.setPlayerState(PlayerState.IDLE);
}
break;
}
}
});
}
try {
Cast.CastApi.setMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace(), mediaPlayer);
} catch (IOException e) {
Log.e(TAG, "Exception while creating channel", e);
}
if(!waitingForReconnect) {
DownloadFile currentPlaying = downloadService.getCurrentPlaying();
startSong(currentPlaying, isPlaying, position);
}
if(waitingForReconnect) {
waitingForReconnect = false;
}
}
}
private class ConnectionFailedListener implements GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(ConnectionResult result) {
shutdownInternal();
}
}
}
Edit for logs:
03-28 19:04:49.757 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Chromecast Home Screen
03-28 19:04:52.280 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: null
03-28 19:04:54.162 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Ready To Cast
03-28 19:05:05.194 6305-6305/github.daneren2005.dsub E/ChromeCastController﹕ Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}
It is strange that you are getting such status code at that time. What comes to mind is that the user may have not logged into his/her gmail account or something along those lines. Do you have the log file for us to take a look at to see if we can get more from the context? Also, to be sure, such user sees the application launched on the TV and only when it comes to loading a media that error is thrown?
The issue is due to using a Self Signed Certificate. I didn't realize the issue on my old phone because I had changed hosts and bought a normal certificate after switching phones. It would be nice if the SDK would through a useful error though. The one thrown makes you think that it is a problem with connecting to the Play Services SDK, and not a problem with the actual URL being used.
My code have more than one thread and Runnable. My problem is i change the value of a certain variable in the thread that the Runnable calling .
After the calling i make a check on that variable value but the value was not retrieved yet.
How can i retrieve the value after the processing? Here is the Runnable and the Thread code:
final Runnable r = new Runnable()
{
public void run()
{
if(flag==true)
onSwipe();
if(SwipeAgain==true)
handler.postDelayed(this, 1000);
}
};
private void onSwipe() {
new Thread() {
public void run() {
String data = null;
decryption_data = null;
encryption_data = null;
SwipeAgain=false;
handler.post(clear_encryption);
try {
data = sreader.ReadCard(15000);
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
return;
} else
CloseSinWave();
}
if (data == null) {
SwipeAgain=true;
encryption_data = sreader.GetErrorString();
if (encryption_data.equalsIgnoreCase("cancel all"))
return;
handler.post(display_encryptiondata);
} else {
encryption_data = "\n" + data;
handler.post(display_encryptiondata);
}.start();
}
SwipeAgain is the value i want after processing
You have to use Callable, Runnable interface do not pass values to the parent method.
See this example.
You may require to use Generic Objects
Use a MONITOR final Object to wait and notify it when processing is done.
private final MONITOR Object[] = new Object[0];
private AtomicBoolean ready = new AtomicBoolean(false);
final Runnable r = new Runnable() {
public void run()
{
if(flag==true){
ready.set(false);
onSwipe();
synchronized(MONITOR){
if(!ready.get()){
try{
MONITOR.wait(); //will block until it get notified
}catch(InteruptedException e){}
}
}
}
if(SwipeAgain==true)
handler.postDelayed(this, 1000);
}
};
private void onSwipe() {
new Thread() {
public void run() {
try{
String data = null;
decryption_data = null;
encryption_data = null;
SwipeAgain=false;
handler.post(clear_encryption);
try {
data = sreader.ReadCard(15000);
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
return;
} else
CloseSinWave();
}
if (data == null) {
SwipeAgain=true;
encryption_data = sreader.GetErrorString();
if (encryption_data.equalsIgnoreCase("cancel all"))
return;
handler.post(display_encryptiondata);
} else {
encryption_data = "\n" + data;
handler.post(display_encryptiondata);
}finally{
synchronized(MONITOR){
ready.set(true);
MONITOR.notifyAll(); //notify (and so unblock r.run())
}
}
}.start();
}
I have trouble using thread.join in my code below. It should wait for the thread to finish before executing the codes after it, right? It was behaving differently on different occasions.
I have three cases to check if my code goes well
App is used for the first time - works as expected but the loading page don't appear while downloading
App is used the second time (db is up to date) - works okay
App is used the third time (db is outdated, must update) - won't update, screen blacks out, then crashes
I think I have problems with this code on onCreate method:
dropOldSchedule();
dropThread.join();
triggerDownload();
Based on the logs, the code works until before this part... What can be the problem?
MainActivity.java
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
TextView homeText1, homeText2, homeText3, homeText4;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
Thread dropThread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.dropOldSchedule();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
db.close();
pd.dismiss();
}
});
}
});
Thread getUploadDateThread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
Thread downloadThread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL url = new URL(csvFile);
Log.i("dl", "start");
InputStream input = url.openStream();
CSVReader reader = new CSVReader(new InputStreamReader(input));
Log.i("dl", "after reading");
String [] sched;
while ((sched = reader.readNext()) != null) {
if(sched[INDEX_CITY].equals("")) sched[INDEX_CITY]="OTHERS";
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
//e.printStackTrace();
}
}
input.close();
Log.i("dl", "finished");
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
writeUploadDateInTextFile();
}
});
#SuppressWarnings("unqualified-field-access")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pms_main);
Button home = (Button) findViewById(R.id.home);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MeralcoSuite_TabletActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
homeText1 = (TextView) findViewById(R.id.home_text1);
homeText2 = (TextView) findViewById(R.id.home_text2);
homeText3 = (TextView) findViewById(R.id.home_text3);
homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
getUploadDate();
try {
getUploadDateThread.join(); //wait for upload date
Log.d("getUploadDate","thread died, upload date=" + str);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
db.close();
if(!uploadDateEqualsDateInFile()){
dropOldSchedule();
dropThread.join();
triggerDownload();
}
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
triggerDownload();
showDisclaimer();
Log.i("oncreate", "finished!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void dropOldSchedule(){
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
dropThread.start();
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
downloadThread.start();
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
getUploadDateThread.start();
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
homeText3
.setText("..." + str
+ "...");
homeText1.setVisibility(View.VISIBLE);
homeText2.setVisibility(View.VISIBLE);
homeText3.setVisibility(View.VISIBLE);
homeText4.setVisibility(View.VISIBLE);
Log.d("showDisclaimer", "finished showing disclaimer");
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
Sorry but I couldn't find mistakes or problems in your code. But I would strongly recommend you to use AsyncTask for doing something in different thread. AsyncTask is very easy to use and I would say that it is one of the biggest advantages of java. I really miss it in obj-c.
http://labs.makemachine.net/2010/05/android-asynctask-example/
http://marakana.com/s/video_tutorial_android_application_development_asynctask_preferences_and_options_menu,257/index.html
check those links hope that will help you.
It was already mentioned that AsyncTask is the better alternative. However, it may be the case, that your call to join will throw InterruptedException. Try to use it like this:
while(getUploadDateThread.isRunning()){
try{
getUploadDateThread.join();
} catch (InterruptedException ie){}
}
// code after join
I think the problem that your facing is that you are blocking the UI thread when you call join in the onCreate() method. You should move this code into another thread which should execute in the background and once its done you can update the UI.
Here is a sample code:
final Thread t1 = new Thread();
final Thread t2 = new Thread();
t1.start();
t2.start();
new Thread(new Runnable() {
#Override
public void run() {
// Perform all your thread joins here.
try {
t1.join();
t2.join();
} catch (Exception e) {
// TODO: handle exception
}
// This thread wont move forward unless all your threads
// mentioned above are executed or timed out.
// ------ Update UI using this method
runOnUiThread(new Runnable() {
#Override
public void run() {
// Update UI code goes here
}
});
}
}).start();