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();
}
}
}
Related
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.
Error Occured white retriving Bitmap In AsyncTask process the Logcat log is below,
please tell me how to clear this Error
I am beginner to android help me
thanks in advance
10-14 18:09:19.380 14124-16035/com.fragments D/dalvikvm﹕ GC_FOR_ALLOC freed 747K, 4% free 37438K/38855K, paused 191ms, total 193ms
10-14 18:09:19.400 14124-16035/com.fragments I/dalvikvm-heap﹕ Forcing collection of SoftReferences for 14155792-byte allocation
10-14 18:09:19.490 14124-16035/com.fragments D/dalvikvm﹕ GC_BEFORE_OOM freed 15K, 4% free 37422K/38855K, paused 91ms, total 91ms
10-14 18:09:19.490 14124-16035/com.fragments E/dalvikvm-heap﹕ Out of memory on a 14155792-byte allocation.
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ "AsyncTask #4" prio=5 tid=16 RUNNABLE
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ | group="main" sCount=0 dsCount=0 obj=0x432d6fc0 self=0x4d7c1fe8
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ | sysTid=16035 nice=10 sched=3/0 cgrp=[fopen-error:2] handle=1300340400
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ | schedstat=( 0 0 0 ) utm=15 stm=3 core=0
10-14 18:09:19.490 14124-16035/com.fragments I/dalvikvm﹕ at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
10-14 18:09:19.500 14124-16035/com.fragments I/dalvikvm﹕ at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:663)
10-14 18:09:19.500 14124-16035/com.fragments I/dalvikvm﹕ at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:735)
10-14 18:09:19.510 14124-16035/com.fragments I/dalvikvm﹕ at com.fragments.NewsListAdapter$ImageLoader.doInBackground(NewsListAdapter.java:128)
10-14 18:09:19.520 14124-16035/com.fragments I/dalvikvm﹕ at com.fragments.NewsListAdapter$ImageLoader.doInBackground(NewsListAdapter.java:112)
10-14 18:09:19.520 14124-16035/com.fragments I/dalvikvm﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ at java.lang.Thread.run(Thread.java:856)
10-14 18:09:19.530 14124-16035/com.fragments I/dalvikvm﹕ [ 10-14 18:09:19.530 14124:14133 W/SQLiteConnectionPool ]
A SQLiteConnection object for database '+data+data+com_fragments+databases+news_db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
10-14 18:09:19.530 14124-14133/com.fragments D/AbsListView﹕ [unregisterDoubleTapMotionListener]
10-14 18:09:19.530 14124-14133/com.fragments I/MotionRecognitionManager﹕ .unregisterListener : / listener count = 0->0, ubvf 9budiwrd5ordgfl5BakTrklMrfo$,#,+)de/a(
10-14 18:09:19.560 14124-16035/com.fragments D/skia﹕ --- decoder->decode returned false
10-14 18:09:19.580 14124-16035/com.fragments W/dalvikvm﹕ threadid=16: thread exiting with uncaught exception (group=0x41ccd2b8)
10-14 18:09:19.740 14124-16035/com.fragments E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #4
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:663)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:735)
at com.fragments.NewsListAdapter$ImageLoader.doInBackground(NewsListAdapter.java:128)
at com.fragments.NewsListAdapter$ImageLoader.doInBackground(NewsListAdapter.java:112)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
10-14 18:09:28.740 14124-14124/com.fragments D/AndroidRuntime﹕ Shutting down VM
10-14 18:09:28.740 14124-14124/com.fragments W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41ccd2b8)
10-14 18:09:28.740 14124-14124/com.fragments I/Process﹕ Sending signal. PID: 14124 SIG: 9
Update:
This is my AsyncTask class
private class ImageLoader extends AsyncTask<NewsAndImages, Void, NewsAndImages> {
#Override
protected NewsAndImages doInBackground(NewsAndImages... params) {
NewsAndImages container = params[0];
News news = container.news;
try {
if (container.position > 0) {
InputStream in = (InputStream) new URL(news.getImage150()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
news.setBitmap(bitmap);
in.close();
container.bitmap = bitmap;
return container;
} else {
InputStream in = (InputStream) new URL(news.getRealImage()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
news.setBitmap(bitmap);
in.close();
container.bitmap = bitmap;
return container;
}
} catch (Exception e) {
Log.v("LOGTAG", e + " streaming pic"+news.getImage150());
}
return null;
}
#Override
protected void onPostExecute(NewsAndImages newsAndImages) {
try {
if (newsAndImages.position > 0) {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsListImage);
imageView.setImageBitmap(newsAndImages.bitmap);
newsAndImages.news.setBitmap(newsAndImages.bitmap);
}else {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsHeadLineImage);
imageView.setImageBitmap(newsAndImages.bitmap);
newsAndImages.news.setBitmap(newsAndImages.bitmap);
}
} catch (Exception e) {
Log.v("LOGTAG", e + " post exe");
}
}
}
Now Tell me what to do...
Apparently your method doInBackground cant process your image. Do you have other images process in your app at all? Also, I recommend you to use this:
bitmap.recycle();
bitmap = null;
This will assure the bitmap is garbage collected. If you don't recycle your bitmaps you will have an out of memory exception
Don't set bitmap inside doInBackground. rather return new downloaded bitmap and set only inside onPostExecute.
you set bitmap twice right now so remove from doInBackground and recycle after use.
update code
private class ImageLoader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(NewsAndImages... params) {
NewsAndImages container = params[0];
News news = container.news;
try {
if (container.position > 0) {
InputStream in = (InputStream) new URL(news.getImage150()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
} else {
InputStream in = (InputStream) new URL(news.getRealImage()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
}
} catch (Exception e) {
Log.v("LOGTAG", e + " streaming pic"+news.getImage150());
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
try {
if (bitmap !=null) {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsListImage);
imageView.setImageBitmap(bitmap);
newsAndImages.news.setBitmap(bitmap);
}else {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsHeadLineImage);
imageView.setImageBitmap(bitmap);
newsAndImages.news.setBitmap(bitmap);
}
bitmap.recycle();
} catch (Exception e) {
Log.v("LOGTAG", e + " post exe");
}
}
}
It Works...
By Using LruCache
private class ImageLoader extends AsyncTask<NewsAndImages, Void, NewsAndImages> {
#Override
protected NewsAndImages doInBackground(NewsAndImages... params) {
NewsAndImages container = params[0];
News news = container.news;
try {
if (container.position > 0) {
InputStream in = (InputStream) new URL(news.getImage150()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
news.setBitmap(bitmap);
in.close();
container.bitmap = bitmap;
return container;
} else {
InputStream in = (InputStream) new URL(news.getRealImage()).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
news.setBitmap(bitmap);
in.close();
container.bitmap = bitmap;
return container;
}
} catch (Exception e) {
Log.v("LOGTAG", e + " streaming pic" + news.getImage150());
}
return null;
}
#Override
protected void onPostExecute(NewsAndImages newsAndImages) {
try {
if (newsAndImages.position > 0) {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsListImage);
imageView.setImageBitmap(newsAndImages.bitmap);
imageCache.put(newsAndImages.news.getNews_id(),newsAndImages.bitmap);
} else {
ImageView imageView = (ImageView) newsAndImages.view.findViewById(R.id.newsHeadLineImage);
imageView.setImageBitmap(newsAndImages.bitmap);
imageCache.put(newsAndImages.news.getNews_id(),newsAndImages.bitmap);
}
} catch (Exception e) {
Log.i(NewsDBOpenHelper.LOGTAG, e + " onPostExecute");
}
}
}
this is my code it throws java null pointer exception on fetching json from url.i have given the internet permission in android manifest and now fetch url in new thread as it does not allow network activities in main threaed
package com.example.usa;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
public class Home extends Activity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
JSONArray contacts = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
final JSONObject json = null ;
// getting JSON string from URL
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
JSONObject json = jParser.getJSONFromUrl(url);
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
//
finish();
}
}, 5000);
// JSONObject json = jParser.getJSONFromUrl(url);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
///////////////////////////
Log.w("ID",id);
Log.w("Name",name);
Log.w("Email",email);
Log.w("Gender",gender);
Log.w("mobile",mobile);
Log.w("home",home);
Log.w("office",office);
Log.w("address",address);
///////////////////
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
//
finish();
}
}, 5000);
// TODO Auto-generated method stub
}
}
this is the stack trace
10-04 06:39:24.830: D/dalvikvm(777): GC_FOR_ALLOC freed 15K, 4% free 4156K/4288K, paused 42ms, total 45ms
10-04 06:39:24.850: I/dalvikvm-heap(777): Grow heap (frag case) to 5.635MB for 1536016-byte allocation
10-04 06:39:25.040: D/dalvikvm(777): GC_FOR_ALLOC freed <1K, 3% free 5655K/5792K, paused 180ms, total 180ms
10-04 06:39:30.280: D/AndroidRuntime(777): Shutting down VM
10-04 06:39:30.280: W/dalvikvm(777): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-04 06:39:30.290: E/AndroidRuntime(777): FATAL EXCEPTION: main
10-04 06:39:30.290: E/AndroidRuntime(777): java.lang.NullPointerException
10-04 06:39:30.290: E/AndroidRuntime(777): at com.example.usa.Home$2.run(Home.java:105)
10-04 06:39:30.290: E/AndroidRuntime(777): at android.os.Handler.handleCallback(Handler.java:730)
10-04 06:39:30.290: E/AndroidRuntime(777): at android.os.Handler.dispatchMessage(Handler.java:92)
10-04 06:39:30.290: E/AndroidRuntime(777): at android.os.Looper.loop(Looper.java:137)
10-04 06:39:30.290: E/AndroidRuntime(777): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-04 06:39:30.290: E/AndroidRuntime(777): at java.lang.reflect.Method.invokeNative(Native Method)
10-04 06:39:30.290: E/AndroidRuntime(777): at java.lang.reflect.Method.invoke(Method.java:525)
10-04 06:39:30.290: E/AndroidRuntime(777): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-04 06:39:30.290: E/AndroidRuntime(777): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-04 06:39:30.290: E/AndroidRuntime(777): at dalvik.system.NativeStart.main(Native Method)
10-04 06:39:34.957: D/dalvikvm(777): GC_FOR_ALLOC freed 261K, 6% free 6445K/6824K, paused 81ms, total 98ms
10-04 06:40:00.868: D/dalvikvm(777): GC_FOR_ALLOC freed 2688K, 36% free 5075K/7880K, paused 39ms, total 43ms
10-04 06:44:25.888: I/Process(777): Sending signal. PID: 777 SIG: 9
Here is the problem:
JSONObject json = jParser.getJSONFromUrl(url);
In the first thread you are retreiving data from URL and parsing it to json, soon after first thread, you are trying to retrieve data from JSON object, which most probably don't have any data because it is still busy in retrieving data.
So it is not a good idea. Retrieve and get data from JSON array in the same thread. This will save you alot of trouble.
Second you are storing the json parsed data in a local json object in the first thread instead of the global one and trying to use the null json object to get TAG_CONTACT data. This is causing NULL Pointer Exception
You have this line
JSONObject json = jParser.getJSONFromUrl(url);
but you also have a method variable json, which I think you are intending to use later.
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();
}
My classmates and I are stuck on an issue with android application we are building.
We've successfully built an Android app which contains an activity which searches our browser histories / bookmarks for specific urls and launches another activity (successfully) if a match is found as an example of an adult content warning implementation.
This is functioning fine.
Now we are implementing a service class to continually execute every few seconds - in order to execute the search of our recent history using our new service class - but we're experiencing a few issues.
Our problem is when we attempt to add the "Nanny" source code from Nanny.java to the service class so the "Nanny" script will search the history continuously, instead of just once - the "Nanny" application continually force closes - due to a null pointer exception at the initialization of our cursor: if (cursor.moveToFirst()) {
Which is a bit strange because the NullPointerException does not occur when the exact same script is executed outside the service class in a test file we have (Main.java)
Our working Main.java and our working service class [which successfully displays a toast every few seconds] as well as our [failed] combination of the two - are shown below:
Empty Service Class:
public class Service_class extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
Working Nanny.java
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
public class Nanny extends Activity {
String Dirty1 = "www.playboy.com";
String Dirty2 = "www.penthouse.com";
String Dirty3 = "www.pornhub.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nanny);
TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
//if (url.toLowerCase().contains(Filthy)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent intent = new Intent(Nanny.this, Warning.class);
Nanny.this.startActivity(intent);
}
} while (cursor.moveToNext());
tv.setText(urls);
}}}
Unsuccessful method we've attempted to implement (adding the functioning nanny script to the service class) which causes the NullPointerException: if (cursor.moveToFirst()) {
public class Service_class extends Service {
String Dirty1 = "www.playboy.com";
String Dirty2 = "www.penthouse.com";
String Dirty3 = "www.pornhub.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//setContentView(R.layout.main3);
// TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent warning_intent = new Intent(Service_class.this, Warning.class);
Service_class.this.startActivity(intent);
}
} while (cursor.moveToNext());
// tv.setText(urls);
return START_STICKY;
}
return startId;}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
private void setContentView(int main3) {
// TODO Auto-generated method stub
}
private TextView findViewById(int hello) {
// TODO Auto-generated method stub
return null;
}
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
LOGCAT (When using combined implementation shown above)
Fails on Line 53: if (cursor.moveToFirst()) {
04-15 18:26:24.761: D/dalvikvm(7466): Late-enabling CheckJNI
04-15 18:26:25.651: D/dalvikvm(7466): GC_FOR_ALLOC freed 82K, 4% free 7379K/7608K, paused 13ms, total 13ms
04-15 18:26:25.651: I/dalvikvm-heap(7466): Grow heap (frag case) to 10.861MB for 3686416-byte allocation
04-15 18:26:25.661: D/dalvikvm(7466): GC_FOR_ALLOC freed 1K, 3% free 10977K/11212K, paused 13ms, total 13ms
04-15 18:26:25.681: D/dalvikvm(7466): GC_CONCURRENT freed <1K, 3% free 10977K/11212K, paused 3ms+2ms, total 17ms
04-15 18:26:25.901: D/dalvikvm(7466): GC_FOR_ALLOC freed <1K, 3% free 10977K/11212K, paused 11ms, total 11ms
04-15 18:26:25.911: I/dalvikvm-heap(7466): Grow heap (frag case) to 17.086MB for 6529744-byte allocation
04-15 18:26:25.931: D/dalvikvm(7466): GC_FOR_ALLOC freed 0K, 2% free 17354K/17592K, paused 13ms, total 13ms
04-15 18:26:25.941: D/dalvikvm(7466): GC_CONCURRENT freed <1K, 2% free 17354K/17592K, paused 3ms+2ms, total 16ms
04-15 18:26:26.051: D/libEGL(7466): loaded /system/lib/egl/libEGL_tegra.so
04-15 18:26:26.061: D/libEGL(7466): loaded /system/lib/egl/libGLESv1_CM_tegra.so
04-15 18:26:26.071: D/libEGL(7466): loaded /system/lib/egl/libGLESv2_tegra.so
04-15 18:26:26.091: D/OpenGLRenderer(7466): Enabling debug mode 0
04-15 18:26:31.181: D/AndroidRuntime(7466): Shutting down VM
04-15 18:26:31.181: W/dalvikvm(7466): threadid=1: thread exiting with uncaught exception (group=0x40f4f930)
04-15 18:26:31.181: E/AndroidRuntime(7466): FATAL EXCEPTION: main
04-15 18:26:31.181: E/AndroidRuntime(7466): java.lang.RuntimeException: Unable to start service com.ut.appdemo.Service_class#41698e90 with Intent { cmp=com.ut.appdemo/.Service_class }: java.lang.NullPointerException
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2673)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.access$1900(ActivityThread.java:141)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.os.Looper.loop(Looper.java:137)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-15 18:26:31.181: E/AndroidRuntime(7466): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 18:26:31.181: E/AndroidRuntime(7466): at java.lang.reflect.Method.invoke(Method.java:511)
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-15 18:26:31.181: E/AndroidRuntime(7466): at dalvik.system.NativeStart.main(Native Method)
04-15 18:26:31.181: E/AndroidRuntime(7466): Caused by: java.lang.NullPointerException
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.ut.appdemo.Service_class.onStartCommand(Service_class.java:53)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2656)
04-15 18:26:31.181: E/AndroidRuntime(7466): ... 10 more
You are setting the cursor to null...
you use this method to instantiate the cursor:
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,projection, null, null, null);
and then you define managedQuery() method like this:
private Cursor managedQuery(Uri bookmarksUri, String[] projection, Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
essentially what your code says is:
Cursor cursor = null;
curser.doSomething();
this will always result in a nullPointer. I strongly suggest you go back and study java fundamentals before diving in to android, you are just asking for headaches if you are trying to accomplish something in android with such a lack of understanding of java.