Vaadin addSucceededListener - java

I have an upload button in Vaadin 8 with an addSucceededListener listener on it- about which i don't know many things..and i couldn't find too much info for this type of listener.
When i click that button i want to fire up a confirmation window - which I instantiate with ConfirmButton cd = new ConfirmButton("Confirmare"); and i open the modal pop-up with cd.openInModalPopup();.
My issue here is that the pop-up -> cd.openInModalPopup(); shows up only after the "Choose a file" window is open and i must select a file.
My question is how can I show the confirmation first, and only if the uer confirms, open the "Choose a file" window.
Adding the code below:
<vaadin-upload button-caption="Incarc INDICATORI " _id="cmdIncarcRaportInd" :right></vaadin-upload>
public Upload getCmdIncarcRaportInd() {
return cmdIncarcRaportInd;
}
getCmdIncarcRaportInd().addSucceededListener(event -> {
int NR_Raport=0;
String WBL ="";
WBL = getCheBL().getValue()?"B":"I";
if(raport!=null) NR_Raport=Numeric.getValInt(raport.get("Nr. Raport"));
if (NR_Raport==0) {
Notification notif = new Notification("Atentie",
"NR Raport incorect",
Notification.Type.ERROR_MESSAGE);
notif.setDelayMsec(-1);
notif.show(Page.getCurrent());
return;
}
int NR_RaportW = NR_Raport;
if(WBL.equals("B")) {
NR_RaportW=99;
ConfirmButton cd = new ConfirmButton("Confirmare");
cd.misWinTitle = "Atentie MIS";
cd.misWinText = "Incarcati valori Base Line ? Daca exista deja, cele vechi se vor rescrie cu valorile noi. CONFIRMATI BASE LINE (DA / NU) ?";
cd.misButOK = "DA";
cd.misButCancel = "NU";
cd.setOkAction(()->{
String raspuns="ok";
if(!receiver.getFile().getName().split("_")[0].equals(proiect.get("Prj cod"))) {
Notification notif = new Notification("Atentie", "Cod Proiect Incorect",
Notification.Type.ERROR_MESSAGE);
notif.setDelayMsec(-1);
notif.show(Page.getCurrent());
return;
}
try {
raspuns = Utility.getSomeData(receiver.getFile(), proiect, 99, themeDisplay);
} catch (IOException | SQLException e) {
raspuns=e.getMessage();
}
Notification notificare = new Notification("Atentie - Incarcare Base Line Indicatori",
raspuns,
Notification.Type.ERROR_MESSAGE);
notificare.setDelayMsec(-1);
notificare.show(Page.getCurrent());
incarcGrdIndicatori(prj_cod);
receiver.uploadFinished(event);
});
cd.setCancelAction(()->{
});
cd.openInModalPopup();
} else {
String raspuns="ok";
if(!receiver.getFile().getName().split("_")[0].equals(proiect.get("Prj cod"))) {
Notification notif = new Notification("Atentie", "Cod Proiect Incorect",
Notification.Type.ERROR_MESSAGE);
notif.setDelayMsec(-1);
notif.show(Page.getCurrent());
return;
}
try {
raspuns = Utility.DoSomeStuff(receiver.getFile(), proiect, NR_RaportW, themeDisplay);
} catch (IOException | SQLException e) {
raspuns=e.getMessage();
}
Notification notificare = new Notification("Atentie - Incarcare Rap Indicatori",
raspuns,
Notification.Type.ERROR_MESSAGE);
notificare.setDelayMsec(-1);
notificare.show(Page.getCurrent());
incarcGrdIndicatori(prj_cod);
receiver.uploadFinished(event);
}
});
//);
}

Add a normal Button which the users clicks, and then show the Upload Button only when your conditions are meet?

Related

How to programmatically update an app from an unknown source in Android 10

Up to version android 10, I updated the application by downloading it through DownloadManager and installed through Intent by running it in StartActivity. But in Android 10, this no longer works. I found only one example using PackageManager but unfortunately nothing works. On the output OnNewIntent I always get the result - PackageInstallStatus.FailureInvalid. The example is redesigned for recording into a session from the stream http of the request, and in original from a file. But this does not problem, I tried it from the file. Does it even work? Maybe there are some features? I also get permissions to install packages.
void WebUpdateApk()
{
Action update = async () =>
{
if (PackageManager.CanRequestPackageInstalls() == true)
{
var packageInstaller = PackageManager.PackageInstaller;
var sessionParams = new PackageInstaller.SessionParams(PackageInstallMode.FullInstall);
int sessionId = packageInstaller.CreateSession(sessionParams);
var session = packageInstaller.OpenSession(sessionId);
try
{
var url = "http://mywebsite.com/getapk.php?apk=myapp.apk";
var httpResponse = await new HttpClient().GetAsync(url, HttpCompletionOption.ResponseContentRead);
try
{
if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK)
{
Stream input = await httpResponse.Content.ReadAsStreamAsync();
try
{
var packageInSession = session.OpenWrite("package", 0, -1);
try
{
if (input != null)
{
input.CopyTo(packageInSession);
}
else
{
throw new Exception("Inputstream is null");
}
}
finally
{
packageInSession.Close();
}
}
finally
{
input.Close();
}
}
}
catch { }
finally
{
httpResponse.Dispose();
}
}
catch { }
Intent intent = new Intent(Application.Context, Class);
intent.SetAction("SESSION_API_PACKAGE_INSTALLED");
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
IntentSender statusReceiver = pendingIntent.IntentSender;
session.Commit(statusReceiver);
}
else
{
Toast.MakeText(this, "No Package Installer Permission", ToastLength.Long).Show();
}
};
if (PackageManager.CanRequestPackageInstalls() == false)
{
RestartActivity = update;
StartActivity(new Intent(Android.Provider.Settings.ActionManageUnknownAppSources,
Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName)));
}
else update();
}
protected override void OnNewIntent(Intent intent)
{
Bundle extras = intent.Extras;
if ("SESSION_API_PACKAGE_INSTALLED".Equals(intent.Action))
{
var status = extras.GetInt(PackageInstaller.ExtraStatus);
var message = extras.GetString(PackageInstaller.ExtraStatusMessage);
switch (status)
{
case (int)PackageInstallStatus.PendingUserAction:
// Ask user to confirm the installation
var confirmIntent = (Intent)extras.Get(Intent.ExtraIntent);
StartActivity(confirmIntent);
break;
case (int)PackageInstallStatus.Success:
//TODO: Handle success
break;
case (int)PackageInstallStatus.Failure:
case (int)PackageInstallStatus.FailureAborted:
case (int)PackageInstallStatus.FailureBlocked:
case (int)PackageInstallStatus.FailureConflict:
case (int)PackageInstallStatus.FailureIncompatible:
case (int)PackageInstallStatus.FailureInvalid:
case (int)PackageInstallStatus.FailureStorage:
//TODO: Handle failures
break;
}
Toast.MakeText(this, "OnNewIntent status = " + status.ToString(), ToastLength.Long).Show();
}
}

Codes to print PDF not working at the last step

I am writing an app that can create Maths worksheet with answer pages in PDF format. I want to add a print function to allow printing the worksheet directly from the app.
In the PrintDocumentAdapter, the first half of the codes check the color of a certain pixel of the page to determine whether it is an answer page and reduce the number of pages to print accordingly. It then constructs a printingPDF document and sends it to print using 's writeTo() method in the onWrite().
Everything works fine until the last part. It reads the PDF correctly, checks the number of answer pages correctly, and sends a correct PDF with question pages only to the printing page. If I choose "Save as PDF" in the printing page, it saves the pages to a new PDF file with no problem. However, if I try to print with my printer that is connected to my phone with USB by clicking the print button, the printing page simply disappears and goes back to the main page of my app. (It is supposed to past those few pages to the printer app.) I tried several different android printer driver apps and the result was the same.
private void printWS() throws IOException {
findViewById(R.id.defaultTextView).setVisibility(View.INVISIBLE);
if (!loadedFile) {
File file = new File(getApplicationContext().getCacheDir(), getString(R.string.defaultFileName));
parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
} else {
parcelFileDescriptor = getContentResolver().openFileDescriptor(pdfUri, "r");
}
// Start printing
PrintManager printManager = (PrintManager) this.getSystemService(PRINT_SERVICE);
String jobName = getString(R.string.app_name);
PrintAttributes printAttributes = new PrintAttributes.Builder().setMediaSize(PrintAttributes.MediaSize.ISO_A4).build();
printManager.print(jobName, new PrintDocumentAdapter() {
int finalTotal;
#Override
public void onStart() {
if (parcelFileDescriptor != null) {
try {
pdfRenderer = new PdfRenderer(parcelFileDescriptor);
} catch (IOException e) {
e.printStackTrace();
}
}
int tempTotal = pdfRenderer.getPageCount();
Bitmap[] tempBitmap = new Bitmap[tempTotal];
finalTotal = tempTotal;
for (int pageNum = 0; pageNum < tempTotal; pageNum++) {
PdfRenderer.Page tempPage = pdfRenderer.openPage(pageNum);
tempBitmap[pageNum] = Bitmap.createBitmap(WS_WIDTH, WS_HEIGHT, Bitmap.Config.ARGB_8888);
tempPage.render(tempBitmap[pageNum], null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
if (tempBitmap[pageNum].getPixel(0, 0) == Color.GRAY) {
finalTotal--;
}
tempPage.close();
}
}
PrintedPdfDocument printingPDF;
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle bundle) {
printingPDF = new PrintedPdfDocument(getApplicationContext(), newAttributes);
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
if (finalTotal > 0) {
PrintDocumentInfo info = new PrintDocumentInfo
.Builder("Worksheet")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(finalTotal)
.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count calculation failed.");
}
}
#Override
public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
Bitmap[] loadedBitmap = new Bitmap[finalTotal];
for (int pageNum = 0; pageNum < finalTotal; pageNum++) {
PdfDocument.PageInfo printingPageInfo = new PdfDocument.PageInfo.Builder(WS_WIDTH, WS_HEIGHT, pageNum).create();
PdfDocument.Page printingPage = printingPDF.startPage(printingPageInfo);
if (cancellationSignal.isCanceled()) {
callback.onWriteCancelled();
printingPDF.close();
printingPDF = null;
return;
}
PdfRenderer.Page loadedPage = pdfRenderer.openPage(pageNum);
loadedBitmap[pageNum] = Bitmap.createBitmap(WS_WIDTH, WS_HEIGHT, Bitmap.Config.ARGB_8888);
loadedPage.render(loadedBitmap[pageNum], null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
Canvas canvas = printingPage.getCanvas();
Paint paint = new Paint();
canvas.drawBitmap(loadedBitmap[pageNum], 0, 0, paint);
printingPDF.finishPage(printingPage);
loadedPage.close();
}
try {
printingPDF.writeTo(new FileOutputStream(destination.getFileDescriptor()));
} catch (IOException e) {
callback.onWriteFailed(e.toString());
return;
} finally {
printingPDF.close();
printingPDF = null;
}
PageRange[] writtenPages = new PageRange[]{PageRange.ALL_PAGES};
callback.onWriteFinished(writtenPages);
}
#Override
public void onFinish() {
try {
pdfRenderer.close();
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}, printAttributes);
}
Can someone take a look at my codes and tell me what is going wrong? Please help! Thanks!
Nevermind. It turned out the codes are ok. What I needed to do was go to the settings of my phone and change the "Display pop-up windows while running in the background" of the printer driver app to "allow", then it worked perfectly!
I will keep the question and answer here in case someone encounters the same problem.

Im doing project on QuickBlox Chat Application, having some doubts

When i click send button it is not sending any messages
The program gives no error, please help me solve this.
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(edtContent.getText().toString());
chatMessage.setSenderId(QBChatService.getInstance().getUser().getId());
chatMessage.setSaveToHistory(true);
try {
qbChatDialog.sendMessage(chatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
QBChatMessagesHolder.getInstance().putMessage(qbChatDialog.getDialogId(), chatMessage);
ArrayList<QBChatMessage> messages = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatDialog.getDialogId());
adapter = new ChatMessageAdapter(getBaseContext(), messages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
I used the quick blox sdk in my app. below is the code for sending message and its working fine.
private void sendChatMessage(String text) {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(text);
chatMessage.setProperty(PROPERTY_SAVE_TO_HISTORY, "1");
chatMessage.setDateSent(System.currentTimeMillis() / 1000);
try {
if (Network.isNetworkConnected(ChatActivity.this)) {
chatDialog.sendMessage(chatMessage);
showMessage(chatMessage);
messageEditText.setText("");
checkIfOpponentIsOnline(chatMessage.getBody());
} else {
ToastUtil.showShortToast(ChatActivity.this, "Please check Internet connection and Try again");
}
} catch (SmackException e) {
Log.e(TAG, "Failed to send a message", e);
ToastUtil.showShortToast(ChatActivity.this, R.string.chat_send_message_error);
} catch (Exception e) {
Log.e(TAG, "Failed to send a message", e);
}
}
If you are still having trouble then you must check the dialogId and dialogUsers on your Quickblox console . There must be something wrong.Check for existence of users in dialog. Also check for ChatService Session cause if there is no session you won't be able to send any messages.

Monitoring a folder for new files Eclipse

I'm making an app that can take photos. If the taken photo is added into my "Camera" folder I want a toaster message to appear.
However with my current code when I click the camera button, the toaster just comes up without waiting for the photo to be taken.
Below is the source code to take the photo:
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v){
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage=Uri.fromFile(
new File("/storage/emulated/0/DCIM/Camera","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
The toaster I want to show:
Toast toast= Toast.makeText(getApplicationContext(),
"Picture was taking", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
Can you tell me why my code is failing to do the intended job?
Only the part of monitoring a a folder:
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
// This key is registered only
// for ENTRY_CREATE events,
// but an OVERFLOW event can
// occur regardless if events
// are lost or discarded.
if (kind == OVERFLOW) {
continue;
}
// The filename is the
// context of the event.
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
// Verify that the new
// file is a text file or a directory using the path filename from above.
}
// Reset the key -- this step is critical if you want to
// receive further watch events. If the key is no longer valid,
// the directory is inaccessible so exit the loop.
boolean valid = key.reset();
if (!valid) {
break;
}
}

How to keep alive a JSONArray for widgets?

My app has a widget with two buttons that goes back and forth and displays information stored in a JSONArray. It works very well but the problem is when i close the app the widget stops working because the JSONArray becomes null. How can i keep it working even when the app is closed ?
its too long to post it here but this is the part when i click next button
if(intent.getAction().equals(NEXT_LISTING)){
try{
if (listingNumber !=15)
{
listingNumber++;
}
JSONObject latestListing = jsonListings.getJSONObject(listingNumber);
String titleString = latestListing.getString("title");
String descriptionString = latestListing.getString("description");
String categoryString = latestListing.getString("category");
Date postDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(latestListing.getString("created"));
Date newDate = new Date(postDate.getTime() + Utils.getCurrentTimezoneOffset() * (3600 * 100));
String createdDate = Utils.getFormattedDate(newDate);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.njoftime_widget);
views.setTextViewText(R.id.title, titleString);
views.setTextViewText(R.id.description, descriptionString);
views.setTextViewText(R.id.textView_category, categoryString);
views.setTextViewText(R.id.textView_date, createdDate);
for(int i=0; i < categoriesList.size();i++)
{
if(categoriesList.get(i).get(0).equals(latestListing.getString("category")))
{
views.setImageViewResource(R.id.category_icon_widget, iconList.get(i));
}
}
if(listingThumbnails.get(listingNumber) != null)
{
views.setViewVisibility(R.id.listing_photo, View.VISIBLE);
views.setImageViewUri(R.id.listing_photo, Uri.parse(""));
Bitmap roundedBitmap = getRoundedLeftCornerBitmap(listingThumbnails.get(listingNumber), 10);
views.setImageViewBitmap(R.id.listing_photo,roundedBitmap);
}
else
{
views.setViewVisibility(R.id.listing_photo, View.GONE);
}
// Instruct the widget manager to update the widget
ComponentName componentName = new ComponentName(context, NjoftimeWidget.class);
AppWidgetManager.getInstance(context).updateAppWidget(componentName, views);
}
catch (Exception e)
{
e.printStackTrace();
}
}

Categories