Search Results

Search found 112 results on 5 pages for 'progressdialog'.

Page 3/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Update UI from an event with a thread

    - by tyrone-tudehope
    Im working on a small application to try out an idea that I have. The idea is to periodically update the UI when event of some sort occurs. In the demo I've created, I'm updating a ProgressDialog every 2 seconds for 15 turns. The problem I am having, which I don't quite understand is that when an event is handled, I send a message to the handler which is supposed to update the message in the ProgressDialog. When this happens however, I get an exception which states that I can't update the UI from that thread. The following code appears in my Activity: ProgressDialog diag; String diagMessage = "Started loading..."; final static int MESSAGE_DATA_RECEIVED = 0; final static int MESSAGE_RECEIVE_COMPLETED = 1; final Handler handler = new Handler(){ @Override public void handleMessage(Message msg){ diag.setMessage(diagMessage); switch(msg.what){ case MESSAGE_DATA_RECEIVED: break; case MESSAGE_RECEIVE_COMPLETED: dismissDialog(); killDialog(); break; } } }; Boolean isRunning = false; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupDialog(); if(isRunning){ showDialog(); } setContentView(R.layout.main); } void setupDialog(){ if(diag == null){ diag = new ProgressDialog(ThreadLoading.this); diag.setMessage(diagMessage); } } void showDialog(){ isRunning = true; if(diag != null && !diag.isShowing()){ diag.show(); } } void dismissDialog(){ if(diag != null && diag.isShowing()){ diag.dismiss(); } } void killDialog(){ isRunning = false; } public void onStart(){ super.onStart(); showDialog(); Thread background = new Thread(new Runnable(){ public void run(){ try{ final ThreadRunner tr = new ThreadRunner(); tr.setOnDataReceivedListener(new ThreadRunner.OnDataReceivedListener(){ public void onDataReceived(String message){ diagMessage = message; handler.handleMessage(handler.obtainMessage(MESSAGE_DATA_RECEIVED)); } }); tr.setOnDataDownloadCompletedEventListener(new ThreadRunner.OnDataDownloadCompletedListener(){ public void onDataDownloadCompleted(String message){ diagMessage = message; handler.handleMessage(handler.obtainMessage(MESSAGE_RECEIVE_COMPLETED)); } }); tr.runProcess(); } catch(Throwable t){ throw new RuntimeException(t); } } }); background.start(); } @Override public void onPause(){ super.onPause(); dismissDialog(); } For curiosity sake, here's the code for the ThreadRunner class: public interface OnDataReceivedListener { public void onDataReceived(String message); } public interface OnDataDownloadCompletedListener { public void onDataDownloadCompleted(String message); } private OnDataReceivedListener onDataReceivedEventListener; private OnDataDownloadCompletedListener onDataDownloadCompletedEventListener; int maxLoop = 15; int loopCount = 0; int sleepTime = 2000; public void setOnDataReceivedListener(OnDataReceivedListener onDataReceivedListener){ this.onDataReceivedEventListener = onDataReceivedListener; } public void setOnDataDownloadCompletedEventListener(OnDataDownloadCompletedListener onDataDownloadCompletedListener){ this.onDataDownloadCompletedEventListener = onDataDownloadCompletedListener; } public void runProcess(){ for(loopCount = 0; loopCount < maxLoop; loopCount++){ try{ Thread.sleep(sleepTime); onDataReceivedEventListener.onDataReceived(Integer.toString(loopCount)); } catch(Throwable t){ throw new RuntimeException(t); } } onDataDownloadCompletedEventListener.onDataDownloadCompleted("Download is completed"); } Am I missing something? The logic makes sense to me and it looks like everything should work, I'm using a handler to update the UI like it is recommended. Any help will be appreciated. Thanks, Tyrone P.S. I'm developing for Android 1.5

    Read the article

  • Encrypt images before uploading to Dropbox [migrated]

    - by Cherry
    I want to encrypt a file first before the file will be uploaded to the dropbox. So i have implement the encryption inside the uploading of the codes. However, there is an error after i integrate the codes together. Where did my mistake go wrong? Error at putFileOverwriteRequest and it says The method putFileOverwriteRequest(String, InputStream, long, ProgressListener) in the type DropboxAPI is not applicable for the arguments (String, FileOutputStream, long, new ProgressListener(){}) Another problem is that this FileOutputStream fis = new FileOutputStream(new File("dont know what to put in this field")); i do not know where to put the file so that after i read the file, it will call the path and then upload to the Dropbox. Anyone is kind to help me in this? As time is running out for me and i still cant solve the problem. Thank you in advance. The full code is as below. public class UploadPicture extends AsyncTask<Void, Long, Boolean> { private DropboxAPI<?> mApi; private String mPath; private File mFile; private long mFileLen; private UploadRequest mRequest; private Context mContext; private final ProgressDialog mDialog; private String mErrorMsg; public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath, File file) { // We set the context this way so we don't accidentally leak activities mContext = context.getApplicationContext(); mFileLen = file.length(); mApi = api; mPath = dropboxPath; mFile = file; mDialog = new ProgressDialog(context); mDialog.setMax(100); mDialog.setMessage("Uploading " + file.getName()); mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mDialog.setProgress(0); mDialog.setButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { // This will cancel the putFile operation mRequest.abort(); } }); mDialog.show(); } @Override protected Boolean doInBackground(Void... params) { try { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey key = keygen.generateKey(); //generate key //encrypt file here first byte[] plainData; byte[] encryptedData; Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); //File f = new File(mFile); //read file FileInputStream in = new FileInputStream(mFile); //obtains input bytes from a file plainData = new byte[(int)mFile.length()]; in.read(plainData); //Read bytes of data into an array of bytes encryptedData = cipher.doFinal(plainData); //encrypt data FileOutputStream fis = new FileOutputStream(new File("dont know what to put in this field")); //upload to a path first then call the path so that it can be uploaded up to the dropbox //save encrypted file to dropbox // By creating a request, we get a handle to the putFile operation, // so we can cancel it later if we want to //FileInputStream fis = new FileInputStream(mFile); String path = mPath + mFile.getName(); mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(), new ProgressListener() { @Override public long progressInterval() { // Update the progress bar every half-second or so return 500; } @Override public void onProgress(long bytes, long total) { publishProgress(bytes); } }); if (mRequest != null) { mRequest.upload(); return true; } } catch (DropboxUnlinkedException e) { // This session wasn't authenticated properly or user unlinked mErrorMsg = "This app wasn't authenticated properly."; } catch (DropboxFileSizeException e) { // File size too big to upload via the API mErrorMsg = "This file is too big to upload"; } catch (DropboxPartialFileException e) { // We canceled the operation mErrorMsg = "Upload canceled"; } catch (DropboxServerException e) { // Server-side exception. These are examples of what could happen, // but we don't do anything special with them here. if (e.error == DropboxServerException._401_UNAUTHORIZED) { // Unauthorized, so we should unlink them. You may want to // automatically log the user out in this case. } else if (e.error == DropboxServerException._403_FORBIDDEN) { // Not allowed to access this } else if (e.error == DropboxServerException._404_NOT_FOUND) { // path not found (or if it was the thumbnail, can't be // thumbnailed) } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) { // user is over quota } else { // Something else } // This gets the Dropbox error, translated into the user's language mErrorMsg = e.body.userError; if (mErrorMsg == null) { mErrorMsg = e.body.error; } } catch (DropboxIOException e) { // Happens all the time, probably want to retry automatically. mErrorMsg = "Network error. Try again."; } catch (DropboxParseException e) { // Probably due to Dropbox server restarting, should retry mErrorMsg = "Dropbox error. Try again."; } catch (DropboxException e) { // Unknown error mErrorMsg = "Unknown error. Try again."; } catch (FileNotFoundException e) { } return false; } @Override protected void onProgressUpdate(Long... progress) { int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5); mDialog.setProgress(percent); } @Override protected void onPostExecute(Boolean result) { mDialog.dismiss(); if (result) { showToast("Image successfully uploaded"); } else { showToast(mErrorMsg); } } private void showToast(String msg) { Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG); error.show(); } }

    Read the article

  • Android exception i don't understand after loading webpage in a webview

    - by DixieFlatline
    I have a webview that loads a webpage. I also have a reload button. Sometimes it works but sometimes it crashes when i hit reload and i get this exceptions: 05-14 10:08:33.958: ERROR/WindowManager(918): Activity com.poslji.gor.Uvod has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@435da698 that was originally added here 05-14 10:08:33.958: ERROR/WindowManager(918): android.view.WindowLeaked: Activity com.poslji.gor.Uvod has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@435da698 that was originally added here 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewRoot.(ViewRoot.java:217) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.Window$LocalWindowManager.addView(Window.java:392) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.app.Dialog.show(Dialog.java:231) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.app.ProgressDialog.show(ProgressDialog.java:107) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.app.ProgressDialog.show(ProgressDialog.java:90) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.poslji.gor.Odgovori$2.onClick(Odgovori.java:120) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.View.performClick(View.java:2179) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.View.onTouchEvent(View.java:3828) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.widget.TextView.onTouchEvent(TextView.java:6307) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.View.dispatchTouchEvent(View.java:3368) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1752) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1206) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.app.Activity.dispatchTouchEvent(Activity.java:1997) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1736) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1752) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1206) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.app.Activity.dispatchTouchEvent(Activity.java:1997) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1736) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.view.ViewRoot.handleMessage(ViewRoot.java:1761) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.os.Handler.dispatchMessage(Handler.java:99) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.os.Looper.loop(Looper.java:123) 05-14 10:08:33.958: ERROR/WindowManager(918): at android.app.ActivityThread.main(ActivityThread.java:3948) 05-14 10:08:33.958: ERROR/WindowManager(918): at java.lang.reflect.Method.invokeNative(Native Method) 05-14 10:08:33.958: ERROR/WindowManager(918): at java.lang.reflect.Method.invoke(Method.java:521) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782) 05-14 10:08:33.958: ERROR/WindowManager(918): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540) 05-14 10:08:33.958: ERROR/WindowManager(918): at dalvik.system.NativeStart.main(Native Method) 05-14 10:08:36.768: ERROR/AndroidRuntime(918): Uncaught handler: thread main exiting due to uncaught exception 05-14 10:08:36.778: ERROR/AndroidRuntime(918): java.lang.IllegalArgumentException: View not attached to window manager 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:356) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:201) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.view.Window$LocalWindowManager.removeView(Window.java:400) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.app.Dialog.dismissDialog(Dialog.java:268) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.app.Dialog.access$000(Dialog.java:69) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.app.Dialog$1.run(Dialog.java:103) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.app.Dialog.dismiss(Dialog.java:252) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at com.poslji.gor.Odgovori$HelloWebViewClient.onPageFinished(Odgovori.java:180) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:225) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.os.Handler.dispatchMessage(Handler.java:99) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.os.Looper.loop(Looper.java:123) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at android.app.ActivityThread.main(ActivityThread.java:3948) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at java.lang.reflect.Method.invokeNative(Native Method) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at java.lang.reflect.Method.invoke(Method.java:521) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540) 05-14 10:08:36.778: ERROR/AndroidRuntime(918): at dalvik.system.NativeStart.main(Native Method) What is going wrong here?

    Read the article

  • call setListAdapter() from inside a thread

    - by Mats Hofman
    Hi, I have a problem with my ListActivity, i use a thread to show a ProgressDialog where get a list of all installed applications. I turn it into a list adapter and than i want to set the listadapter of the activity but i can't do that from the thread. I get the following error: ERROR/AndroidRuntime(14429): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. new Thread() { public void run() { showList(); // the method where i get all the apps and have the setListAdapter(); method progressDialog.dismiss(); } }.start(); How do I get it so I can use the setListAdapter from inside my thread

    Read the article

  • Progress Dialog in Android doesn't Show?

    - by Tyler
    Okay.. I am doing something similar to the below: private void onCreate() { final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true); Thread t = new Thread() { public void run() { //do some serious stuff... dialog.dismiss(); } }; t.start(); t.join(); stepTwo(); } However, what I am finding is that my progress dialog never even shows up. My App stalls for a moment so I know it is chugging along inside of thread t, but why doesnt my dialog appear? IF I remove the line: t.join(); Then what I find happens is that the progress dialog does show up, but my app starts stepTwo(); before what happens in the thread is complete.. Any ideas?

    Read the article

  • Data not displayed first time in android after copying the file from assets to data folder

    - by Thinkcomplete
    Description I have used the code tip from http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ to copy a pre-filled data file to the target and handled this in a asynch task Problem : On starting the application it gives error and shuts down first time, starting again without any change it works perfectly fine. So first time after the file is copied, the error comes but after that no issues. Please help Code attached:.. private class CopyDatabase extends AsyncTask<String, Void, Boolean> { private final ProgressDialog dialog = new ProgressDialog(BabyNames.this); protected void onPreExecute() { this.dialog.setMessage("Loading..."); this.dialog.show(); } @Override protected Boolean doInBackground(String... params) { // TODO Auto-generated method stub try { namesDBSQLHelper.createDatabase(); return null; } catch(IOException ioe){ ioe.printStackTrace(); } return null; } protected void onPostExecute(final Boolean success){ if (this.dialog.isShowing()){ this.dialog.dismiss(); } } }

    Read the article

  • Progress dialog getting dismissed before the thread gets finished - Android

    - by user264953
    Hi experts, I use the code provided by Fedor in the following link, in order to get the latitude and longitude from my simple demo app. I am trying to fetch the latitude and longitude using the MyLocation class provided by him in that link. What is the simplest and most robust way to get the user's current location in Android? I try to fetch the latitude and longitude on a button click. On the button click, I start an async task and delegate the location fetching work to the do in background method of my asynctask. pre execute - progressdialog initiated. post execute - progress dialog dismissed. This is how, the progress dialog in my code should work and here is the issue which I have. THe progress dialog gets initiated correctly, but even before the latitude and longitude gets printed in the doinbackground method, the progress dialog gets dismissed. I do not understand why this happens. Here is my front end activity public class LocationServices extends Activity { MyLocation myLocation = new MyLocation(); LocationResult locationResult; TextView tv1, tv2; Location location; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv1 = (TextView) findViewById(R.id.tv1); tv2 = (TextView) findViewById(R.id.tv2); Button btn = (Button) findViewById(R.id.Button01); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new LocationAsyncTasking().execute(); } }); } public class LocationAsyncTasking extends AsyncTask<String, Void, Void> { ProgressDialog dialog; int totalAvail; protected void onPreExecute() { // this.dialog.setMessage("Inserting data..."); dialog = new ProgressDialog(LocationServices.this); this.dialog.setMessage("Fetching data..."); this.dialog.show(); } protected Void doInBackground(String... args) { Looper.prepare(); locationResult = new LocationResult() { public void gotLocation(Location location) { // TODO Auto-generated method stub // LocationServices.this.location = location; System.out.println("Progress dialog should be present now - latitude"+location.getLatitude()); System.out.println("Progress dialog should be present now - longitude"+location.getLongitude()); } }; myLocation.getLocation(LocationServices.this, locationResult); return (null); } protected void onProgressUpdate(Integer... progress) { } protected void onPostExecute(Void unused) { dialog.dismiss(); } } } I am quite puzzled, thinking of what makes this progress dialog disappear even before the SOP in doinbackground is finished. Experts, please help me understand and resolve this issue. Any help in this regard is well appreciated. Looking forward, Best Regards, Rony

    Read the article

  • Android: how to update UI dynamically?

    - by pandre
    I have an Android app and I need to change UI dynamically: ex: when user presses a button, I want to change the current activity's views and, as in some cases there are a lot of views involved, I need to display a ProgressDialog. I have been using an AsyncTask, but I think that it is not the best solution, because AsyncTask's doInBackground runs a different thread, so I can't update UI from there - I have to use runOnUiThread, which runs the code in the UI Thread, but freezes the progress dialog that is shown. I guess there should be more people with similar issues, as updating UI while displaying a ProgressDialog seems to be something done regularly by applications. So does anyone have a solution to this?

    Read the article

  • Wait for inline thread to complete before moving to next method...

    - by Tyler
    Hello, I have an android app where I am doing the following: private void onCreate() { final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true); new Thread() { public void run() { //do some serious stuff... dialog.dismiss(); } }.start(); stepTwo(); } And I would like to ensure that my thread is complete before stepTwo(); is called. How can I do this? Thanks!

    Read the article

  • android webView loading finished but it was a blank only I touch the screen can the content show Idont know why?and how it happened

    - by Sunday
    when my webView load this page , it was blank-page or white page only I touch the screen the content can only show private WebView webview; private ProgressDialog mProgressDialog; private Context mContext; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); mContext = this; webview = (WebView)findViewById(R.id.myWebView); String url = (String)getIntent().getExtras().get("url"); webview.getSettings().setJavaScriptEnabled(true); webview.setWebViewClient(new MyWebViewClient()); if(url!=null){ webview.loadUrl(url); } } class MyWebViewClient extends WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mProgressDialog = ProgressDialog.show(mContext, "tips", "wate···the view is loading", true, false); } @Override public void onPageFinished(WebView view, String url) { mProgressDialog.dismiss(); super.onPageFinished(view, url); } }

    Read the article

  • NoMachine NX window closes after establishing connection

    - by blackicecube
    I am trying to use nomachine nx server and client. But somehow it doen't work. What happens is the following: Client starts up Client authenticates with Server The NoMachine window appears for 2-4 seconds The NoMachine window exists Somehow a "closeEvent" is sent. Here's what I see in the log file: [Thu Sep 24 11:20:37 2009]: Starting nxcomp with options: 'NX 299 Switch connection to: NX mode: unencrypted options: nx/nx,options=/home/foo/.nx/S-adnws029-1022-7EEF1367361DB2A7F4D9F76B06F4B434/options:1022'. [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: NXFileMonitor: opened file: [/home/foo/.nx/S-adnws029-1022-7EEF1367361DB2A7F4D9F76B06F4B434/session] [Thu Sep 24 11:20:38 2009]: LoginDialog::ShowConnectionStatus code=[246] str=[Initializing X protocol compression] error=[0] [Thu Sep 24 11:20:38 2009]: ProgressDialog::printNxStatus: [Initializing X protocol compression] [Thu Sep 24 11:20:38 2009]: LoginDialog::ShowConnectionStatus code=[247] str=[Established the display connection] error=[0] [Thu Sep 24 11:20:38 2009]: ProgressDialog::printNxStatus: [Established the display connection] [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: LoginDialog: slotAgentTimer [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: QClipboard: Unknown SelectionClear event received. [Thu Sep 24 11:20:38 2009]: LoginDialog: slotAgentTimer [Thu Sep 24 11:20:38 2009]: LoginDialog: Agent found closing windows... [Thu Sep 24 11:20:38 2009]: LoginDialog: setting automatic reconnection to true. [Thu Sep 24 11:20:38 2009]: Settings::flush [Thu Sep 24 11:20:38 2009]: Settings::flush [Thu Sep 24 11:20:38 2009]: LoginDialog: closeEvent received! [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: NXFileMonitor::readData [Thu Sep 24 11:20:38 2009]: LoginDialog::destructor called begin [Thu Sep 24 11:20:38 2009]: LoginDialog: stopAllTimers [Thu Sep 24 11:20:38 2009]: LoginDialog: stopProgressTimer [Thu Sep 24 11:20:38 2009]: Utility::getPreferencesFile: 'nxclient' - '/home/foo/.nx/config/nxclient.cfg' [Thu Sep 24 11:20:38 2009]: Settings::flush [Thu Sep 24 11:20:38 2009]: Called destructor for protocol class [Thu Sep 24 11:20:38 2009]: LoginDialog::destructor called end Anyone with a helpful idea?

    Read the article

  • Android: Retrieving Password via registered Email on My Server

    - by Raghavan'G'
    i am working on retrieving password to the user when he submits his mail id that he registered on my server. I need to check whether he entered correct registered id and give him response by sending password to his corresponding mail and set dialog as password sent to your mail or if he entered wrong mail id i have to show mail id not registered... Any Idea? This is my code... package com.soap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText public class Register extends Activity { /** Called when the activity is first created. */ // static Spinner operator = null; private static final String SOAP_ACTION = "......"; private static final String METHOD_NAME = "......"; private static final String NAMESPACE = "......"; private static final String URL = "My site"; private static final String TAG = "HELLO"; Thread t; ProgressDialog dialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.forgotpasswordpage); Button signin = (Button) findViewById(R.id.fpwdsubmit); signin.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(0); t = new Thread() { public void run() { register(); } }; t.start(); } }); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: { dialog = new ProgressDialog(this); dialog.setMessage("Please wait while connecting..."); dialog.setIndeterminate(true); dialog.setCancelable(true); return dialog; } } return null; } public void register() { Log.v(TAG, "Trying to Login"); EditText etxt_user = (EditText)findViewById(R.id.fpedtext); String email_id = etxt_user.getText().toString(); SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("Email", email_id); Pattern EMAIL_ADDRESS_PATTERN =Pattern.compile( "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+"); Matcher matcher = EMAIL_ADDRESS_PATTERN.matcher(email_id); if(matcher.matches()){ Log.v(TAG, "Your email id is valid ="+email_id); // System.out.println("Your email id is valid ="+email); } else{ // System.out.println("enter valid email id"); Log.v(TAG, "enter valid email id" ); } SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); soapEnvelope.dotNet = true; soapEnvelope.setOutputSoapObject(request); HttpTransportSE aht = new HttpTransportSE(URL); try { aht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); aht.call(SOAP_ACTION, soapEnvelope); SoapObject resultsRequestSOAP = (SoapObject) soapEnvelope.bodyIn; Log.v("TAG", String.valueOf(resultsRequestSOAP)); } catch (Exception e) { e.printStackTrace(); } } }

    Read the article

  • android upload progressbarr not working

    - by pieter
    I'm a beginner in Android programming and I was tryinh to upload an image to a server. I found some code here on stackoverflow, I adjusted it and it still doesn't work. The problem is my image still won't upload. edit I solved the problem, I had no rights on the folder on the server. Now I have a new problem. the progresbarr doesn't work. it keeps saying 0 % transmitted does anyone sees an error in my code? import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class PreviewActivity extends Activity { /** The captured image file. Get it's path from the starting intent */ private File mImage; public static final String EXTRA_IMAGE_PATH = "extraImagePath" /** Log tag */ private static final String TAG = "DFH"; /** Progress dialog id */ private static final int UPLOAD_PROGRESS_DIALOG = 0; private static final int UPLOAD_ERROR_DIALOG = 1; private static final int UPLOAD_SUCCESS_DIALOG = 2; /** Handler to confirm button */ private Button mConfirm; /** Handler to cancel button */ private Button mCancel; /** Uploading progress dialog */ private ProgressDialog mDialog; /** * Called when the activity is created * * We load the captured image, and register button callbacks */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.preview); setResult(RESULT_CANCELED); // Import image Bundle extras = getIntent().getExtras(); String imagePath = extras.getString(FotoActivity.EXTRA_IMAGE_PATH); Log.d("DFHprev", imagePath); mImage = new File(imagePath); if (mImage.exists()) { setResult(RESULT_OK); loadImage(mImage); } registerButtonCallbacks(); } @Override protected void onPause() { super.onPause(); } /** * Register callbacks for ui buttons */ protected void registerButtonCallbacks() { // Cancel button callback mCancel = (Button) findViewById(R.id.preview_send_cancel); mCancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { PreviewActivity.this.finish(); } }); // Confirm button callback mConfirm = (Button) findViewById(R.id.preview_send_confirm); mConfirm.setEnabled(true); mConfirm.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new UploadImageTask().execute(mImage); } }); } /** * Initialize the dialogs */ @Override protected Dialog onCreateDialog(int id) { switch(id) { case UPLOAD_PROGRESS_DIALOG: mDialog = new ProgressDialog(this); mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mDialog.setCancelable(false); mDialog.setTitle(getString(R.string.progress_dialog_title_connecting)); return mDialog; case UPLOAD_ERROR_DIALOG: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.upload_error_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.upload_error_message) .setCancelable(false) .setPositiveButton(getString(R.string.retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { PreviewActivity.this.finish(); } }); return builder.create(); case UPLOAD_SUCCESS_DIALOG: AlertDialog.Builder success = new AlertDialog.Builder(this); success.setTitle(R.string.upload_success_title) .setIcon(android.R.drawable.ic_dialog_info) .setMessage(R.string.upload_success_message) .setCancelable(false) .setPositiveButton(getString(R.string.success), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { PreviewActivity.this.finish(); } }); return success.create(); default: return null; } } /** * Prepare the progress dialog */ @Override protected void onPrepareDialog(int id, Dialog dialog) { switch(id) { case UPLOAD_PROGRESS_DIALOG: mDialog.setProgress(0); mDialog.setTitle(getString(R.string.progress_dialog_title_connecting)); } } /** * Load the image file into the imageView * * @param image */ protected void loadImage(File image) { Bitmap bm = BitmapFactory.decodeFile(image.getPath()); ImageView view = (ImageView) findViewById(R.id.preview_image); view.setImageBitmap(bm); } /** * Asynchronous task to upload file to server */ class UploadImageTask extends AsyncTask<File, Integer, Boolean> { /** Upload file to this url */ private static final String UPLOAD_URL = "http://www.xxxx.x/xxxx/fotos"; /** Send the file with this form name */ private static final String FIELD_FILE = "file"; /** * Prepare activity before upload */ @Override protected void onPreExecute() { super.onPreExecute(); setProgressBarIndeterminateVisibility(true); mConfirm.setEnabled(false); mCancel.setEnabled(false); showDialog(UPLOAD_PROGRESS_DIALOG); } /** * Clean app state after upload is completed */ @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); setProgressBarIndeterminateVisibility(false); mConfirm.setEnabled(true); mDialog.dismiss(); if (result) { showDialog(UPLOAD_SUCCESS_DIALOG); } else { showDialog(UPLOAD_ERROR_DIALOG); } } @Override protected Boolean doInBackground(File... image) { return doFileUpload(image[0], "UPLOAD_URL"); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); if (values[0] == 0) { mDialog.setTitle(getString(R.string.progress_dialog_title_uploading)); } mDialog.setProgress(values[0]); } private boolean doFileUpload(File file, String uploadUrl) { HttpURLConnection connection = null; DataOutputStream outputStream = null; DataInputStream inputStream = null; String pathToOurFile = file.getPath(); String urlServer = "http://www.xxxx.x/xxxx/upload.php"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; // log pathtoourfile Log.d("DFHinUpl", pathToOurFile); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1*1024*1024; int sentBytes = 0; long fileSize = file.length(); // log filesize String files= String.valueOf(fileSize); String buffers= String.valueOf(maxBufferSize); Log.d("fotosize",files); Log.d("buffers",buffers); try { FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) ); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // Enable POST method connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); outputStream = new DataOutputStream( connection.getOutputStream() ); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); sentBytes += bufferSize; publishProgress((int)(sentBytes * 100 / fileSize)); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); fileInputStream.close(); outputStream.flush(); outputStream.close(); try { int responseCode = connection.getResponseCode(); return responseCode == 200; } catch (IOException ioex) { Log.e("DFHUPLOAD", "Upload file failed: " + ioex.getMessage(), ioex); return false; } catch (Exception e) { Log.e("DFHUPLOAD", "Upload file failed: " + e.getMessage(), e); return false; } } catch (Exception ex) { String msg= ex.getMessage(); Log.d("DFHUPLOAD", msg); } return true; } } } the PHP code that handles this upload is following: <?php $date=getdate(); $urldate=$date['year'].$date['month'].$date['month'].$date['hours'].$date['minutes'].$date[ 'seconds']; $target_path = "./"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']) . $urldate; if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> would really appreciate it if someone could help me.

    Read the article

  • TabHost disappears after locking the phone and reopening it:

    - by Emil Adz
    I have a weird issue with my TabHost in my FragmentActivity that contains a ViewPager. The problem is that when I close my phone (press the power button) while I use my application, and then I turn back the phone and my application gets reopened, at this point my TabHost is missing. So the closing of my phone is causes the TabHost to disappear. My guess would be that I need to save my tabHost state in the saveInstanceState object, and restore it in onResume I only have no idea how it's done. here is my code for the FragmentActivity: public class TabsViewPagerFragmentActivity extends FragmentActivity implements ViewPager.OnPageChangeListener, TabHost.OnTabChangeListener { static final String TAG = TabsViewPagerFragmentActivity.class.getSimpleName(); private TabHost mTabHost; private ViewPager mViewPager; private HashMap<String, TabInfo> mapTabInfo; public ViewPagerAdapter mPagerAdapter; private TextView tvReportName, tvTabTitle; private Button bBackToParameters; private Dialog progressDialog; private SGRaportManagerAppObj application; private int numberOfTabs = 0; private Display display; public static final int POPUP_MARGIN = 6; LeftSideMenu leftSideMenu; public void NotifyTabActivityViewPagerAdapter() { mPagerAdapter.notifyDataSetChanged(); } public ViewPagerAdapter getTabActivityViewPagerAdapter() { return mPagerAdapter; } public ViewPager getTabActivityViewPager() { return mViewPager; } public void setCurrentTabTitle (String title) { tvTabTitle.setText(title); Log.d(TAG, "set tab title from activity: "+title); } /** * Maintains extrinsic info of a tab's construct */ private class TabInfo { private String tag; private Class<?> clss; private Bundle args; private Fragment fragment; TabInfo(String tag, Class<?> clazz, Bundle args) { this.tag = tag; this.clss = clazz; this.args = args; } } /** * A simple factory that returns dummy views to the Tabhost */ class TabFactory implements TabContentFactory { private final Context mContext; /** * @param context */ public TabFactory(Context context) { mContext = context; } /** (non-Javadoc) * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String) */ public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } /** (non-Javadoc) * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle) */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); application = SGRaportManagerAppObj.getInstance(); display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); // Inflate the layout setContentView(R.layout.tabs_screen_activity_layout); tvTabTitle = (TextView) findViewById(R.id.tvTabName); tvReportName = (TextView)findViewById(R.id.tvReportName); tvReportName.setText(application.currentReport.getName()+ " - "); bBackToParameters = (Button) findViewById(R.id.bBackToParameters); leftSideMenu = (LeftSideMenu) findViewById(R.id.leftSideMenu); applyOnClickListenerToLeftSideMenu(); findViewById(R.id.showLeftMenuButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Display d = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int width = d.getWidth(); View panel = findViewById(R.id.leftSideMenu); View appPanel = findViewById(R.id.appLayout); if (panel.getVisibility() == View.GONE){ appPanel.setLayoutParams(new LinearLayout.LayoutParams(width, LayoutParams.FILL_PARENT)); panel.setVisibility(View.VISIBLE); applyOnClickListenerToLeftSideMenu(); }else{ ToggleButton button = (ToggleButton) findViewById(R.id.showLeftMenuButton); button.setChecked(false); panel.setVisibility(View.GONE); } } }); // Initialise the TabHost progressDialog = DialogUtils.createProgressDialog(this, this.getString(R.string.populating_view_pager)); progressDialog.show(); if (SGRaportManagerAppObj.getInstance().parametersRepository.getParametersRepository().size() == 0) { bBackToParameters.setText(R.string.back_to_report_list); } this.initialiseTabHost(savedInstanceState); if (savedInstanceState != null) { mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state } // Intialise ViewPager this.intialiseViewPager(); progressDialog.dismiss(); } /** (non-Javadoc) * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle) */ protected void onSaveInstanceState(Bundle outState) { outState.putString("tab", mTabHost.getCurrentTabTag()); //save the tab selected super.onSaveInstanceState(outState); } /** * Initialise ViewPager */ public void intialiseViewPager() { List<Fragment> fragments = new Vector<Fragment>(); // TabInfo tabInfo = null; if (application.getCurrentDataSource().equals(DataSource.SSRS)) { numberOfTabs = application.currentReport.getTabsList().size(); } else if (application.getCurrentDataSource().equals(DataSource.SGRDL)) { numberOfTabs = application.currentReport.getODTabsList().size(); Log.d(TAG, "CURRENT REPORT FROM VIEW PAGER: "+ application.currentReport.toString()); } Log.d(TAG,"Current Tabs number from TabsViewPager activity: " +numberOfTabs); if (application.getCurrentDataSource().equals(DataSource.SSRS)) { for (int i = 0; i < numberOfTabs; i++) { Tab tempTab = application.currentReport.getTabsList().get(i); if (tempTab.getTabTemplateId() == 7) { GridFragment gridFragment = new GridFragment(tempTab); fragments.add(gridFragment); } else if (tempTab.getTabTemplateId() == 8) { NewChartFragment chartFragment = new NewChartFragment(tempTab, this); fragments.add(chartFragment); } } } else if (application.getCurrentDataSource().equals(DataSource.SGRDL)) { for (int i = 0; i < numberOfTabs; i++) { ODTab tempTab = application.currentReport.getODTabsList().get(i); if (tempTab.getTabType().equals(ODGrid.XML_GRID_ELEMENT)) { GridFragment gridFragment = GridFragment.newInstance(tempTab.getTabId()); fragments.add(gridFragment); } else if (tempTab.getTabType().equals(ODChart.XML_CHART_ELEMENT)) { NewChartFragment chartFragment = NewChartFragment.newInstance(tempTab.getTabId()); fragments.add(chartFragment); } } } Log.d(TAG, "Current report fragments set to adapter: "+fragments.toString()); /* if (this.mPagerAdapter == null) { this.mPagerAdapter = new ViewPagerAdapter(super.getSupportFragmentManager(), fragments); } else { this.mPagerAdapter.removeAllFragments(); this.mPagerAdapter.addFragmentsListToAdapter(fragments); } */ this.mPagerAdapter = new ViewPagerAdapter(super.getSupportFragmentManager(), fragments); this.mViewPager = (ViewPager)super.findViewById(R.id.pager); // this.mViewPager.setAdapter(null); this.mViewPager.setAdapter(this.mPagerAdapter); this.mViewPager.setOffscreenPageLimit(0); this.mViewPager.setOnPageChangeListener(this); Log.d(TAG, "Adapter initialized!"); } /** * Initialise the Tab Host */ public void initialiseTabHost(Bundle args) { mTabHost = (TabHost)findViewById(android.R.id.tabhost); /* //new edit if (mTabHost.getChildCount() > 0) { mTabHost.removeAllViews(); } */ mTabHost.setup(); TabInfo tabInfo = null; mapTabInfo = new HashMap<String, TabsViewPagerFragmentActivity.TabInfo>(); if (args != null) {} else { if (application.getCurrentDataSource().equals(DataSource.SSRS)) { int numberOfTabs = application.currentReport.getTabsList().size(); for (int i = 0; i < numberOfTabs; i++) { Tab tempTab = application.currentReport.getTabsList().get(i); if (tempTab.getTabTemplateId() == 7) { //GridFragment gridFragment = new GridFragment(tempTab); TabsViewPagerFragmentActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab "+String.valueOf(i)).setIndicator("Tab "+String.valueOf(i)), ( tabInfo = new TabInfo("Tab "+String.valueOf(i), GridFragment.class, args))); this.mapTabInfo.put(tabInfo.tag, tabInfo); } else if (tempTab.getTabTemplateId() == 8) { TabsViewPagerFragmentActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab "+String.valueOf(i)).setIndicator("Tab "+String.valueOf(i)), ( tabInfo = new TabInfo("Tab "+String.valueOf(i), NewChartFragment.class, args))); this.mapTabInfo.put(tabInfo.tag, tabInfo); } } } else if (application.getCurrentDataSource().equals(DataSource.SGRDL)) { int numberOfTabs = application.currentReport.getODTabsList().size(); for (int i = 0; i < numberOfTabs; i++) { ODTab tempTab = application.currentReport.getODTabsList().get(i); // Log.d(TAG,"Crashed Tab type: "+ tempTab.getTabType()); if (tempTab.getTabType().equals(ODGrid.XML_GRID_ELEMENT)) { //GridFragment gridFragment = new GridFragment(tempTab); TabsViewPagerFragmentActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab "+String.valueOf(i)).setIndicator("Tab "+String.valueOf(i)), ( tabInfo = new TabInfo("Tab "+String.valueOf(i), GridFragment.class, args))); this.mapTabInfo.put(tabInfo.tag, tabInfo); } else if (tempTab.getTabType().equals(ODChart.XML_CHART_ELEMENT)) { TabsViewPagerFragmentActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab "+String.valueOf(i)).setIndicator("Tab "+String.valueOf(i)), ( tabInfo = new TabInfo("Tab "+String.valueOf(i), NewChartFragment.class, args))); this.mapTabInfo.put(tabInfo.tag, tabInfo); } } } } // Default to first tab //this.onTabChanged("Tab1"); // mTabHost.setOnTabChangedListener(this); } /** * Add Tab content to the Tabhost * @param activity * @param tabHost * @param tabSpec * @param clss * @param args */ private static void AddTab(TabsViewPagerFragmentActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) { // Attach a Tab view factory to the spec ImageView indicator = new ImageView(activity.getBaseContext()); indicator.setPadding(10, 10, 10, 10); indicator.setImageResource(R.drawable.tab_select_icon_selector); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(10, 10, 10, 10); indicator.setLayoutParams(lp); tabSpec.setIndicator(indicator); tabSpec.setContent(activity.new TabFactory(activity)); tabHost.addTab(tabSpec); } /** (non-Javadoc) * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String) */ public void onTabChanged(String tag) { //TabInfo newTab = this.mapTabInfo.get(tag); int pos = this.mTabHost.getCurrentTab(); this.mViewPager.setCurrentItem(pos); } /* (non-Javadoc) * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrolled(int, float, int) */ @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageSelected(int) */ @Override public void onPageSelected(int position) { // TODO Auto-generated method stub this.mTabHost.setCurrentTab(position); } /* (non-Javadoc) * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrollStateChanged(int) */ @Override public void onPageScrollStateChanged(int state) { // TODO Auto-generated method stub } How would one save the state of the TabHost and restore it in onResume? Any help would be very appreciated.

    Read the article

  • Making a database backup to SDCard on Android

    - by Pentium10
    I am using the below code to write a backup copy to SDCard and I get java.io.IOException: Parent directory of file is not writable: /sdcard/mydbfile.db private class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> { private final ProgressDialog dialog = new ProgressDialog(ctx); // can use UI thread here protected void onPreExecute() { this.dialog.setMessage("Exporting database..."); this.dialog.show(); } // automatically done on worker thread (separate from UI thread) protected Boolean doInBackground(final String... args) { File dbFile = new File(Environment.getDataDirectory() + "/data/com.mypkg/databases/mydbfile.db"); File exportDir = new File(Environment.getExternalStorageDirectory(), ""); if (!exportDir.exists()) { exportDir.mkdirs(); } File file = new File(exportDir, dbFile.getName()); try { file.createNewFile(); this.copyFile(dbFile, file); return true; } catch (IOException e) { Log.e("mypck", e.getMessage(), e); return false; } } // can use UI thread here protected void onPostExecute(final Boolean success) { if (this.dialog.isShowing()) { this.dialog.dismiss(); } if (success) { Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show(); } } void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } }

    Read the article

  • Webview shouldoverrideurlloading doesn't work

    - by Zak
    I have this code in my app: public class Home extends Activity{ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.home); final ProgressDialog progressBar; if(isOnline()){ WebView webView = (WebView) findViewById(R.id.home_web); webView.setBackgroundColor(Color.parseColor(getString(R.color.colore_bg))); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setPluginsEnabled(true); webView.setWebViewClient(new MyWebViewClient()); progressBar = ProgressDialog.show(this,getString(R.string.caricamento),getString(R.string.attendere)); webView.setWebViewClient(new WebViewClient(){ public void onPageFinished(WebView view, String url) { if (progressBar.isShowing()) { progressBar.dismiss(); } } }); webView.loadUrl("http://www.mysite.com/android.php"); }else{ Toast.makeText(this,getString(R.string.no_connessione),Toast.LENGTH_LONG).show(); } } private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { System.out.println("here"); if (Uri.parse(url).getHost().equals("mysite.com")) { // This is my web site, so do not override; let my WebView load the page return false; } // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } } public boolean isOnline(){ ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if(ni==null){ return false; } return ni.isConnected(); } } The shouldOverrideUrlLoading doesn't work, neither print the system.out, it seems to be never called. How can I repair this? I need to open all the link (except the main page www.mysite.com/iphone.php) in the default browser

    Read the article

  • Functioning Socket read no longer works when called in AsyncTask

    - by bibismcbryde
    I'm making an app that sends a string to a server over a socket and then reads the output after the server has processed that data. It worked perfectly when it was my foreground task, but I have since used AsyncTask to show a process dialog while the socket communication runs in the background, and things start breaking after I read the output from the server and then try to close the socket. private class Progressor extends AsyncTask<String, Void, Void> { ProgressDialog dialog; protected void onPreExecute() { dialog = ProgressDialog.show(ClearTalkInputActivity.this, "Loading..", "Analyzing Text", true, false); } protected Void doInBackground(String... strings) { String language = strings[0].toLowerCase(); String the_text = strings[1]; Socket socket = null; DataOutputStream dos = null; DataInputStream dis = null; try { socket = new Socket(my_ip, port); dos = new DataOutputStream(socket.getOutputStream()); dis = new DataInputStream(socket.getInputStream()); dos.writeUTF(language+"****"+the_text); String in = ""; while (in.indexOf("</content>") < 0) { in += dis.readUTF(); } socket.close(); save_str(OUTPUT_KEY, in); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } if (dis != null) { try { dis.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } protected void onPostExecute() { if (dialog.isShowing()) dialog.dismiss(); startActivity(new Intent (output_intent)); } }

    Read the article

  • Call AsyncTask methods from another class/service (callbacks?)

    - by TiGer
    Hi, I was wondering if it's possible to call specific methods defined within the AsynTask class from another class and/or service ? In my specific case I have a Service playing some sounds, but the sound is selected from a List with available sounds... When a sounds is selected it is downloaded from my home server, this takes some time (not much, let's say around the 3-4 seconds, the sounds/effects aren't big in size)... So my problem at the moment is that I have a service to play those sounds, and when I select one I wanted to show a progressdialog... The way (if I understood correctly) is to use an AsyncTask, but the only thing the AsyncTask will do is telling my Service to play a specific sound from my server... So there is no "callback" from the service to the Asynctask... How can I achieve that ? How can I call a running AsyncTask, which sits in another class, and tell him all work is done and thus he can stop showing the ProgressDialog ? Or am I over-engineering it and there are other ways ? Thanks in advance...

    Read the article

  • Show dialog while loading new screen

    - by darkdusky
    I have a front screen with a button which opens a second screen. The second screen can take a few seconds to load so I want to display a dialog while loading. My problem is the dialog does not display while loading second screen, but it displays when I return to first page from the second page. If I comment out the "startActivity" to open second page the dialog shows fine. I'm fairly new to android programming - I guess it has something to do with threads. //code snippet from inside onCreate: NewGame.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { //does not get displayed before 2nd page opens showDialog(DIALOG2_KEY); //shows fine if next 2 lines commented out Intent i = new Intent(screen1.this, SudukuXL.class); startActivity(i); I've dealt with the dialog showing on returning to the front screen using onPause(). I've tried using threads to seperate the dialog from the startActivity but I've had no luck. Any help would be appreciated. I used code from Android examples to create dialog. I include below for reference: protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG2_KEY: { ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage("Loading..."); dialog.setIndeterminate(true); dialog.setCancelable(true); return dialog; } } return null; }

    Read the article

  • PrgressDialog when load a WebView crash issue

    - by AndreaF
    I have an Activity with a WeView that load an url, and I want to display a little waiting dialog during the load of the site, so I have tried this: private ProgressDialog dialog = new ProgressDialog(MyNameActivity.this); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); setContentView(R.layout.web_view_activity); WebView wv; wv = (WebView) findViewById(R.id.areaWebSolver); wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { if (dialog.isShowing()) { dialog.dismiss(); } } }); dialog.setMessage("Loading..Please wait."); dialog.setCanceledOnTouchOutside(false); dialog.show(); wv.loadUrl(url); WebSettings webSettings = wv.getSettings(); webSettings.setJavaScriptEnabled(true); } Unfortunately doesn't works and the app crashes with a source not found... If I try to remove the Progress dialog code the activity works. What's wrong? How could I fix this?

    Read the article

  • [Android] Force close when trying to parse JSON with AsyncTask in the background

    - by robs
    Hello everyone, i'm new to android development and i'm playing around with json data. I managed to get the parsing to work. I want to show a ProgressDialog and i read that i need to use AsyncTask that. But for some reason i get a force close as soon as i put the same working code inside doInBackground() eventhough eclipse says everything is fine. Here is the source code: public class HomeActivity extends Activity { public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> { ProgressDialog dialog = new ProgressDialog (HomeActivity.this); @Override protected void onPreExecute() { dialog.setMessage("Loading...please wait"); dialog.setIndeterminate(true); dialog.setCancelable(false); dialog.show(); } protected void onPostExecute() { dialog.dismiss(); } @Override protected Void doInBackground(Void... params) { try { URL json = new URL("http://www.corps-marchia.de/jsontest.php"); URLConnection tc = json.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream())); String line; while ((line = in.readLine()) != null) { JSONArray ja = new JSONArray(line); JSONObject jo = (JSONObject) ja.get(0); TextView txtView = (TextView)findViewById(R.id.TextView01); txtView.setText(jo.getString("text")); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new BackgroundAsyncTask().execute(); } } Here is the error log: 01-08 12:33:48.225: ERROR/AndroidRuntime(815): FATAL EXCEPTION: AsyncTask #1 01-08 12:33:48.225: ERROR/AndroidRuntime(815): java.lang.RuntimeException: An error occured while executing doInBackground() 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.os.AsyncTask$3.done(AsyncTask.java:200) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at java.util.concurrent.FutureTask.setException(FutureTask.java:125) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at java.lang.Thread.run(Thread.java:1019) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.view.ViewRoot.checkThread(ViewRoot.java:2932) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.view.ViewRoot.requestLayout(ViewRoot.java:629) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.view.View.requestLayout(View.java:8267) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.view.View.requestLayout(View.java:8267) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.view.View.requestLayout(View.java:8267) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.view.View.requestLayout(View.java:8267) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.view.View.requestLayout(View.java:8267) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.widget.TextView.checkForRelayout(TextView.java:5521) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.widget.TextView.setText(TextView.java:2724) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.widget.TextView.setText(TextView.java:2592) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.widget.TextView.setText(TextView.java:2567) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at net.ajzele.demo.andy1.HomeActivity$BackgroundAsyncTask.doInBackground(HomeActivity.java:52) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at net.ajzele.demo.andy1.HomeActivity$BackgroundAsyncTask.doInBackground(HomeActivity.java:1) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at android.os.AsyncTask$2.call(AsyncTask.java:185) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 01-08 12:33:48.225: ERROR/AndroidRuntime(815): ... 4 more 01-08 12:33:51.605: ERROR/WindowManager(815): Activity net.ajzele.demo.andy1.HomeActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051d0c0 that was originally added here 01-08 12:33:51.605: ERROR/WindowManager(815): android.view.WindowLeaked: Activity net.ajzele.demo.andy1.HomeActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051d0c0 that was originally added here 01-08 12:33:51.605: ERROR/WindowManager(815): at android.view.ViewRoot.<init>(ViewRoot.java:258) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.view.Window$LocalWindowManager.addView(Window.java:424) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.app.Dialog.show(Dialog.java:241) 01-08 12:33:51.605: ERROR/WindowManager(815): at net.ajzele.demo.andy1.HomeActivity$BackgroundAsyncTask.onPreExecute(HomeActivity.java:33) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.os.AsyncTask.execute(AsyncTask.java:391) 01-08 12:33:51.605: ERROR/WindowManager(815): at net.ajzele.demo.andy1.HomeActivity.onCreate(HomeActivity.java:72) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.os.Handler.dispatchMessage(Handler.java:99) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.os.Looper.loop(Looper.java:123) 01-08 12:33:51.605: ERROR/WindowManager(815): at android.app.ActivityThread.main(ActivityThread.java:3647) 01-08 12:33:51.605: ERROR/WindowManager(815): at java.lang.reflect.Method.invokeNative(Native Method) 01-08 12:33:51.605: ERROR/WindowManager(815): at java.lang.reflect.Method.invoke(Method.java:507) 01-08 12:33:51.605: ERROR/WindowManager(815): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 01-08 12:33:51.605: ERROR/WindowManager(815): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 01-08 12:33:51.605: ERROR/WindowManager(815): at dalvik.system.NativeStart.main(Native Method) Any hints? I hope you can help me out ive searched the net and didnt find any working solution...Thanks in advance

    Read the article

  • Get data from MySQL to Android application

    - by Mona
    I want to get data from MySQL database using PHP and display it in Android activity. I code it and pass JSON Array but there is a problem i dont know how to connect to server and my all database is on local server. I code it Kindly tell me where i go wrong so I can get exact results. I'll be very thankful to you. My PHP code is: <?php $response = array(); require_once __DIR__ . '/db_connect.php'; $db = new DB_CONNECT(); if (isset($_GET["cid"])) { $cid = $_GET['cid']; // get a product from products table $result = mysql_query("SELECT *FROM my_task WHERE cid = $cid"); if (!empty($result)) { // check for empty result if (mysql_num_rows($result) > 0) { $result = mysql_fetch_array($result); $task = array(); $task["cid"] = $result["cid"]; $task["cus_name"] = $result["cus_name"]; $task["contact_number"] = $result["contact_number"]; $task["ticket_no"] = $result["ticket_no"]; $task["task_detail"] = $result["task_detail"]; // success $response["success"] = 1; // user node $response["task"] = array(); array_push($response["my_task"], $task); // echoing JSON response echo json_encode($response); } else { // no task found $response["success"] = 0; $response["message"] = "No product found"; // echo no users JSON echo json_encode($response); } } else { // no task found $response["success"] = 0; $response["message"] = "No product found"; echo json_encode($response); } } else { $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response);} ?> My Android code is: public class My_Task extends Activity { TextView cus_name_txt, contact_no_txt, ticket_no_txt, task_detail_txt; EditText attend_by_txtbx, cus_name_txtbx, contact_no_txtbx, ticket_no_txtbx, task_detail_txtbx; Button btnSave; Button btnDelete; String cid; // Progress Dialog private ProgressDialog tDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList<HashMap<String, String>> my_taskList; // single task url private static final String url_read_mytask = "http://198.168.0.29/mobile/read_My_Task.php"; // url to update product private static final String url_update_mytask = "http://198.168.0.29/mobile/update_mytask.php"; // url to delete product private static final String url_delete_mytask = "http://198.168.0.29/mobile/delete_mytask.php"; // JSON Node names private static String TAG_SUCCESS = "success"; private static String TAG_MYTASK = "my_task"; private static String TAG_CID = "cid"; private static String TAG_NAME = "cus_name"; private static String TAG_CONTACT = "contact_number"; private static String TAG_TICKET = "ticket_no"; private static String TAG_TASKDETAIL = "task_detail"; private static String attend_by_txt; // task JSONArray JSONArray my_task = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_task); cus_name_txt = (TextView) findViewById(R.id.cus_name_txt); contact_no_txt = (TextView)findViewById(R.id.contact_no_txt); ticket_no_txt = (TextView)findViewById(R.id.ticket_no_txt); task_detail_txt = (TextView)findViewById(R.id.task_detail_txt); attend_by_txtbx = (EditText)findViewById(R.id.attend_by_txt); attend_by_txtbx.setText(My_Task.attend_by_txt); Spinner severity = (Spinner) findViewById(R.id.severity_spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this, R.array.Severity_array, android.R.layout.simple_dropdown_item_1line); // Specify the layout to use when the list of choices appears adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner severity.setAdapter(adapter3); // save button btnSave = (Button) findViewById(R.id.btnSave); btnDelete = (Button) findViewById(R.id.btnDelete); // getting product details from intent Intent i = getIntent(); // getting product id (pid) from intent cid = i.getStringExtra(TAG_CID); // Getting complete product details in background thread new GetProductDetails().execute(); // save button click event btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // starting background task to update product new SaveProductDetails().execute(); } }); // Delete button click event btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // deleting product in background thread new DeleteProduct().execute(); } }); } /** * Background Async Task to Get complete product details * */ class GetProductDetails extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); tDialog = new ProgressDialog(My_Task.this); tDialog.setMessage("Loading task details. Please wait..."); tDialog.setIndeterminate(false); tDialog.setCancelable(true); tDialog.show(); } /** * Getting product details in background thread * */ protected String doInBackground(String... params) { // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { // Check for success tag int success; try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("cid", cid)); // getting product details by making HTTP request // Note that product details url will use GET request JSONObject json = JSONParser.makeHttpRequest( url_read_mytask, "GET", params); // check your log for json response Log.d("Single Task Details", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully received product details JSONArray my_taskObj = json .getJSONArray(TAG_MYTASK); // JSON Array // get first product object from JSON Array JSONObject my_task = my_taskObj.getJSONObject(0); // task with this cid found // Edit Text // display task data in EditText cus_name_txtbx = (EditText) findViewById(R.id.cus_name_txt); cus_name_txtbx.setText(my_task.getString(TAG_NAME)); contact_no_txtbx = (EditText) findViewById(R.id.contact_no_txt); contact_no_txtbx.setText(my_task.getString(TAG_CONTACT)); ticket_no_txtbx = (EditText) findViewById(R.id.ticket_no_txt); ticket_no_txtbx.setText(my_task.getString(TAG_TICKET)); task_detail_txtbx = (EditText) findViewById(R.id.task_detail_txt); task_detail_txtbx.setText(my_task.getString(TAG_TASKDETAIL)); } else { // task with cid not found } } catch (JSONException e) { e.printStackTrace(); } } }); return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once got all details tDialog.dismiss(); } } /** * Background Async Task to Save product Details * */ class SaveProductDetails extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); tDialog = new ProgressDialog(My_Task.this); tDialog.setMessage("Saving task ..."); tDialog.setIndeterminate(false); tDialog.setCancelable(true); tDialog.show(); } /** * Saving product * */ protected String doInBackground(String... args) { // getting updated data from EditTexts String cus_name = cus_name_txt.getText().toString(); String contact_no = contact_no_txt.getText().toString(); String ticket_no = ticket_no_txt.getText().toString(); String task_detail = task_detail_txt.getText().toString(); // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(TAG_CID, cid)); params.add(new BasicNameValuePair(TAG_NAME, cus_name)); params.add(new BasicNameValuePair(TAG_CONTACT, contact_no)); params.add(new BasicNameValuePair(TAG_TICKET, ticket_no)); params.add(new BasicNameValuePair(TAG_TASKDETAIL, task_detail)); // sending modified data through http request // Notice that update product url accepts POST method JSONObject json = JSONParser.makeHttpRequest(url_update_mytask, "POST", params); // check json success tag try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully updated Intent i = getIntent(); // send result code 100 to notify about product update setResult(100, i); finish(); } else { // failed to update product } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product uupdated tDialog.dismiss(); } } /***************************************************************** * Background Async Task to Delete Product * */ class DeleteProduct extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); tDialog = new ProgressDialog(My_Task.this); tDialog.setMessage("Deleting Product..."); tDialog.setIndeterminate(false); tDialog.setCancelable(true); tDialog.show(); } /** * Deleting product * */ protected String doInBackground(String... args) { // Check for success tag int success; try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("cid", cid)); // getting product details by making HTTP request JSONObject json = JSONParser.makeHttpRequest( url_delete_mytask, "POST", params); // check your log for json response Log.d("Delete Task", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { // product successfully deleted // notify previous activity by sending code 100 Intent i = getIntent(); // send result code 100 to notify about product deletion setResult(100, i); finish(); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted tDialog.dismiss(); } } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } } My JSONParser code is: public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public static JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; my all database is in localhost and it is not opening an activity. displays an error "Stopped unexpectedly":( How can i get exact results. Kindly guide me

    Read the article

  • Android WebView not loading a JavaScript file, but Android Browser loads it fine.

    - by Justin
    I'm writing an application which connects to a back office site. The backoffice site contains a whole slew of JavaScript functions, at least 100 times the average site. Unfortunately it does not load them, and causes much of the functionality to not work properly. So I am running a test. I put a page out on my server which loads the FireBugLite javascript text. Its a lot of javascript and perfect to test and see if the Android WebView will load it. The WebView loads nothing, but the browser loads the Firebug Icon. What on earth would make the difference, why can it run in the browser and not in my WebView? Any suggestions. More background information, in order to get the stinking backoffice application available on a Droid (or any other platform except windows) I needed to trick the bakcoffice application to believe what's accessing the website is Internet Explorer. I do this by modifying the WebView User Agent. Also for this application I've slimmed my landing page, so I could give you the source to offer me aid. package ksc.myKMB; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebSettings; import android.webkit.WebViewClient; import android.widget.Toast; public class myKMB extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /** Performs base set up */ /** Create a Activity of this Activity, IE myProcess */ myProcess = this; /*** Create global objects and web browsing objects */ HideDialogOnce = true; webview = new WebView(this) { }; webChromeClient = new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { // Activities and WebViews measure progress with different scales. // The progress meter will automatically disappear when we reach 100% myProcess.setProgress((progress * 100)); //CreateMessage("Progress is : " + progress); } }; webViewClient = new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(myProcess, MessageBegText + description + MessageEndText, Toast.LENGTH_SHORT).show(); } public void onPageFinished (WebView view, String url) { /** Hide dialog */ try { // loadingDialog.dismiss(); } finally { } //myProcess.setProgress(1000); /** Fon't show the dialog while I'm performing fixes */ //HideDialogOnce = true; view.loadUrl("javascript:document.getElementById('JTRANS011').style.visibility='visible';"); } public void onPageStarted(WebView view, String url, Bitmap favicon) { if (HideDialogOnce == false) { //loadingDialog = ProgressDialog.show(myProcess, "", // "One moment, the page is laoding...", true); } else { //HideDialogOnce = true; } } }; getWindow().requestFeature(Window.FEATURE_PROGRESS); webview.setWebChromeClient(webChromeClient); webview.setWebViewClient(webViewClient); setContentView(webview); /** Load the Keynote Browser Settings */ LoadSettings(); webview.loadUrl(LandingPage); } /** Get Menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } /** an item gets pushed */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // We have only one menu option case R.id.quit: System.exit(0); break; case R.id.back: webview.goBack(); case R.id.refresh: webview.reload(); case R.id.info: //IncludeJavascript(""); } return true; } /** Begin Globals */ public WebView webview; public WebChromeClient webChromeClient; public WebViewClient webViewClient; public ProgressDialog loadingDialog; public Boolean HideDialogOnce; public Activity myProcess; public String OverideUserAgent_IE = "Mozilla/5.0 (Windows; MSIE 6.0; Android 1.6; en-US) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2 myKMB/1.0"; public String LandingPage = "http://kscserver.com/main-leap-slim.html"; public String MessageBegText = "Problem making a connection, Details: "; public String MessageEndText = " For Support Call: (xxx) xxx - xxxx."; public void LoadSettings() { webview.getSettings().setUserAgentString(OverideUserAgent_IE); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setBuiltInZoomControls(true); webview.getSettings().setSupportZoom(true); } /** Creates a message alert dialog */ public void CreateMessage(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message) .setCancelable(true) .setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } } My Application is running in the background, and as you can see no Firebug in the lower right hand corner. However the browser (the emulator on top) has the same page but shows the firebug. What am I doing wrong? I'm assuming its either not enough memory allocated to the application, process power allocation, or a physical memory thing. I can't tell, all I know is the results are strange. I get the same thing form my android device, the application shows no firebug but the browser shows the firebug.

    Read the article

  • Android GPS timeout

    - by Scott Saunders
    I'm writing an Android application that, among other things, needs to send the current GPS coordinates to a server when the user tells it to. From a context menu, I run the service below. The service is a LocationListener and requests updates from the LocationManager. When it gets a location (onLocationChanged()), it removes itself as a listener and sends the coordinates off to the server. All of this is working. However, if GPS coordinates are not quickly available, my service just keeps running until it gets some. It holds up the UI with a progress dialog, which is annoying. Worse, if the user has moved since starting the service, the first GPS coordinates might be wrong and the app will send bad data to the server. I need a timeout on the service. Is there a good way to do that? I'm not very experienced with threads. I think I can run a Runnable in the onStartCommand() method that will somehow count down 30 seconds and then, if there is no GPS result yet, call my service's stop() method. Does that sound like the best way to do this? Alternatively, is it possible to tell if the GPS cannot get a fix? How would I go about doing that? Edit: To further clarify, I'm looking for the best way to "give up" on getting a Location after some amount of time. public class AddCurrentLocation extends Service implements LocationListener { Application app; LocationManager mLocManager; ProgressDialog mDialog; @Override public int onStartCommand(Intent intent, int arg0, int arg1) { app = getApplication(); // show progress dialog if (app.getScreen() != null) { mDialog = ProgressDialog.show(app.getScreen(), "", "Adding Location. Please wait...", true); } // find GPS service and start listening Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String bestProvider = mLocManager.getBestProvider(criteria, true); mLocManager.requestLocationUpdates(bestProvider, 2000, 0, this); return START_NOT_STICKY; } private void stop() { mLocManager.removeUpdates(this); if (mDialog != null) { mDialog.dismiss(); } stopSelf(); } @Override public void onLocationChanged(Location location) { // done with GPS stop listening mLocManager.removeUpdates(this); sendLocation(location); // method to send info to server stop(); } // other required methods and sendLocation() ... }

    Read the article

  • Android: Memory leak due to AsyncTask

    - by Manu
    Hello, I'm stuck with a memory leak that I cannot fix. I identified where it occurs, using the MemoryAnalizer but I vainly struggle to get rid of it. Here is the code: public class MyActivity extends Activity implements SurfaceHolder.Callback { ... Camera.PictureCallback mPictureCallbackJpeg = new Camera.PictureCallback() { public void onPictureTaken(byte[] data, Camera c) { try { // log the action Log.e(getClass().getSimpleName(), "PICTURE CALLBACK JPEG: data.length = " + data); // Show the ProgressDialog on this thread pd = ProgressDialog.show(MyActivity.this, "", "Préparation", true, false); // Start a new thread that will manage the capture new ManageCaptureTask().execute(data, c); } catch(Exception e){ AlertDialog.Builder dialog = new AlertDialog.Builder(MyActivity.this); ... dialog.create().show(); } } class ManageCaptureTask extends AsyncTask<Object, Void, Boolean> { protected Boolean doInBackground(Object... args) { Boolean isSuccess = false; // initialize the bitmap before the capture ((myApp) getApplication()).setBitmapX(null); try{ // Check if it is a real device or an emulator TelephonyManager telmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String deviceID = telmgr.getDeviceId(); boolean isEmulator = "000000000000000".equalsIgnoreCase(deviceID); // get the bitmap if (isEmulator) { ((myApp) getApplication()).setBitmapX(BitmapFactory.decodeFile(imageFileName)); } else { ((myApp) getApplication()).setBitmapX(BitmapFactory.decodeByteArray((byte[]) args[0], 0, ((byte[])args[0]).length)); } ((myApp) getApplication()).setImageForDB(ImageTools.resizeBmp(((myApp) getApplication()).getBmp())); // convert the bitmap into a grayscale image and display it in the preview ((myApp) getApplication()).setImage(makeGrayScale()); isSuccess = true; } catch (Exception connEx){ errorMessageFromBkgndThread = getString(R.string.errcapture); } return isSuccess; } protected void onPostExecute(Boolean result) { // Pass the result data back to the main activity if (MyActivity.this.pd != null) { MyActivity.this.pd.dismiss(); } if (result){ ((ImageView) findViewById(R.id.apercu)).setImageBitmap(((myApp) getApplication()).getBmp()); ((myApp) getApplication()).setBitmapX(null); } else{ // there was an error ErrAlert(); } } } }; private void ErrAlert(){ // notify the user about the error AlertDialog.Builder dialog = new AlertDialog.Builder(this); ... dialog.create().show(); } } MemoryAnalyzer indicated the memory leak at: ((myApp) getApplication()).setBitmapX(BitmapFactory.decodeByteArray((byte[]) args[0], 0, ((byte[])args[0]).length)); I am grateful for any suggestion, thank you in advance.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >