Problems in saving data with Android on CloudBoost - java

I'm using CloudBoost for Android application and i had some problems when I try to save save a data in a table, I'm not getting any results. This is my code:
CloudApp.init("*****", "*****");
...
new Thread(new Runnable() {
#Override
public void run() {
CloudObject obj = new CloudObject("User", "1uvSDThQ");
Log.e("LOG", "1"); //Already this is not shown
try {
obj.set("color", "#000000");
obj.setAcl(new ACL());
obj.save(new CloudObjectCallback() {
#Override
public void done(final CloudObject x, final CloudException e) {
if(e != null)
//error
Log.e("LOG", "Errore");
if(x!=null)
//cloudObject
Log.e("LOG", "FATTO");
}
});
} catch (CloudException e) {
e.printStackTrace();
}
}
});

Your log isn't shown because you made a Thread without calling start().
Android typically uses Asynctask anyway, but I'm not sure why you really need a Thread with this library... That save method looks asynchronous
CloudApp.init("*****", "*****")
CloudObject obj = new CloudObject("User", "1uvSDThQ");
Log.e("LOG", "1");
try {
obj.set("color", "#000000");
obj.setAcl(new ACL());
obj.save(new CloudObjectCallback() {
#Override

Related

Null textview when it's call on a handler

I'm trying to do a setText() on a Textview (already instantiate in the onCreate()) called by a Handler and using the ruiOnUiTread() but I have a nullPointerException on the Textview.
Where can the problem come from?
I saw in the debug that the instance of the activity was not the same between the instantiation and the setText() while I do not change activity but impossible to instantiate it in the same place as the setText().
private TextView ambianceTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ambianceTextView = findViewById(R.id.valeur_ambiance);
StarterKillerPidroid.getInstance().startApp();
}
private final Runnable retrieveData = new Runnable() {
public void run() {
try {
setText();
} catch (Exception e) {
e.printStackTrace();
}
handlerRecup.postDelayed(retrieveData, 1000);
}
};
public void setText(){
runOnUiThread(new Runnable() {
#Override
public void run() {
ambianceTextView.setText("test");
}
});
}
public void doAfterLogin() {
handlerRecup.postDelayed(retrieveData, 10000);
}
the runnable is started by a function called by a callback of an http request with Volley
public class StarterKillerPidroid {
void startApp() {
//Sending a request
PostmanPidroid.getInstance().login();
}
public void ackLogin(Boolean isValid) {
if (isValid) {
ActivityMain.getInstance().doAfterLogin();
} else {
PostmanPidroid.getInstance().login();
}
}
}
The class Postman :
public class Postman {
public void login(){
// Parameters
String email = "test#tes";
String password = "test";
// Encoding the request with parameters
JsonObjectRequest request = EncoderDecoderPidroid.getInstance()
.encodeRequestLogin(email, password);
// Sending the request
sendRequest(request);
}
void sendRequest(StringRequest message){
// Creating the queu if it's not create
if (queue == null) {
queue = Volley.newRequestQueue(context);
}
// Adding the request to the queue
queue.add(message);
}
}
When a success response is received, this callback is called :
private Response.Listener<JSONObject> callbackLogin =
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
...
StarterKillerPidroid.getInstance().ackLogin(true);
}
};
Basically, this kind of problem is due to the instance. It may be possible that your textview instance is not initialized. One more thing using handler directly for updating UI thread is not a good idea. Instead of directly updating Ui with handler you should use FunctionalInterface for doing this.
FunctionalInterface is a good approach for such cases.
A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. ... Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
Java has a predefined FunctionalInterface Callable. It goes something like this
public static void doDid(final Callable<Void> callable) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
callable.call();
handler.postDelayed(this, every * repeattime);
} catch (Exception e) {
e.printStackTrace();
}
}
}, every * tempvalue);
}
and use this for updating UI in this way
doDid(new Callable<Void>() {
#Override
public Void call() {
textView.setText("Your text");
return null;
}
});
There is one open-source library available for Android which works like a charm is such cases called Predictor. You can download it from here and import in your project. You can also contribute in this project for saving many developers life.
Do you wanna see how predictor can do this?
Predictor.every(3).second().doDid(new Job<Void>() {
#Override
public Void run() {
textView.setText("Your text");
return null;
}
});
What can you do with predictor?
Predictor gives you several ways of handling multithreading some of them are as follows:
Predictor.every(3).second().doDid(something());
Predictor.every(5).minutes().doDid(something());
Predictor.every().hour().doDid(something());
Predictor.every().week().doDid(something());
Predictor.every().month().doDid(something());
and many more...
Try this way:
private final Runnable retrieveData = new Runnable() {
public void run() {
try {
ambianceTextView = (TextView) findViewById(R.id.valeur_ambiance);
setText();
} catch (Exception e) {
e.printStackTrace();
}
handlerRecup.postDelayed(retrieveData, 1000);
}
};

Looper.prepare() error inside a thread

I am using handler to get GCM value
I want to update this value in my database
so I call AsyncTask from the handler
but I get this Error
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I checked other solutions they said I have to put the code in the run() section which I already do..
This is the code,
private void GetGCM(final String UserID) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
GCMHelper gcmRegistrationHelper = new GCMHelper(getApplicationContext());
String gcmRegID = "";
gcmRegID = gcmRegistrationHelper.GCMRegister("123456");
// Update using Web Service
try {
UpdateGCMWSTask updateGCMWSTask = new UpdateGCMWSTask();
updateGCMWSTask.execute(UserID, gcmRegID);
// ************ HERE IS THE ERROR ***********************
}catch (Exception e)
{
e.printStackTrace();
}
} catch (Exception bug) {
bug.printStackTrace();
}
}
});
thread.start();
}
Add Looper.prepare() and Looper.loop() in you code, like this:
private void GetGCM(final String UserID) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Looper.prepare();
GCMHelper gcmRegistrationHelper = new GCMHelper(getApplicationContext());
String gcmRegID = "";
gcmRegID = gcmRegistrationHelper.GCMRegister("123456");
// Update using Web Service
try {
UpdateGCMWSTask updateGCMWSTask = new UpdateGCMWSTask();
updateGCMWSTask.execute(UserID, gcmRegID);
// ************ HERE IS THE ERROR ***********************
}catch (Exception e)
{
e.printStackTrace();
}
Looper.loop();
} catch (Exception bug) {
bug.printStackTrace();
}
}
});
thread.start();
}
You can't create asynctask inside a thread. There are few ways to handle it:
Create a new handler.
Call function runOnUIThread of activity.
Using broadcast.

Vaadin Table using threads only working one way

I have a class called HomeView that is used to extend a Vaadin Designer HTML class. This class has a Vaadin table that takes input from an uploaded file. So far the file uploads fine and I can split the file up into lines for testing. I was trying to use Vaadin threads to lock the session and go to the UploadFile class in which I will split up the file and add to a row in the table. I would then unlock the session, exit back to the background thread and the UI should update the table with new rows. This is not happening with the code below.
public void uploadSucceeded(Upload.SucceededEvent succeededEvent) {
//upload notification for upload
new Notification("File Uploaded Successfully",
Notification.Type.HUMANIZED_MESSAGE)
.show(Page.getCurrent());
//create new class for parsing logic
uf = new UploadFile();
new Thread(new Runnable() {
#Override
public void run() {
try {
getSession().lock();
uf.parseFile();
getSession().unlock();
} catch (IOException e) {
new Notification("Could not parse file type",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
}
catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (ReadOnlyException e) {
e.printStackTrace();
}
}
}).start();
//outputFile.delete();
}
});
UploadFile class
public class UploadFile extends HomeView {
/**
*
*/
private static final long serialVersionUID = 839096232794540854L;
public void parseFile() throws IOException {
//container.removeAllItems();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println("before add:" + uploadTable.size());
container = uploadTable.getContainerDataSource();
container.addItem("row3");
Item item2 = container.getItem("row3");
Property property2 = item2.getItemProperty("name");
property2.setValue("hello");
uploadTable.setContainerDataSource(container);
System.out.println("after add:" + uploadTable.size());
}
reader.close();
}
}
If I take the code above and just put it in place of the method call, then the table updates fine. The table is updating the row count in the background, it's just not refreshing the view. What am I missing to make the UI refresh?
#Override
public void uploadSucceeded(Upload.SucceededEvent succeededEvent) {
//upload notification for upload
new Notification("File Uploaded Successfully",
Notification.Type.HUMANIZED_MESSAGE)
.show(Page.getCurrent());
//create new class for parsing logic
uf = new UploadFile();
new Thread(new Runnable() {
#Override
public void run() {
try {
getSession().lock();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println("before add:" + uploadTable.size());
container = uploadTable.getContainerDataSource();
container.addItem("row3");
Item item2 = container.getItem("row3");
Property property2 = item2.getItemProperty("name");
property2.setValue("hello");
uploadTable.setContainerDataSource(container);
System.out.println("after add:" + uploadTable.size());
}
reader.close();
getSession().unlock();
} catch (IOException e) {
new Notification("Could not parse file type",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
}
catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (ReadOnlyException e) {
e.printStackTrace();
}
}
}).start();
//outputFile.delete();
}
});
UI.getCurrent() helper uses a ThreadLocal variable to get the active UI and it only works in a code executed in UI thread (e.g. a init method or button click listener). Get the UI reference before constructing the Thread and use the access method around your code that modifies UI. Do not use getSession().lock() or similar, you'll most likely do something wrong with that. Here is a simple usage example that should help you to resolve your use case as well.
// Get the reference to UI to be modified
final UI ui = getUI();
new Thread() {
#Override
public void run() {
// Do stuff that don't affect UI state here, e.g. potentially
// slow calculation or rest call
final double d = 1*1;
ui.access(new Runnable() {
#Override
public void run() {
// This code here is safe to modify ui
Notification.show("The result of calculation is " + d);
}
});
}
}.start();
In addition to properly synchronised UI access you need to have properly working push connection or polling to get changes to the client. If you want to use "real push" you need to add the annotation and add vaadin-push module to your app. Simpler method (and most often just as good) is just to enable polling:
ui.setPollInterval(1000); // 1000ms polling interval for client

Simultaneous launch of two processes

I need to run two processes simultaneously.
I wrote the code:
public void starttwoprocessing () {
final Thread tworunprocessing = new Thread(new Runnable() {
public void run() {
FlashLight.onFlashResume();
handler.post(new Runnable() {
public void run() {
camera.takePicture(null, null, photoCallback);
}
});
}
});
tworunprocessing.start();
}
First start:
camera.takePicture(null, null, photoCallback);
The second:
FlashLight.onFlashResume();
After changing places with the same result.
In this case, I get the first shot and the flash is started later.
Thread.sleep(...); does not help
How to start simultaneously flash, and immediately take a picture?
Thanks
written like this:
public class Launcher
{
public void main(String args[]) throws IOException, InterruptedException
{
try {
Process[] proc = new Process[2];
proc[0] = new ProcessBuilder("FlashPreview.onFlashResumeStart()").start();
Thread.sleep(3000);
proc[1] = new ProcessBuilder("camera.takePicture(null, null, photoCallback)").start();
try {
Thread.sleep(3000);
}
catch (InterruptedException ex)
{
}
proc[0].destroy();
Thread.sleep(3000);
proc[1].destroy();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Called:
mk = new Launcher();
try {
mk.main(null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Something I'm doing wrong.
Does not work at all, no crash, but wrote in the log:07-05 16:38:58.217: W/System.err(30934): java.io.IOException: Error running exec(). Command: [FlashPreview.onFlashResumeStart()] Working Directory: null Environment: [ANDROID_SOCKET_zygote=9, SECONDARY_STORAGE=/storage/extSdCard:/storage/UsbDriveA:/storage/UsbDriveB:/storage/UsbDriveC:/storage/UsbDriveD:/storage/UsbDriveE:/storage/UsbDriveF, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/storage/sdcard0, ANDROID_ASSETS=/system/app, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/framework2.jar:/system/framework/framework_ext.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar:/system/framework/sec_edm.jar:/system/framework/seccamera.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=8,66560, VIBE_PIPE_PATH=/dev/pipes]
even using Threads your processes will runs after eche other. Using Threads means that second process no need to wait while first one is done. But easiest way how to fire two processes at the same time it is use timeout or ProcessBuilder
Also it can be good idea to run second process in first one. As for me it the best solution.
P.S. privet, ne chasto yvidiw zdes svoih s ykrainu)))
I have implemented the following:
class MyTask extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
FlashLight.onFlashResume();
}
#Override
protected Integer doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
camera.takePicture(null, null, photoCallback);
}
}

Method run() is not executed

I'm using java. I'm trying to execute a thread, but the issue I'm getting is
thread.start() method is getting executed, but as we know when we call the start method of thread, the run() method gets called internally.
But in my case the run() method is not getting executed:
public static void main(String[] args) throws Exception {
parseArguments(args);
ScraperStore scraperStore = ScraperStore.getInstance();
SocialSiteManager siteManager = new SocialSiteManager();
sitesToScrape = siteManager.getSocialSitesToScrape();
for (SocialSite site : sitesToScrape) {
ScrapeThread srThread = new ScrapeThread("srThread");
Thread scraper = new Thread(srThread);
srThread.setSiteToScrape(site);
srThread.setPageTypeToScrape(startPageToScrape);
srThread.setTypeToScrape(typeToScrape);
ArrayList<String> listOfValues = ScraperStore.getNextUrlToScrape(startPageToScrape, site);
srThread.setTypeToScrape(typeToScrape);
try {
srThread.setUrlOwnedBy(listOfValues.get(0));
srThread.setStartUrl(listOfValues.get(1));
scraper.start();
boolean state = scraper.isAlive();
scrapeThreads.add(scraper);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Thread class:
class ScrapeThread {
public ScrapeThread(String threadName) {
thread = new Thread(this,threadName);
System.out.println(thread.getName());
}
}
Run method:
public void run() {
try {
System.out.println("in the run method");
selenium = new DefaultSelenium(config.getHost(), Integer.parseInt(config.getPort()),
config.getBrowser(), config.getUrl());
selenium.start();
Integer count = 0;
while (startUrl != null) {
HtmlPage homePage = new HtmlPage();
homePage.setCreatedBy(new String());
homePage.setCreatedon(new String());
homePage.setModifiedBy(new String());
homePage.setModifiedOn(new String());
homePage.setNoOfItemsFound(new String());
homePage.setOwnedBy(urlOwnedBy);
homePage.setPageType(scraper.getPageTypeToScrape());
homePage.setPageUrl(startUrl);
proxy = getInitialisedProxy();
scraper.setNavigator(proxy.getNavigator());
scraper.setStartUrl(startUrl);
try {
scraper.initialize();
} catch (MyException e) {
if (status == false){
throw new Exception(MyException.NOTFOUND);
}
}
}
}
}
I'm using sellinium. Is there any chance that I'm getting the issue because of selenium?
Look at code and compare it with your code.
public static void main(String []args)
{
Runnable inst=new Runnable()
{
public void run()
{
System.out.println("Thread statement!");
}
};
Thread thrd=new Thread(inst);
thrd.start();
}
How did you come to know run method is not executed . didu u put a trace on the run method?
//Old
new Thread(niidleThread,"scraper"); scraper.start()
// new
new Thread(srThread); or
new Thread(srThread,"scraper");
Try the new one i have given above;
Just from a cursory review of your code... I see that you might have gone a little thread-happy. Consider:
ScrapeThread srThread = new ScrapeThread("srThread"); // This is creating your ScrapeThread object (which should really implement the Runnable interface)
Thread scraper = new Thread(srThread); // This is creating a thread which wraps another thread... take this out.
srThread.setSiteToScrape(site);
srThread.setPageTypeToScrape(startPageToScrape);
srThread.setTypeToScrape(typeToScrape);
ArrayList<String> listOfValues = ScraperStore.getNextUrlToScrape(startPageToScrape, site);
srThread.setTypeToScrape(typeToScrape);
try {
srThread.setUrlOwnedBy(listOfValues.get(0));
srThread.setStartUrl(listOfValues.get(1));
scraper.start(); // You would want to replace this with srThread.start(); once fixing the items I addressed above
boolean state=scraper.isAlive();
scrapeThreads.add(scraper);
}
catch (Exception e) {
e.printStackTrace();
}
http://www.javabeginner.com/learn-java/java-threads-tutorial might help you out a bit.

Categories

Resources