Android Volley - Getting No Response using StringRequest to XML API - java

I get no response when request string to XML API. Here's the code :
String url = "http://www.w3schools.com/xml/note.xml"
String url2 = "http://api.json.request"
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String _response) {
Log.d("json=>",_response);
res = _response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Error handling
Log.d("jsone=>", error.toString());
}
});
queue.add(stringRequest);
i have tested it using Google API (url2), but it's fine. Maybe Android Volley run too slow when try to get response, but seeing log i didnt get it at all.
The Log when initiate request :
01-28 10:57:05.253 21424-21424/com.merahjambutech.zuki.deteksi I/Timeline: Timeline: Activity_launch_request time:26387334
01-28 10:57:05.353 21424-21424/com.merahjambutech.zuki.deteksi D/pre=: 0
01-28 10:57:05.433 21424-21424/com.merahjambutech.zuki.deteksi W/ImageLoader: Try to initialize ImageLoader which had already been initialized before. To re-init ImageLoader with new configuration call ImageLoader.destroy() at first.
01-28 10:57:05.463 21424-21470/com.merahjambutech.zuki.deteksi D/dalvikvm: GC_FOR_ALLOC freed 503K, 11% free 24699K/27632K, paused 29ms, total 29ms
01-28 10:57:05.483 21424-21470/com.merahjambutech.zuki.deteksi I/dalvikvm-heap: Grow heap (frag case) to 29.898MB for 3686416-byte allocation
01-28 10:57:05.543 21424-21424/com.merahjambutech.zuki.deteksi W/ImageLoader: Try to initialize ImageLoader which had already been initialized before. To re-init ImageLoader with new configuration call ImageLoader.destroy() at first.
01-28 10:57:05.573 21424-21547/com.merahjambutech.zuki.deteksi D/dalvikvm: GC_FOR_ALLOC freed 173K, 10% free 28324K/31236K, paused 15ms, total 15ms
01-28 10:57:05.573 21424-21547/com.merahjambutech.zuki.deteksi I/dalvikvm-heap: Grow heap (frag case) to 33.438MB for 3686416-byte allocation </note>
01-28 10:57:05.643 21424-21424/com.merahjambutech.zuki.deteksi I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#42485428 time:26387720

please ensure that you add permission in manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Related

TextToSpeech android API 22 not playing audio

I am using text to speech engine in my App. It works fine on emulator Nexus 6 with API 23 and higher. But on emulator Nexus 6 with API 22 it does not speak.
Both emulators use Pico TTS as preferred engine.
My activity layout contains only one button "Speak".
This is my activity code:
public class MainActivity extends AppCompatActivity {
private TextToSpeech mTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakBtn = findViewById(R.id.button);
speakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
}
});
mTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTTS.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
mTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.d("TTS", "onStart called, utteranceId = " + utteranceId);
}
#Override
public void onDone(String utteranceId) {
Log.d("TTS", "onDone called, utteranceId = " + utteranceId);
}
#Override
public void onError(String utteranceId) {
Log.d("TTS", "onError called, utteranceId = " + utteranceId);
}
});
} else {
Log.e("TTS", "Initialization failed");
}
}
});
}
private void speak() {
Log.d("TTS", "speak() method called");
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "greeting");
mTTS.speak("hello", TextToSpeech.QUEUE_FLUSH, map);
}
}
This is all logs from emulator Nexus 6 API 22:
02-18 13:54:09.942 9739-9739/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
02-18 13:54:09.943 9739-9739/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
02-18 13:54:09.943 9739-9739/? I/art: Not late-enabling -Xcheck:jni (already on)
02-18 13:54:09.961 9739-9748/? E/art: Failed sending reply to debugger: Broken pipe
02-18 13:54:09.961 9739-9748/? I/art: Debugger is no longer active
02-18 13:54:09.992 9739-9739/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
02-18 13:54:10.001 9739-9739/? I/art: Rejecting re-init on previously-failed class java.lang.Class
02-18 13:54:10.001 9739-9739/? I/art: Rejecting re-init on previously-failed class java.lang.Class
02-18 13:54:10.064 9739-9739/? I/TextToSpeech: Sucessfully bound to com.svox.pico
02-18 13:54:10.072 9739-9757/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-18 13:54:10.074 9739-9739/? D/Atlas: Validating map...
02-18 13:54:10.093 9739-9739/? I/TextToSpeech: Connected to ComponentInfo{com.svox.pico/com.svox.pico.PicoService}
02-18 13:54:10.096 9739-9758/? I/TextToSpeech: Set up connection to ComponentInfo{com.svox.pico/com.svox.pico.PicoService}
02-18 13:54:10.111 9739-9757/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-18 13:54:10.111 9739-9757/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
02-18 13:54:10.128 9739-9757/? D/EGL_emulation: eglCreateContext: 0xae434e20: maj 2 min 0 rcv 2
02-18 13:54:10.131 9739-9757/? D/EGL_emulation: eglMakeCurrent: 0xae434e20: ver 2 0
02-18 13:54:10.134 9739-9757/? D/OpenGLRenderer: Enabling debug mode 0
02-18 13:54:10.174 9739-9757/? D/EGL_emulation: eglMakeCurrent: 0xae434e20: ver 2 0
02-19 09:32:25.570 9739-9739/com.example.ttsapp D/TTS: speak() method called
Figured out how to solve the problem. Everything works if launch the emulator not via Debugging or Execution but from AVD Manager after starting Android Studio.

Activity is completely blank when ran - maybe as a result of internet permissions?

I'm fairly new to java/android development so please bear with me.
I've created an app as part of a online course that should supposedly run a "Guess the celebrity game".
The issue is when i run my code the main activity is completely blank.
The strange part is that the app presented in the course runs without issue and i have followed the code word for word. I have managed to find one other candidate who has the same issue and cannot solve it.
There are no errors (that i can find) in the logs and i can't seem to find any posts with a similar issue.
This weird behaviour only occours when i add the following permission in the manifest xml:
<uses-permission android:name="android.permission.INTERNET" />
Screenshot of emulator (also tested on real device):
https://s9.postimg.org/su0gc58gf/Capture.png/
Code from MainActivity:
public class MainActivity extends Activity {
ArrayList<String> celebURLs = new ArrayList<String>();
ArrayList<String> celebNames = new ArrayList<String>();
int chosenCeleb = 0;
int locationOfCorrectAnswer = 0;
String[] answers = new String[4];
ImageView imageView;
Button button0;
Button button1;
Button button2;
Button button3;
public void celebChosen(View view) {
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))) {
Toast.makeText(getApplicationContext(), "Correct!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Wrong! It was " + celebNames.get(chosenCeleb), Toast.LENGTH_LONG).show();
}
createNewQuestion();
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button0 = (Button) findViewById(R.id.button1);
button1 = (Button) findViewById(R.id.button2);
button2 = (Button) findViewById(R.id.button3);
button3 = (Button) findViewById(R.id.button4);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.posh24.com/celebrities").get();
String[] splitResult = result.split("<div class=\"sidebarContainer\">");
Pattern p = Pattern.compile("<img src=\"(.*?)\"");
Matcher m = p.matcher(splitResult[0]);
while (m.find()) {
celebURLs.add(m.group(1));
}
p = Pattern.compile("alt=\"(.*?)\"");
m = p.matcher(splitResult[0]);
while (m.find()) {
celebNames.add(m.group(1));
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
createNewQuestion();
}
public void createNewQuestion() {
Random random = new Random();
chosenCeleb = random.nextInt(celebURLs.size());
ImageDownloader imageTask = new ImageDownloader();
Bitmap celebImage;
try {
celebImage = imageTask.execute(celebURLs.get(chosenCeleb)).get();
imageView.setImageBitmap(celebImage);
locationOfCorrectAnswer = random.nextInt(4);
int incorrectAnswerLocation;
for (int i = 0; i < 4; i++) {
if (i == locationOfCorrectAnswer) {
answers[i] = celebNames.get(chosenCeleb);
} else {
incorrectAnswerLocation = random.nextInt(celebURLs.size());
while (incorrectAnswerLocation == chosenCeleb) {
incorrectAnswerLocation = random.nextInt(celebURLs.size());
}
answers[i] = celebNames.get(incorrectAnswerLocation);
}
}
button0.setText(answers[0]);
button1.setText(answers[1]);
button2.setText(answers[2]);
button3.setText(answers[3]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Logs:
08-21 20:47:46.778 835-835/? I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread.
08-21 20:47:49.283 421-519/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
--------- beginning of system
08-21 20:47:49.335 421-434/? I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.shenstone.guessthecelebrity2/.MainActivity (has extras)} from uid 10007 on display 0
08-21 20:47:49.614 421-433/? I/art: Background sticky concurrent mark sweep GC freed 10530(678KB) AllocSpace objects, 3(608KB) LOS objects, 12% free, 9MB/10MB, paused 4.358ms total 263.235ms
08-21 20:47:49.854 69-69/? I/art: Background concurrent mark sweep GC freed 794(33KB) AllocSpace objects, 0(0B) LOS objects, 90% free, 111KB/1135KB, paused 12.562ms total 112.418ms
08-21 20:47:49.945 421-1030/? I/ActivityManager: Start proc com.example.shenstone.guessthecelebrity2 for activity com.example.shenstone.guessthecelebrity2/.MainActivity: pid=3562 uid=10055 gids={50055, 9997, 3003} abi=armeabi-v7a
08-21 20:47:49.982 3562-3562/? I/art: Not late-enabling -Xcheck:jni (already on)
08-21 20:47:52.244 3562-3574/? W/art: Suspending all threads took: 12.799ms
08-21 20:47:52.262 3562-3574/? I/art: Background partial concurrent mark sweep GC freed 322(512KB) AllocSpace objects, 0(0B) LOS objects, 64% free, 555KB/1579KB, paused 14.923ms total 43.870ms
08-21 20:47:52.395 3562-3574/? I/art: Background sticky concurrent mark sweep GC freed 219(436KB) AllocSpace objects, 0(0B) LOS objects, 28% free, 1129KB/1579KB, paused 9.677ms total 22.436ms
08-21 20:47:52.534 3562-3574/? I/art: WaitForGcToComplete blocked for 10.763ms for cause Background
08-21 20:47:53.258 3562-3574/? I/art: Background sticky concurrent mark sweep GC freed 469(1634KB) AllocSpace objects, 0(0B) LOS objects, 58% free, 660KB/1599KB, paused 6.830ms total 31.639ms
08-21 20:47:56.495 3562-3573/? I/art: WaitForGcToComplete blocked for 21.032ms for cause HeapTrim
08-21 20:47:59.381 421-443/? W/ActivityManager: Launch timeout has expired, giving up wake lock!
08-21 20:48:00.154 3562-3574/? W/art: Suspending all threads took: 39.137ms
08-21 20:48:00.183 3562-3574/? I/art: Background partial concurrent mark sweep GC freed 108(3KB) AllocSpace objects, 57(862KB) LOS objects, 60% free, 663KB/1687KB, paused 41.100ms total 174.221ms
08-21 20:48:00.244 3562-3574/? W/art: Suspending all threads took: 10.311ms
08-21 20:48:00.255 3562-3574/? I/art: Background sticky concurrent mark sweep GC freed 53(1872B) AllocSpace objects, 30(451KB) LOS objects, 56% free, 728KB/1687KB, paused 12.216ms total 26.132ms
08-21 20:48:00.354 3562-3574/? W/art: Suspending all threads took: 9.038ms
08-21 20:48:00.415 3562-3574/? I/art: Background partial concurrent mark sweep GC freed 135(4KB) AllocSpace objects, 81(1221KB) LOS objects, 48% free, 1094KB/2MB, paused 12.238ms total 111.401ms
Any help would be much appreciated, thanks!
You are using the AsyncTask but did not started it. Use execute() method to start your async task.

Back button, jsoup and AsyncTask

Help me, please, I have already searched the whole Internet. Why pressing on Back button close the program, not get on previous page? I think, the reason - there is no history for webview.canGoBack(), but i can't understand, why.. Sorry, if it's stupid question, I'm newbie in programming.
public class MainActivity extends Activity {
WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webView1);
new ParseMyPageTask()
.execute("https://mysite.com/forumdisplay.php?f=36&styleid=35");
webview.setWebViewClient(new ForumWebViewClient());
}
class ParseMyPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Document doc = null;
String htmltext = "";
try {
doc = Jsoup.connect(params[0]).get();
Elements body = doc.select("ul.forumbits, ul#stickies, ul#threads, ol#posts");
htmltext = body.html();
} catch (IOException e) {
e.printStackTrace();
}
return htmltext;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
webview.getSettings().setUseWideViewPort(true);
webview.setInitialScale(0);
webview.loadDataWithBaseURL(null, "result", "text/html", "UTF-8", null);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class ForumWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
new ParseMyPageTask().execute("https://mysite.com/" + url + "&styleid=35");
return true;
}
}
}
I think it is because of somewhere here:
private class ForumWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
new ParseMyPageTask().execute("https://mysite.com/" + url + "&styleid=35");
return true;
}
}
Result of
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
if (isDebug) {
Log.v(TAG, "BackButton canGoBack. " + event);
}
webview.goBack();
return true;
}
if (isDebug) {
Log.v(TAG, "BackButton pressed. " + event);
}
return super.onKeyDown(keyCode, event);
}
is
07-29 21:20:42.711: I/webclipboard(9044): clipservice: android.sec.clipboard.ClipboardExManager#421e3cf0
07-29 21:20:42.806: E/webview(9044): registerForStylusPenEvent onAttachedToWindow
07-29 21:20:42.806: E/webview(9044): registerForStylusPenEvent START
07-29 21:20:42.826: E/webview(9044): registerForStylusPenEvent END
07-29 21:20:43.301: D/libEGL(9044): loaded /system/lib/egl/libEGL_mali.so
07-29 21:20:43.351: D/libEGL(9044): loaded /system/lib/egl/libGLESv1_CM_mali.so
07-29 21:20:43.356: D/libEGL(9044): loaded /system/lib/egl/libGLESv2_mali.so
07-29 21:20:43.366: D/(9044): Device driver API match
07-29 21:20:43.366: D/(9044): Device driver API version: 10
07-29 21:20:43.366: D/(9044): User space API version: 10
07-29 21:20:43.366: D/(9044): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Thu Oct 25 08:43:05 KST 2012
07-29 21:20:43.461: D/OpenGLRenderer(9044): Enabling debug mode 0
07-29 21:20:43.481: D/WebView(9044): onSizeChanged - w:800 h:1196
07-29 21:20:43.501: I/Choreographer(9044): Skipped 39 frames! The application may be doing too much work on its main thread.
07-29 21:20:43.781: V/webkit(9044): BrowserFrame constructor: this=Handler (android.webkit.BrowserFrame) {421dddc8}
07-29 21:20:43.796: D/dalvikvm(9044): GC_CONCURRENT freed 258K, 7% free 12340K/13191K, paused 111ms+70ms, total 272ms
07-29 21:20:44.106: D/TilesManager(9044): new EGLContext from framework: 5a920fb8
07-29 21:20:44.106: D/GLWebViewState(9044): Reinit shader
07-29 21:20:44.191: D/GLWebViewState(9044): Reinit transferQueue
07-29 21:20:45.421: D/dalvikvm(9044): GC_CONCURRENT freed 267K, 7% free 12529K/13447K, paused 11ms+1ms, total 28ms
07-29 21:20:45.661: D/dalvikvm(9044): GC_CONCURRENT freed 455K, 9% free 12532K/13639K, paused 12ms+12ms, total 42ms
07-29 21:20:45.856: D/dalvikvm(9044): GC_CONCURRENT freed 112K, 7% free 12803K/13639K, paused 11ms+2ms, total 30ms
07-29 21:20:45.946: I/dalvikvm(9044): Total arena pages for JIT: 11
07-29 21:20:45.966: D/dalvikvm(9044): GC_CONCURRENT freed 361K, 7% free 12938K/13895K, paused 2ms+9ms, total 33ms
07-29 21:20:46.846: I/GATE(9044): <GATE-M>DEV_ACTION_COMPLETED</GATE-M>
07-29 21:20:49.821: V/WebViewInputDispatcher(9044): blockWebkitDraw
07-29 21:20:49.821: V/WebViewInputDispatcher(9044): blockWebkitDraw lockedfalse
07-29 21:20:49.826: V/webview(9044): singleCursorHandlerTouchEvent -getEditableSupport FASLE
07-29 21:20:50.126: D/webview(9044): blockWebkitViewMessage= false
07-29 21:20:50.146: D/WebCore(9044): uiOverrideUrlLoading: shouldOverrideUrlLoading() returnstrue
07-29 21:20:51.591: D/dalvikvm(9044): GC_CONCURRENT freed 535K, 9% free 12840K/13959K, paused 14ms+2ms, total 35ms
07-29 21:20:51.616: D/dalvikvm(9044): GC_FOR_ALLOC freed 40K, 8% free 12850K/13959K, paused 15ms, total 15ms
07-29 21:20:51.616: I/dalvikvm-heap(9044): Grow heap (frag case) to 13.208MB for 131088-byte allocation
07-29 21:20:51.631: D/dalvikvm(9044): GC_FOR_ALLOC freed 0K, 9% free 12978K/14151K, paused 15ms, total 15ms
07-29 21:20:51.646: D/dalvikvm(9044): GC_FOR_ALLOC freed 0K, 9% free 12978K/14151K, paused 14ms, total 14ms
07-29 21:20:51.646: I/dalvikvm-heap(9044): Grow heap (frag case) to 13.333MB for 131088-byte allocation
07-29 21:20:51.661: D/dalvikvm(9044): GC_FOR_ALLOC freed 0K, 9% free 13106K/14343K, paused 15ms, total 15ms
07-29 21:20:51.681: D/dalvikvm(9044): GC_FOR_ALLOC freed 411K, 10% free 12969K/14343K, paused 15ms, total 15ms
07-29 21:20:51.701: I/dalvikvm(9044): Total arena pages for JIT: 12
07-29 21:20:51.761: D/dalvikvm(9044): GC_CONCURRENT freed 264K, 9% free 13088K/14343K, paused 12ms+12ms, total 38ms
07-29 21:20:51.856: D/dalvikvm(9044): GC_CONCURRENT freed 284K, 9% free 13187K/14343K, paused 12ms+1ms, total 29ms
07-29 21:20:51.946: D/dalvikvm(9044): GC_CONCURRENT freed 292K, 8% free 13293K/14343K, paused 12ms+12ms, total 41ms
07-29 21:20:52.056: D/dalvikvm(9044): GC_CONCURRENT freed 532K, 8% free 13201K/14343K, paused 12ms+11ms, total 42ms
07-29 21:20:52.116: D/dalvikvm(9044): GC_FOR_ALLOC freed 665K, 10% free 12919K/14343K, paused 15ms, total 15ms
07-29 21:20:52.201: I/GATE(9044): <GATE-M>DEV_ACTION_COMPLETED</GATE-M>
07-29 21:20:54.116: V/myLogs(9044): BackButton pressed. KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_BACK, scanCode=158, metaState=0, flags=0x8, repeatCount=0, eventTime=163583381, downTime=163583381, deviceId=4, source=0x101 }
07-29 21:20:54.596: W/IInputConnectionWrapper(9044): showStatusIcon on inactive InputConnection
07-29 21:20:54.596: E/webview(9044): removeForStylusPenEvent onDetachedFromWindow
07-29 21:20:54.596: E/webview(9044): removeForStylusPenEvent START
07-29 21:20:54.596: E/webview(9044): removeForStylusPenEvent END
Result of following code the same:
#Override
public void onBackPressed(){
if (webview.canGoBack()) {
webview.goBack();
if (isDebug) {
Log.v(TAG, "goBack");
}
return;
}
if (isDebug) {
Log.v(TAG, "onBackPressed");
}
super.onBackPressed();
}
try this,
#override
public void onBackPressed(){
super.onBackPressed();
if ( webview.canGoBack()) {
webview.goBack();
}
}
you can try this one to close the Activty on back press
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}

Lower version app not running in the Higher version in android

I have made my application using android SDK 2.2 version and now when I am running my app on android SDK 4.0.3 it's not running.
I have given the min and the max sdk in the manifest file.
I am new in android and want to run my app for the lower and higher versions both. Can anybody tell me how can I do this. Any help is appreciated.
Code for splash class
package com.Cricket_trivia.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
public class SplashScreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final SplashScreen sPlashScreen = this;
// thread for displaying the SplashScreen
splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
finish();
Intent i = new Intent();
i.setClass(sPlashScreen, K_trivia_cricketActivity.class);
startActivity(i);
stop();
}
}
};
splashTread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized(splashTread){
splashTread.notifyAll();
}
}
return true;
}
}
EDIT: My logcat
06-07 10:24:18.710: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:18.760: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:18.890: D/dalvikvm(1461): GC_FOR_ALLOC freed 45K, 4% free 6541K/6787K, paused 74ms
06-07 10:24:18.900: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.333MB for 921616-byte allocation
06-07 10:24:19.010: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:19.100: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:19.140: D/dalvikvm(1461): GC_CONCURRENT freed <1K, 5% free 7440K/7751K, paused 5ms+5ms
06-07 10:24:19.240: D/dalvikvm(1461): GC_FOR_ALLOC freed 0K, 5% free 7440K/7751K, paused 97ms
06-07 10:24:19.240: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.723MB for 409936-byte allocation
06-07 10:24:19.320: D/dalvikvm(1461): GC_FOR_ALLOC freed 0K, 5% free 7841K/8199K, paused 61ms
06-07 10:24:19.589: D/gralloc_goldfish(1461): Emulator without GPU emulation detected.
06-07 10:24:19.669: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:19.779: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:24.600: W/dalvikvm(1461): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
06-07 10:24:24.600: E/AndroidRuntime(1461): FATAL EXCEPTION: Thread-78
06-07 10:24:24.600: E/AndroidRuntime(1461): java.lang.UnsupportedOperationException
06-07 10:24:24.600: E/AndroidRuntime(1461): at java.lang.Thread.stop(Thread.java:1076)
06-07 10:24:24.600: E/AndroidRuntime(1461): at java.lang.Thread.stop(Thread.java:1063)
06-07 10:24:24.600: E/AndroidRuntime(1461): at com.Cricket_trivia.in.SplashScreen$1.run(SplashScreen.java:40)
06-07 10:24:26.209: D/dalvikvm(1461): GC_FOR_ALLOC freed 1037K, 15% free 7022K/8199K, paused 62ms
06-07 10:24:26.209: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.509MB for 614416-byte allocation
06-07 10:24:26.440: D/dalvikvm(1461): GC_CONCURRENT freed <1K, 8% free 7621K/8199K, paused 4ms+5ms
06-07 10:24:26.610: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:26.640: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
The reason why your app is crashing on 4.0.3 but not 2.2 is most likely because you are performing an expensive operation on the UI thread. Blocking the UI thread is very bad practice... don't do it!! Previous versions of Android (i.e. pre-ICS versions) didn't care when you did this and let your app run as is. In 4.0 and above, however, the OS checks against this and crashes your app if you ever perform a potentially expensive operation on the UI thread (such as a network connection, etc.).
You have provided basically no information on what the problem is in your question, so that's all I can really do to help you out.
Edit:
Does something like this work?
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Intent i = new Intent();
i.setClass(sPlashScreen, K_trivia_cricketActivity.class);
startActivity(i);
}
return true;
}
Don't you threads because it is creating the problem in the higher version. Use the code below to show the splash screen.
package com.Cricket_trivia.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.MotionEvent;
public class SplashScreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
MyCount counter = new MyCount(4000, 4000);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
counter.start();
}
public class MyCount extends CountDownTimer
{
public MyCount(long csecond, long countDownInterval)
{
super(csecond, countDownInterval);
}
#Override
public void onFinish() {
finish();
Intent intent = new Intent();
intent.setClass(SplashScreen.this, K_trivia_cricketActivity.class);
startActivity(intent);
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}
}
I think it will work for you

Android - Large file downloads stop - using async/progressdialog

I have a simple code that is supposed to do one task, when the button is clicked download a file, save it to the SD card, and open it. Everything works except during the download, for larger files, the connection drops and the progress bar hangs - almost always at 20%. I have searched and searched and cannot figure out what to do to keep the connection alive and allow the download to complete. Any ideas how to keep the connection alive so the download completes instead of stalling at 20%?
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DownloadTestActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgressDialog = new ProgressDialog(DownloadTestActivity.this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/file.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.doc");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[8192];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
private void showPdf() {
// TODO Auto-generated method stub
if(mProgressDialog != null){
mProgressDialog.dismiss();
}
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test1.doc");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/msword");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/msword");
startActivity(intent);
}
}
}
Edit with logcat information:
--------- beginning of /dev/log/system
W/InputManagerService( 199): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#4137b898
--------- beginning of /dev/log/main
D/AndroidRuntime(20673):
D/AndroidRuntime(20673): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20673): CheckJNI is OFF
D/AndroidRuntime(20673): Calling main entry com.android.commands.pm.Pm
D/AndroidRuntime(20673): Shutting down VM
D/dalvikvm(20673): GC_CONCURRENT freed 101K, 82% free 467K/2560K, paused 1ms+0ms
D/dalvikvm(20673): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20673): NOTE: attach of thread 'Binder Thread #3' failed
D/AndroidRuntime(20687):
D/AndroidRuntime(20687): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20687): CheckJNI is OFF
D/AndroidRuntime(20687): Calling main entry com.android.commands.am.Am
I/ActivityManager( 199): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.myapp/.Activity} from pid 20687
D/AndroidRuntime(20687): Shutting down VM
D/dalvikvm(20687): GC_CONCURRENT freed 102K, 81% free 489K/2560K, paused 0ms+0ms
D/jdwp (20687): Got wake-up signal, bailing out of select
D/dalvikvm(20687): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20687): NOTE: attach of thread 'Binder Thread #3' failed
D/dalvikvm(20698): Late-enabling CheckJNI
I/ActivityManager( 199): Start proc com.myapp for activity com.myapp/.Activity: pid=20698 uid=10102 gids={1015, 3003}
I/dalvikvm(20698): Turning on JNI app bug workarounds for target SDK version 10...
V/PhoneStatusBar( 271): setLightsOn(true)
D/AudioHardware( 98): AudioHardware pcm playback is going to standby.
D/AudioHardware( 98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager( 199): Displayed com.myapp/.Activity: +197ms
W/InputManagerService( 199): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#4199ed28 (uid=10098 pid=20011)
I/ActivityManager( 199): START {cmp=com.myapp/.Choice} from pid 20698
D/AudioHardware( 98): AudioHardware pcm playback is exiting standby.
D/AudioHardware( 98): openPcmOut_l() mPcmOpenCnt: 0
V/PhoneStatusBar( 271): setLightsOn(true)
I/ActivityManager( 199): Displayed com.myapp/.Choice: +93ms
D/ANDRO_ASYNC(20698): Lenght of file: 736768
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
W/NetworkStats( 199): found non-monotonic values; saving to dropbox
D/dalvikvm( 199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm( 199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
D/AudioHardware( 98): AudioHardware pcm playback is going to standby.
D/AudioHardware( 98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager( 199): Force stopping package com.myapp uid=10102
I/ActivityManager( 199): Killing proc 20698:com.myapp/10102: force stop
W/ActivityManager( 199): Force removing ActivityRecord{41eb1ec0 com.myapp/.Choice}: app died, no saved state
I/InputDispatcher( 199): Dropping event because there is no focused window or focused application.
I/ActivityManager( 199): Force finishing activity ActivityRecord{418450c8 com.myapp/.Activity}
I/InputDispatcher( 199): Dropping event because there is no focused window or focused application.
W/InputDispatcher( 199): channel '417b41f0 com.myapp/com.myapp/.Activity (server)' ~ Consumer closed input channel or an error occurred. events=0x8
E/InputDispatcher( 199): channel '417b41f0 com.myapp/com.myapp.Activity (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 199): Attempted to unregister already unregistered input channel '417b41f0 com.myapp/com.myapp.Activity (server)'
W/WindowManager( 199): Failed looking up window
W/WindowManager( 199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy#41c7ffc8 does not exist
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager( 199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager( 199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager( 199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager( 199): WIN DEATH: null
I/WindowManager( 199): WIN DEATH: Window{4175b280 com.myapp/com.myapp.Choice paused=false}
W/WindowManager( 199): Failed looking up window
W/WindowManager( 199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy#41758028 does not exist
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager( 199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager( 199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager( 199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager( 199): WIN DEATH: null
W/InputManagerService( 199): Got RemoteException sending setActive(false) notification to pid 20698 uid 10102
D/dalvikvm(20011): GC_CONCURRENT freed 460K, 32% free 9468K/13767K, paused 3ms+4ms
D/AudioHardware( 98): AudioHardware pcm playback is exiting standby.
D/AudioHardware( 98): openPcmOut_l() mPcmOpenCnt: 0
I've tried to download your file a few times, looks like download stalls for a few seconds here and there, and it might trigger a timeout in your application. Try to specify timeouts explicitly in range 10-20 seconds.
private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet get = new HttpGet("your url comes here");
protected String[] doInBackground(Void... v) {
HttpParams httpParameters = new BasicHttpParams();
// set the timeout in milliseconds until a connection is established
// the default value is zero, that means the timeout is not used
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// set the default socket timeout (SO_TIMEOUT) in milliseconds
// which is the timeout for waiting for data
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient.setParams(httpParameters);
try {
HttpEntity entity = httpclient.execute( get ).getEntity();
FileOutputStream output = new FileOutputStream(outputFile);
entity.writeTo(output);
output.close();
// return something, maybe?
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return null;
}
What seems to be the problem is that process 199 in your logcat seem to be your activity, but then it shows:
I/ActivityManager( 199): Force stopping package com.viperean.atcassistant uid=10102
I/ActivityManager( 199): Killing proc 20698:com.viperean.atcassistant/10102: force stop
W/ActivityManager( 199): Force removing ActivityRecord{41eb1ec0 com.viperean.atcassistant/.atcChoice}: app died, no saved state
(and the second line shows that it is killing your asynctask...).
I don't think there is anything wrong with the download code by itself. I think you should look more in the activity (what are you doing during that time beside that asynctask, what are you displaying on the screen...etc...).
Seems also that you are pretty low in heap space.
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
D/dalvikvm( 199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm( 199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
Those are from the garbage collection and happen just before your app crashed, maybe that could be a problem too?
every thread in Android is being killed by the system if it doesn't respond for more than five minutes. maybe you should consider downloading as a service or overriding the onProgress and get the thread to stay alive

Categories