I need your help, there is an Fatal Error in my code. I don't know how to solve this problem... please help me out :)
my code
public class MainActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "https://example.pdf";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private SSLContext context;
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
This line is the error in: URL url = new URL(f_url[0]);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
// Load the truststore that includes self-signed cert as a "trusted" entry.
KeyStore truststore;
truststore = KeyStore.getInstance("BKS");
InputStream in = getActivity().getResources().openRawResource(R.raw.mykeystore);
truststore.load(in, "mysecret".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(truststore);
// Create custom SSL context that incorporates that truststore
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
private ContextWrapper getActivity() {
// TODO Auto-generated method stub
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
and this is my Logcat :
03-21 16:36:26.747: E/AndroidRuntime(5751): FATAL EXCEPTION: AsyncTask #1
03-21 16:36:26.747: E/AndroidRuntime(5751): Process: com.example.test2, PID: 5751
03-21 16:36:26.747: E/AndroidRuntime(5751): java.lang.RuntimeException: An error occured while executing doInBackground()
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.lang.Thread.run(Thread.java:841)
03-21 16:36:26.747: E/AndroidRuntime(5751): Caused by: java.lang.NullPointerException: println needs a message
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.util.Log.println_native(Native Method)
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.util.Log.e(Log.java:232)
03-21 16:36:26.747: E/AndroidRuntime(5751): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:194)
03-21 16:36:26.747: E/AndroidRuntime(5751): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:1)
03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-21 16:36:26.747: E/AndroidRuntime(5751): ... 4 more
Stacktrace output
03-21 18:39:45.957: W/System.err(2061): java.lang.NullPointerException
03-21 18:39:45.967: W/System.err(2061): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:147)
03-21 18:39:45.967: W/System.err(2061): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:1)
03-21 18:39:45.967: W/System.err(2061): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-21 18:39:45.967: W/System.err(2061): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-21 18:39:45.967: W/System.err(2061): at java.lang.Thread.run(Thread.java:841)
Try
Log.e("Error:", " " + e.getMessage());
Instead of Log.e("Error: ", e.getMessage());
// e.getMessage() could be null or empty.
Also add catch(MalformedURLException e) {} and see why the url exception is thrown
Make your AsyncTask extend AsyncTask<String, Void, String>.
Related
I got this error whenever I change my URL to my online hosting, but if I change to 10.0.2.2 everything seems fine and running.
LogCat
02-01 23:02:18.302 17643-18052/com.example.jithea.testlogin E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0x40d8d9a8)
02-01 23:02:18.303 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: uncaught exception occurred
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ java.lang.RuntimeException: An error occured while executing doInBackground()
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-01 23:02:18.304 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-01 23:02:18.305 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ Caused by: java.lang.NullPointerException
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
02-01 23:02:18.306 17643-18052/com.example.jithea.testlogin W/System.err﹕ at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/System.err﹕ ... 4 more
02-01 23:02:18.307 17643-18052/com.example.jithea.testlogin W/dalvikvm﹕ threadid=12: calling UncaughtExceptionHandler
02-01 23:02:18.315 17643-18052/com.example.jithea.testlogin E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:132)
at com.example.jithea.testlogin.NewsActivity$LoadAllProducts.doInBackground(NewsActivity.java:107)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
02-01 23:02:18.371 17643-17659/com.example.jithea.testlogin I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x528dc150) fps:43.08, dur:1044.57, max:73.51, min:6.02
And here's my NewsActivity.java
public class NewsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParserNews jParser = new JSONParserNews();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://agustiniancampusevents.site40.net/newsDB/get_all_news.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_PID = "pid";
private static final String TAG_NEWSTITLE = "newstitle";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_NEWS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String newstitle = c.getString(TAG_NEWSTITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NEWSTITLE, newstitle);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
ViewNewsActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
NewsActivity.this, productsList,
R.layout.news_list_item, new String[]{TAG_PID,
TAG_NEWSTITLE},
new int[]{R.id.pid, R.id.newstitle});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}
I am trying to create an app using text to speech. Whenever I move from activity Text_entry to activity CombChange and back i receive these service connection leaked errors in the log cat (below).
Can anyone see why?
I have only pasted the relevant bits of the Text_Entry and CombChange classes - so there may be missing declarations and curly brackets etc.
public class Text_entry extends Activity implements OnTouchListener, TextToSpeech.OnInitListener{
speech = new Speech(this);
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
Intent intent2 = new Intent(this, CombChange.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent2.putExtra("newPat", enteredNumber);
startActivity(intent2);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
String hc =" ";
hc = intent.getExtras().getString("helpComb");
if (hc.equals("true"))
helpComb = true;
else
helpComb = false;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
speech = new Speech(this);
}
else {
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
.
public class CombChange extends ListActivity {
speech = new Speech(this);
speech.changeText("enter the new combination");
speech.speaks();
SystemClock.sleep(1300);
Intent intent = new Intent(this, Text_entry.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("helpComb", "true");
speech.cleanUp();
startActivity(intent);
}
.
public class Speech implements TextToSpeech.OnInitListener {
private String toRead;
private TextToSpeech tts;
public Speech(Context c) {
tts = new TextToSpeech(c, this);
tts.setPitch(1.2f);
tts.setSpeechRate(1.5f);
}
public void speaks()
{
speakOut();
}
public void changeText(String changeTo)
{
toRead = changeTo;
}
public void cleanUp() {
//Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
protected void onStop()
{
if(tts != null){
tts.shutdown();
}
}
private void speakOut() {
tts.speak(toRead, TextToSpeech.QUEUE_FLUSH, null);
}
}
.
03-21 16:42:32.515: I/TextToSpeech(24023): Sucessfully bound to com.google.android.tts
03-21 16:42:32.535: E/ActivityThread(24023): Activity org.BT.Text_entry has leaked ServiceConnection android.speech.tts.TextToSpeech$Connection#427fd290 that was originally bound here
03-21 16:42:32.535: E/ActivityThread(24023): android.app.ServiceConnectionLeaked: Activity org.BT.Text_entry has leaked ServiceConnection android.speech.tts.TextToSpeech$Connection#427fd290 that was originally bound here
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:965)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:859)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.ContextImpl.bindService(ContextImpl.java:1344)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.ContextImpl.bindService(ContextImpl.java:1336)
03-21 16:42:32.535: E/ActivityThread(24023): at android.content.ContextWrapper.bindService(ContextWrapper.java:401)
03-21 16:42:32.535: E/ActivityThread(24023): at android.speech.tts.TextToSpeech.connectToEngine(TextToSpeech.java:627)
03-21 16:42:32.535: E/ActivityThread(24023): at android.speech.tts.TextToSpeech.initTts(TextToSpeech.java:597)
03-21 16:42:32.535: E/ActivityThread(24023): at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:553)
03-21 16:42:32.535: E/ActivityThread(24023): at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:527)
03-21 16:42:32.535: E/ActivityThread(24023): at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:512)
03-21 16:42:32.535: E/ActivityThread(24023): at org.BT.Speech.<init>(Speech.java:14)
03-21 16:42:32.535: E/ActivityThread(24023): at org.BT.Text_entry.onCreate(Text_entry.java:97)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.Activity.performCreate(Activity.java:5184)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.ActivityThread.access$600(ActivityThread.java:140)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
03-21 16:42:32.535: E/ActivityThread(24023): at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 16:42:32.535: E/ActivityThread(24023): at android.os.Looper.loop(Looper.java:137)
03-21 16:42:32.535: E/ActivityThread(24023): at android.app.ActivityThread.main(ActivityThread.java:4898)
03-21 16:42:32.535: E/ActivityThread(24023): at java.lang.reflect.Method.invokeNative(Native Method)
03-21 16:42:32.535: E/ActivityThread(24023): at java.lang.reflect.Method.invoke(Method.java:511)
03-21 16:42:32.535: E/ActivityThread(24023): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
03-21 16:42:32.535: E/ActivityThread(24023): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
03-21 16:42:32.535: E/ActivityThread(24023): at dalvik.system.NativeStart.main(Native Method)
03-21 16:42:32.670: I/TextToSpeech(24023): Sucessfully bound to com.google.android.tts
03-21 16:42:32.670: D/(24023): 3333333333333333333333333333333333333333333333333
03-21 16:42:32.670: E/SpannableStringBuilder(24023): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-21 16:42:32.670: E/SpannableStringBuilder(24023): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-21 16:42:32.775: I/TextToSpeech(24023): Connected to TTS Service
03-21 16:42:32.780: I/TextToSpeech(24023): Connected to TTS Service
I believe this can solve your problem, however I cannot explain it in terms of your code - maybe someone else on here can
http://www.stevenmarkford.com/android-activity-has-leaked-serviceconnection-that-was-originally-bound-here/
I am not sure how much this will help but Please try to implement onPause() method in Activity class. And unbind your service explicitly.
For ex:
#Override
protected void onPause() {
super.onPause();
CalculatorUser c=new CalculatorUser(); //your Activity name object
c.unbindService((ServiceConnection) this);
}
Unbinding might solve your issue and "Activity 'APP' has leaked ServiceConnection" happens mostly when you move out of your Activity So you need to explicitly tell to Android OS to please unbind me from services my Activity is using as of now. When again you will launch you App it will bind to service. If its not helpful sent me code i will try to fix it for you.
ACTUAL ANSWER TO THIS PROBLEM:
You need to call destroy() on your TextToSpeech object when the service is destroyed.
I had this problem and saw your question so I thought I would answer it for anyone else who comes here.
For me works to shutdown the TextToSpeech object.
#Override
protected void onDestroy() {
tts.shutdown();
super.onDestroy();
}
I am creating an RSS reader application for android 4.0+. I have put the reader code in AsyncTask because of the NetworkOnMainThreadException. The code almost works fine, however one line has an error. This is my code:
Java code:
private class PostTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url=params[0];
headlines = new ArrayList();
links = new ArrayList();
//Download and parse xml feed
headlines = new ArrayList();
links = new ArrayList();
try {
URL url1 = new URL("http://feeds.pcworld.com/pcworld/latestnews");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url1), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
* As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
* so we should skip the "<title>" tag which is a child of "<channel>" tag,
* and take in consideration only "<title>" tag which is a child of "<item>"
*
* In order to achieve this, we will make use of a boolean variable.
*/
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Feed parsed!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
}
in this code snippet i get an error:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
Error: The constructor ArrayAdapter(MainActivity.PostTask, int, List) is undefined.
Logcat:
01-26 20:55:53.811: E/AndroidRuntime(1830): FATAL EXCEPTION: AsyncTask #1
01-26 20:55:53.811: E/AndroidRuntime(1830): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.lang.Thread.run(Thread.java:856)
01-26 20:55:53.811: E/AndroidRuntime(1830): Caused by: java.lang.IllegalArgumentException
01-26 20:55:53.811: E/AndroidRuntime(1830): at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1615)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:343)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:1)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-26 20:55:53.811: E/AndroidRuntime(1830): ... 5 more
Could anyone please look into my problem and come up with a solution? Or tell me if i should do anything different? Thanks a lot!
Change it to:
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, headlines);
this refers to the AsyncTask, so you have to explicitly reference MainActivity's this.
use Activity Context instead of AsyncTask to Create ArrayAdapter inside onPostExecute method as :
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(Your_Current_Activity.this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
EDIT :
after log posted also change
xpp.setInput(getInputStream(url1), "UTF_8");
to
xpp.setInput(url1.openConnection().getInputStream(), "UTF_8");
I'm trying to develop an autocomplete location for goofle map. But, I have encountered some errors while developing. I do not know what is the cause of the error.
Below is my code.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ArrayAdapter<String> adapter;
AutoCompleteTextView textView;
Object[] arg0 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, R.layout.item_list);
textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (count % 3 == 1) {
adapter.clear();
// GetPlaces task = new GetPlaces();
// now pass the argument in the textview to the task
new GetPlaces().execute(textView.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args) {
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try {
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+ URLEncoder.encode(arg0[0].toString(), "UTF-8")
+ "&types=geocode&language=en&sensor=true&key=<API-key here>");
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
// take Google's legible JSON and turn it into one big
// string.
while ((line = in.readLine()) != null) {
sb.append(line);
}
// turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
// now get the JSON array that's inside that object
JSONArray ja = new JSONArray(
predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
// add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
// then our post
#Override
protected void onPostExecute(ArrayList<String> result) {
Log.d("YourApp", "onPostExecute : " + result.size());
// update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.item_list);
adapter.setNotifyOnChange(true);
// attach the adapter to textview
textView.setAdapter(adapter);
for (String string : result) {
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp",
"onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
Here is the logcat error:
10-24 15:10:54.609: E/AndroidRuntime(14346): FATAL EXCEPTION: AsyncTask #1
10-24 15:10:54.609: E/AndroidRuntime(14346): java.lang.RuntimeException: An error occured while executing doInBackground()
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$3.done(AsyncTask.java:278)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.lang.Thread.run(Thread.java:856)
10-24 15:10:54.609: E/AndroidRuntime(14346): Caused by: java.lang.NullPointerException
10-24 15:10:54.609: E/AndroidRuntime(14346): at com.test.main.MainActivity$GetPlaces.doInBackground(MainActivity.java:76)
10-24 15:10:54.609: E/AndroidRuntime(14346): at com.test.main.MainActivity$GetPlaces.doInBackground(MainActivity.java:1)
10-24 15:10:54.609: E/AndroidRuntime(14346): at android.os.AsyncTask$2.call(AsyncTask.java:264)
10-24 15:10:54.609: E/AndroidRuntime(14346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
The source of the error is obviously in MainActivity line 76, where you are accessing a null object
in 76th line..
use "URLEncoder.encode(args[0].toString()" instead of "URLEncoder.encode(arg0[0].toString()"