Back button, jsoup and AsyncTask - java

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();
}

Related

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.

Android Volley - Getting No Response using StringRequest to XML API

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"/>

unfortunately has stopped when I want to update ListView

My logic is as follows.
First, I get some data from the server. Then, I manipulate the data. Next, I put the data into a ListView. If the user scrolls to the bottom of this view, I want to refresh the view. I copy the properties from my Async object to a new object. At this point I see "unfortunately has stopped".
Here my code of activity class
DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH,monthOfYear);
this.Syear = calendar.get(Calendar.YEAR);
this.Smonth = calendar.get(Calendar.MONTH);
Smonth = Smonth + 1;
InboxActivity i = new InboxActivity();
String user_id = getIntent().getExtras().getString(LoginActivity.SESSION_ID);
final FetchTask fetch = new FetchTask();
fetch.Selectedmonth = this.Smonth;
fetch.Selectedyear = this.Syear;
fetch.page = 0;
fetch.sess_id = user_id;
ListView ll = (ListView)findViewById(R.id.mailList);
fetch.ll = ll;
fetch.execute();
ll.setOnScrollListener(new OnScrollListener(){
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount)
{
if(firstVisibleItem+visibleItemCount==totalItemCount)
{
//System.out.println("HERE WILL BE MY SESSION ID!!!!w");
//System.out.println(fetch.sess_id);
FetchTask RefreshFetch = new FetchTask();
fetch.page++;
RefreshFetch.page = fetch.page++;
RefreshFetch.Selectedmonth = fetch.Selectedmonth;
RefreshFetch.Selectedyear = fetch.Selectedyear;
RefreshFetch.sess_id = fetch.sess_id;
RefreshFetch.ll = fetch.ll;
RefreshFetch.execute();
}
}
});
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
public class FetchTask extends AsyncTask<Void, Void, JSONArray> {
public JSONArray result_arr;
public String result_str,email,password,test;
public int Selectedyear;
public int Selectedmonth;
public int page;
public String sess_id;
public ListView ll;
public ProgressDialog pd;
public ArrayAdapter<String> adapter;
#Override
protected JSONArray doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("MY SITE URL ....");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("qw", "das"));
nameValuePairs.add(new BasicNameValuePair("debug", "1"));
nameValuePairs.add(new BasicNameValuePair("t", "0"));
nameValuePairs.add(new BasicNameValuePair("m", Integer.toString(this.Selectedmonth)));
nameValuePairs.add(new BasicNameValuePair("y", Integer.toString(this.Selectedyear)));
nameValuePairs.add(new BasicNameValuePair("st", Integer.toString(this.page)));
nameValuePairs.add(new BasicNameValuePair("sess_id", this.sess_id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine());
String line = "0";
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
reader.close();
String result11 = sb.toString();
this.result_str = result11;
// parsing data
JSONArray arr = new JSONArray(result11);
return new JSONArray(result11);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
}
My logs
03-05 13:24:43.239: D/dalvikvm(2052): GC_FOR_ALLOC freed 49K, 7% free 3326K/3540K, paused 33ms, total 35ms
03-05 13:24:43.629: D/gralloc_goldfish(2052): Emulator without GPU emulation detected.
03-05 13:24:50.349: D/dalvikvm(2052): GC_FOR_ALLOC freed 151K, 8% free 3690K/4004K, paused 28ms, total 36ms
03-05 13:24:50.349: D/InputEventConsistencyVerifier(2052): KeyEvent: ACTION_UP but key was not down.
03-05 13:24:50.349: D/InputEventConsistencyVerifier(2052): in android.widget.EditText{b1e53a20 VFED..CL .F....I. 179,489-589,548 #7f090004 app:id/password}
03-05 13:24:50.349: D/InputEventConsistencyVerifier(2052): 0: sent at 11916532000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=11916532, downTime=11916440, deviceId=0, source=0x101 }
03-05 13:24:55.809: D/dalvikvm(2052): GC_FOR_ALLOC freed 417K, 14% free 3788K/4368K, paused 31ms, total 31ms
03-05 13:24:56.509: D/dalvikvm(2052): GC_FOR_ALLOC freed 89K, 12% free 3877K/4368K, paused 39ms, total 42ms
03-05 13:24:56.549: D/dalvikvm(2052): GC_FOR_ALLOC freed 28K, 12% free 3947K/4468K, paused 39ms, total 40ms
03-05 13:24:56.599: I/dalvikvm-heap(2052): Grow heap (frag case) to 5.087MB for 1127536-byte allocation
03-05 13:24:56.649: D/dalvikvm(2052): GC_FOR_ALLOC freed <1K, 10% free 5048K/5572K, paused 48ms, total 48ms
03-05 13:25:14.239: D/dalvikvm(2052): GC_FOR_ALLOC freed 504K, 12% free 5273K/5940K, paused 56ms, total 58ms
03-05 13:25:15.319: I/Choreographer(2052): Skipped 125 frames! The application may be doing too much work on its main thread.
03-05 13:25:15.809: I/Choreographer(2052): Skipped 49 frames! The application may be doing too much work on its main thread.
03-05 13:25:16.209: I/Choreographer(2052): Skipped 34 frames! The application may be doing too much work on its main thread.
03-05 13:25:17.249: I/Choreographer(2052): Skipped 87 frames! The application may be doing too much work on its main thread.
03-05 13:25:17.599: I/Choreographer(2052): Skipped 35 frames! The application may be doing too much work on its main thread.
03-05 13:25:22.239: I/Choreographer(2052): Skipped 37 frames! The application may be doing too much work on its main thread.
03-05 13:25:22.659: I/Choreographer(2052): Skipped 42 frames! The application may be doing too much work on its main thread.
03-05 13:25:23.629: I/Choreographer(2052): Skipped 98 frames! The application may be doing too much work on its main thread.
03-05 13:25:24.819: D/AndroidRuntime(2052): Shutting down VM
03-05 13:25:24.819: W/dalvikvm(2052): threadid=1: thread exiting with uncaught exception (group=0xb1aefba8)
03-05 13:25:24.919: E/AndroidRuntime(2052): FATAL EXCEPTION: main
03-05 13:25:24.919: E/AndroidRuntime(2052): Process: com.example.earchive, PID: 2052
03-05 13:25:24.919: E/AndroidRuntime(2052): java.lang.NullPointerException
03-05 13:25:24.919: E/AndroidRuntime(2052): at com.example.earchive.InboxActivity$FetchTask.onPostExecute(InboxActivity.java:291)
03-05 13:25:24.919: E/AndroidRuntime(2052): at com.example.earchive.InboxActivity$FetchTask.onPostExecute(InboxActivity.java:1)
03-05 13:25:24.919: E/AndroidRuntime(2052): at android.os.AsyncTask.finish(AsyncTask.java:632)
03-05 13:25:24.919: E/AndroidRuntime(2052): at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-05 13:25:24.919: E/AndroidRuntime(2052): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
03-05 13:25:24.919: E/AndroidRuntime(2052): at android.os.Handler.dispatchMessage(Handler.java:102)
03-05 13:25:24.919: E/AndroidRuntime(2052): at android.os.Looper.loop(Looper.java:136)
03-05 13:25:24.919: E/AndroidRuntime(2052): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-05 13:25:24.919: E/AndroidRuntime(2052): at java.lang.reflect.Method.invokeNative(Native Method)
03-05 13:25:24.919: E/AndroidRuntime(2052): at java.lang.reflect.Method.invoke(Method.java:515)
03-05 13:25:24.919: E/AndroidRuntime(2052): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-05 13:25:24.919: E/AndroidRuntime(2052): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-05 13:25:24.919: E/AndroidRuntime(2052): at dalvik.system.NativeStart.main(Native Method)
03-05 13:25:26.259: D/dalvikvm(2052): GC_FOR_ALLOC freed 385K, 9% free 5692K/6240K, paused 145ms, total 145ms
On post execute method
protected void onPostExecute(JSONArray result)
{
if (result != null)
{
List<String> subjects = new ArrayList<String>();
List<String> emails = new ArrayList<String>();
for(int i = 0; i < result.length(); i++)
{
try
{
JSONObject json_data = result.getJSONObject(i);
emails.add(json_data.getString("mittente"));
subjects.add(json_data.getString("oggetto"));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
if(this.page == 0)
{
this.adapter = new ArrayAdapter<String>(
InboxActivity.this,
R.layout.da_item,
emails
);
this.ll.setAdapter(this.adapter);
}
else
{
for(int i = 0; i < result.length(); i++)
{
JSONObject json_data;
try
{
json_data = result.getJSONObject(i);
this.adapter.add(json_data.getString("mittente"));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
else
{
System.out.println("Messages not found");
}
this.pd.dismiss();
}
}
Your this.adapter.add(json_data.getString("mittente")); is throwing a NullPointerException.
If page = 1, this.adapter is not initialized (page = 0) and is therefore NULL. If page 0 is guaranteed to be called before page 1, this would work, but I'm guessing it is not. Here's a fix if I understand your code correctly.
if( this.adapter == null ) {
this.adapter = new ArrayAdapter<String>(
InboxActivity.this,
R.layout.da_item,
emails
);
this.ll.setAdapter(this.adapter);
}
if(this.page != 0)
{
for(int i = 0; i < result.length(); i++)
{
JSONObject json_data;
try
{
json_data = result.getJSONObject(i);
this.adapter.add(json_data.getString("mittente"));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}

Getter is crashing program

I am using a getter the same way that I always do (I think), and it crashes the program, but I cannot figure out why! Does anyone have any idea where my mistake is?
its crashing on line 45 below:
package edu.virginia.hotncolduva;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import sofia.app.Screen;
import android.content.Context;
import android.location.LocationManager;
import android.os.SystemClock;
import android.text.Editable;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
public class HotNColdUva extends Screen {
private TextView txtHotOrCold;
private TextView txtLocation;
private double currentLatitude;
private double currentLongitude;
private static List<HistoricalLocation> places;
private static Chronometer chronometer;
private boolean victor;
private EditText inputLatitude;
private EditText inputLongitude;
private HistoricalLocation riceHall;
public void initialize() {
presentScreen(MainMenu.class);
presentScreen(Splash.class);
victor = false;
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
makeHistoricalLocations();
for(HistoricalLocation hl : places){
hl.setDistance(howFar(hl));
}
//THIS IS WHAT CAUSES THE CRASH
riceHall.getLatitude();
currentLatitude = 38.03211;
currentLongitude = -78.51002;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// LocationListener locList = new WhereAmI();
// lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
// locList);
// new Thread(new Runnable(){
// public void run(){
// Timer.callRepeatedly(this, "update", 1000);
// }
// }).start();
// jeffersonStatue();
new Timer().schedule(new TimerTask() {
public void run() {
update();
}
}, 1000, 1000);
}
public void btnTeleportClicked(){
// currentLatitude = doubleinputLatitude.getText();
// currentLongitude = inputLatitude.getText();;
}
public void makeHistoricalLocations() {
HistoricalLocation riceHall = new HistoricalLocation(
"Rice Hall",
38.03161,
-78.51075,
0,
"\"The real promise of what will happen here is the 21st Century extension of the academical village and what will be made possible by the technologies that are used, developed and explored in these places. The village won’t simply exist then in these buildings or on this campus, but across the state, across the nation and globe. We have only really begun to understand the way in which these technologies can enhance human performance and accomplishment and how they can improve the human condition.\"\n\n-Paul Rice",
false);}
package edu.virginia.hotncolduva;
import sofia.app.Screen;
public class HistoricalLocation extends Screen {
private String name;
private double latitude;
private double longitude;
private double distance;
private String hist;
private boolean visited;
public HistoricalLocation(String name, double latitude, double longitude, double distance,
String hist, boolean visited) {
super();
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.distance = distance;
this.hist = hist;
this.visited = visited;
}
#Override
public String toString() {
return name;
}
public String getName() {
return name;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
public String getHist() {
return hist;
}
public boolean getVisited() {
return visited;
}
public void hasVisited() {
visited = true;
}
}
this is obviously not the entire project, but this is all of the code that is being used. it is crashing on
riceHall.getLatitude();
logcat:
04-20 16:26:27.700: W/ActivityThread(27796): Application edu.virginia.hotncolduva can be debugged on port 8100...
04-20 16:26:27.760: D/dalvikvm(27796): GC_FOR_ALLOC freed 131K, 4% free 7361K/7640K, paused 17ms, total 19ms
04-20 16:26:27.760: I/dalvikvm-heap(27796): Grow heap (frag case) to 7.842MB for 539664-byte allocation
04-20 16:26:27.790: D/dalvikvm(27796): GC_CONCURRENT freed 1K, 4% free 7886K/8168K, paused 5ms+2ms, total 29ms
04-20 16:26:27.790: D/dalvikvm(27796): WAIT_FOR_CONCURRENT_GC blocked 24ms
04-20 16:26:27.830: D/dalvikvm(27796): GC_FOR_ALLOC freed <1K, 4% free 7886K/8168K, paused 14ms, total 14ms
04-20 16:26:27.830: I/dalvikvm-heap(27796): Grow heap (frag case) to 8.751MB for 955696-byte allocation
04-20 16:26:27.850: D/dalvikvm(27796): GC_FOR_ALLOC freed 0K, 4% free 8819K/9104K, paused 17ms, total 17ms
04-20 16:26:27.870: D/dalvikvm(27796): GC_CONCURRENT freed <1K, 4% free 8820K/9104K, paused 2ms+1ms, total 22ms
04-20 16:26:27.930: D/AndroidRuntime(27796): Shutting down VM
04-20 16:26:27.930: W/dalvikvm(27796): threadid=1: thread exiting with uncaught exception (group=0x40d12930)
04-20 16:26:27.940: E/AndroidRuntime(27796): FATAL EXCEPTION: main
04-20 16:26:27.940: E/AndroidRuntime(27796): java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.virginia.hotncolduva/edu.virginia.hotncolduva.HotNColdUva}: java.lang.NullPointerException
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.os.Handler.dispatchMessage(Handler.java:99)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.os.Looper.loop(Looper.java:137)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-20 16:26:27.940: E/AndroidRuntime(27796): at java.lang.reflect.Method.invokeNative(Native Method)
04-20 16:26:27.940: E/AndroidRuntime(27796): at java.lang.reflect.Method.invoke(Method.java:511)
04-20 16:26:27.940: E/AndroidRuntime(27796): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-20 16:26:27.940: E/AndroidRuntime(27796): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-20 16:26:27.940: E/AndroidRuntime(27796): at dalvik.system.NativeStart.main(Native Method)
04-20 16:26:27.940: E/AndroidRuntime(27796): Caused by: java.lang.NullPointerException
04-20 16:26:27.940: E/AndroidRuntime(27796): at edu.virginia.hotncolduva.HotNColdUva.initialize(HotNColdUva.java:45)
04-20 16:26:27.940: E/AndroidRuntime(27796): at java.lang.reflect.Method.invokeNative(Native Method)
04-20 16:26:27.940: E/AndroidRuntime(27796): at java.lang.reflect.Method.invoke(Method.java:511)
04-20 16:26:27.940: E/AndroidRuntime(27796): at sofia.internal.events.EventDispatcher$MethodTransformer.invoke(EventDispatcher.java:474)
04-20 16:26:27.940: E/AndroidRuntime(27796): at sofia.internal.events.EventDispatcher.invokeTransformer(EventDispatcher.java:136)
04-20 16:26:27.940: E/AndroidRuntime(27796): at sofia.internal.events.EventDispatcher.dispatch(EventDispatcher.java:109)
04-20 16:26:27.940: E/AndroidRuntime(27796): at sofia.app.internal.ScreenMixin.invokeInitialize(ScreenMixin.java:561)
04-20 16:26:27.940: E/AndroidRuntime(27796): at sofia.app.Screen.onCreate(Screen.java:186)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.app.Activity.performCreate(Activity.java:5104)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-20 16:26:27.940: E/AndroidRuntime(27796): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-20 16:26:27.940: E/AndroidRuntime(27796): ... 11 more
04-20 16:26:27.970: D/dalvikvm(27796): GC_CONCURRENT freed 797K, 11% free 8472K/9416K, paused 2ms+5ms, total 34ms
In the method makeHistoricalLocations you are assigning reference of a new object to a local variable, not to instance one.
public void makeHistoricalLocations() {
this.riceHall = new HistoricalLocation(
...
riceHall is null, because you have never initialized it.
It seems like your variable riceHall is null. I can't tell because you cut off the implementation of makeHistoricalLocations but I suspect you are either not calling that method, or (more likely) creating a method-local version of riceHall and not setting it at the object level.

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

Categories