java Null pointer Exception on fetching JSON - java

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.

Related

Error when attempting to connect to local Database

When I attempt to connect to a local Database on my computer I get a list of problems.
07-31 21:29:53.036: I/System.out(1470): 1
07-31 21:29:53.046: I/System.out(1470): 2
07-31 21:29:53.106: I/System.out(1470): 3
07-31 21:29:53.326: W/EGL_emulation(1470): eglSurfaceAttrib not implemented
07-31 21:30:00.126: E/JSON(1470):{"tag":"register","success":0,"error":1,"error_msg":"Error occured in Registartion"}n
07-31 21:30:00.126: I/System.out(1470): 4
07-31 21:30:00.156: I/System.out(1470): 5
07-31 21:30:00.156: I/System.out(1470): ERROR
07-31 21:30:00.186: W/System.err(1470): java.lang.NullPointerException
07-31 21:30:00.186: W/System.err(1470): at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:138)
07-31 21:30:00.196: W/System.err(1470): at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:1)
07-31 21:30:00.196: W/System.err(1470): at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-31 21:30:00.196: W/System.err(1470): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-31 21:30:00.196: W/System.err(1470): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-31 21:30:00.206: W/System.err(1470): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-31 21:30:00.206: W/System.err(1470): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-31 21:30:00.206: W/System.err(1470): at java.lang.Thread.run(Thread.java:841)
07-31 21:30:00.206: I/System.out(1470): 9
07-31 21:30:00.326: D/AndroidRuntime(1470): Shutting down VM
07-31 21:30:00.326: W/dalvikvm(1470): threadid=1: thread exiting with uncaught exception (group=0xb1a32ba8)
07-31 21:30:00.336: E/AndroidRuntime(1470): FATAL EXCEPTION: main
07-31 21:30:00.336: E/AndroidRuntime(1470): Process: com.example.skelotong, PID: 1470
07-31 21:30:00.336: E/AndroidRuntime(1470): java.lang.NullPointerException
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.example.skelotong.RegularUsercreation$ruc.onPostExecute(RegularUsercreation.java:184)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.example.skelotong.RegularUsercreation$ruc.onPostExecute(RegularUsercreation.java:1)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask.finish(AsyncTask.java:632)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.Handler.dispatchMessage(Handler.java:102)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.Looper.loop(Looper.java:136)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-31 21:30:00.336: E/AndroidRuntime(1470): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 21:30:00.336: E/AndroidRuntime(1470): at java.lang.reflect.Method.invoke(Method.java:515)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-31 21:30:00.336: E/AndroidRuntime(1470): at dalvik.system.NativeStart.main(Native Method)
07-31 21:30:03.356: I/Process(1470): Sending signal. PID: 1470 SIG: 9
07-31 21:30:05.946: D/dalvikvm(1499): GC_FOR_ALLOC freed 179K, 12% free 3467K/3932K, paused 141ms, total 144ms
07-31 21:30:06.636: D/(1499): HostConnection::get() New Host Connection established 0xb8f39498, tid 1499
07-31 21:30:06.786: W/EGL_emulation(1499): eglSurfaceAttrib not implemented
07-31 21:30:06.796: D/OpenGLRenderer(1499): Enabling debug mode 0
Here is the code that I attempt to run.
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegularUsercreation extends ActionBarActivity implements Runnable {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
EditText inputUsername;
EditText dateofbirth;
EditText zip;
// EditText skils;
// JSON Response node names
private static String KEY_SUCCESS = "success";
// private static String KEY_ERROR = "error";
// private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private Handler mHandler = new Handler(Looper.getMainLooper());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regular_usercreation);
}
public void clicker(View view) {
new ruc().execute((String[]) null);
}
public void ss(View view) {
Intent i = new Intent(getApplicationContext(), RegisterClass.class);
startActivity(i);
// Close Registration View
finish();
}
private class ruc extends AsyncTask<String, Integer, Boolean> {
final ProgressDialog pd = new ProgressDialog(RegularUsercreation.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.setMessage("Please wait");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCanceledOnTouchOutside(false);
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
System.out.println("1");
}
#Override
protected Boolean doInBackground(String... params) {
System.out.println(2);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.FullName2);
inputEmail = (EditText) findViewById(R.id.Email2);
inputPassword = (EditText) findViewById(R.id.Password2);
inputUsername = (EditText) findViewById(R.id.Username2);
dateofbirth = (EditText) findViewById(R.id.DOB2);
zip = (EditText) findViewById(R.id.ZipCode2);
btnRegister = (Button) findViewById(R.id.create2);
btnLinkToLogin = (Button) findViewById(R.id.cancel2);
registerErrorMsg = (TextView) findViewById(R.id.errormessage3);
// skils = (EditText) findViewById(R.id.skills1);
System.out.println("3");
// Register Button Click event
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String usernmae = inputUsername.getText().toString();
String birth = dateofbirth.getText().toString();
String zipcode = zip.getText().toString();
// String skills = skils.getText().toString();
UserFunction userFunction = new UserFunction();
JSONObject json = userFunction.registerUser(name, email, password,
usernmae, birth, zipcode);
System.out.println(4);
// check for login response
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
System.out.println("5");
if (Integer.parseInt(res) == 1) {
publishProgress(1);
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
System.out.println(6);
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME),
json_user.getString(KEY_EMAIL),
json.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
System.out.println("7");
return true;
} else {
System.out.println("ERROR");
// Error in registration
//registerErrorMsg
// .setText("Error occured in registration");
return false;
}
}
} catch (JSONException e) {
publishProgress(1);
e.printStackTrace();
System.out.println("9");
return false;
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
if (values.equals(1)) {
pd.setMessage("Almost Done");
}
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == true) {
// launch dashboard
Intent dashboard = new Intent(getApplicationContext(),
HomePage.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}
if (result == false) {
registerErrorMsg.setText("Error occured in registration");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.regular_usercreation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void run() {
// TODO Auto-generated method stub
mHandler.post(new Runnable() {
public void run() {
new ruc();
ruc.execute(RegularUsercreation.this);
}
});
}
}
How can this problem be fixed and what can be done in the future to prevent this?
Also why does this happen.
from the looks of is either res is null or something's null within these lines
if (Integer.parseInt(res) == 1) {
publishProgress(1);
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
However its hard to be sure. publishProgress or getApplicationContext may have something throwing the NullPointerException as well. Try this for debugging the problem : since you're using eclipse, you can use debugger instead of println, its way more powerful. A useful tutorial. If you don't want to use the debugger, print the values instead of numbers. They'll provide much more useeful context.

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

Android ArrayList json connect

In my app,I have used ArrayList to display the value.From the ArrayList,values are taken and through JSON results are displayed.But the application is not displaying the value.
I am uploading the code please check and if there any error please help.
actvity
String klno;
TextView tv101;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_karmic_lesson = "http://iascpl.com/app/get_karmic_lesson.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_KARMIC = "karmic";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstactivity_xm);
new GetProductDetails().execute();
//tv1.setText("");
//for (int j = 0; j < list.size(); j++){
// tv1.append("KarmicLesson " + list.get(j) + "\n");
//}
TextView tv2 = (TextView) findViewById (R.id.textView2);
tv2.setText(getIntent().getStringExtra("name2"));
}
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FirstActivity.this);
pDialog.setMessage("Loading the result... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... args)
{
ArrayList<Integer> klno = getIntent().getIntegerArrayListExtra("sum1");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("klno", String.valueOf(klno)));
JSONObject json = jsonParser.makeHttpRequest(
url_karmic_lesson, "GET", params);
Log.d("Single Product Details", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
final JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
final TextView tv1 = (TextView) findViewById (R.id.textView1);
final ArrayList<Integer> klno1 = getIntent().getIntegerArrayListExtra("sum1");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
try {
//tv1.setText("");
//for (int j = 0; j < list.size(); j++){
// tv1.append("KarmicLesson " + list.get(j) + "\n");
//}
tv1.setText("");
for (int j = 0; j < klno1.size(); j++){
tv1.setText(product.getString(TAG_KARMIC));
}} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
logcat
12-12 12:51:34.797: I/Process(9856): Sending signal. PID: 9856 SIG: 9
12-12 12:59:23.098: D/gralloc_goldfish(10054): Emulator without GPU emulation detected.
12-12 12:59:27.527: D/InputEventConsistencyVerifier(10054): KeyEvent: ACTION_UP but key was not down.
12-12 12:59:27.527: D/InputEventConsistencyVerifier(10054): in android.widget.EditText{40d10060 VFED..CL .F....I. 80,85-400,144 #7f080001 app:id/editText2}
12-12 12:59:27.527: D/InputEventConsistencyVerifier(10054): 0: sent at 27507962000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=27507962, downTime=27507855, deviceId=0, source=0x101 }
12-12 12:59:27.667: D/dalvikvm(10054): GC_CONCURRENT freed 88K, 8% free 2683K/2892K, paused 78ms+12ms, total 225ms
12-12 12:59:37.727: I/Choreographer(10054): Skipped 30 frames! The application may be doing too much work on its main thread.
12-12 12:59:42.397: D/dalvikvm(10054): GC_FOR_ALLOC freed 139K, 9% free 2859K/3120K, paused 558ms, total 599ms
12-12 12:59:42.517: I/dalvikvm-heap(10054): Grow heap (frag case) to 3.513MB for 635812-byte allocation
12-12 12:59:42.867: D/dalvikvm(10054): GC_FOR_ALLOC freed 2K, 8% free 3478K/3744K, paused 348ms, total 348ms
12-12 12:59:43.638: D/dalvikvm(10054): GC_CONCURRENT freed 14K, 8% free 3473K/3744K, paused 18ms+76ms, total 774ms
doing too much work on its main thread.
12-12 13:00:34.857: D/Single Product Details(10054): {"message":"No product found","success":0}
12-12 13:00:38.547: I/Choreographer(10054): Skipped 38 frames! The application may be doing too much work on its main thread.

what the error in this code to get json data? [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
android.os.NetworkOnMainThreadException . Need to use async task?
(2 answers)
Closed 9 years ago.
What is the error in this code?
I would like to add a facebook page name and get its json data, but there is something error I cannot discover. These are all files I use and added logcat messages:
PagesActivity.java
package com.engahmedphp.facebookcollector;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PagesActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
final Button button = (Button) findViewById(R.id.addPage);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(
PagesActivity.this);
alert.setTitle("Add New Page");
alert.setMessage("Enter Page Name OR Valid Facebook Link");
// Set an EditText view to get user input
final EditText input = new EditText(PagesActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
// Do something with value!
String url = "http://graph.facebook.com/"
+ value + "/?fields=picture,name";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json
.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
// addPageData(value);
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
}
void addPageData(String pageName) {
String url = "http://graph.facebook.com/" + pageName
+ "/?fields=picture,name";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
}
JSONParser.java
package com.engahmedphp.facebookcollector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
LogCat
08-31 03:35:23.031: D/dalvikvm(15972): GC_FOR_ALLOC freed 39K, 6% free 2633K/2792K, paused 65ms, total 68ms
08-31 03:35:23.041: I/dalvikvm-heap(15972): Grow heap (frag case) to 3.767MB for 1136500-byte allocation
08-31 03:35:23.163: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 5% free 3740K/3904K, paused 116ms, total 116ms
08-31 03:35:23.511: D/gralloc_goldfish(15972): Emulator without GPU emulation detected.
08-31 03:35:26.611: I/Choreographer(15972): Skipped 30 frames! The application may be doing too much work on its main thread.
08-31 03:39:40.903: D/dalvikvm(15972): GC_FOR_ALLOC freed 47K, 4% free 4013K/4180K, paused 48ms, total 81ms
08-31 03:39:40.903: I/dalvikvm-heap(15972): Grow heap (frag case) to 4.638MB for 635812-byte allocation
08-31 03:39:41.023: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 4% free 4631K/4804K, paused 111ms, total 111ms
08-31 03:39:41.483: I/Choreographer(15972): Skipped 83 frames! The application may be doing too much work on its main thread.
08-31 03:39:48.701: D/AndroidRuntime(15972): Shutting down VM
08-31 03:39:48.701: W/dalvikvm(15972): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
08-31 03:39:48.741: E/AndroidRuntime(15972): FATAL EXCEPTION: main
08-31 03:39:48.741: E/AndroidRuntime(15972): android.os.NetworkOnMainThreadException
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.engahmedphp.facebookcollector.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.engahmedphp.facebookcollector.PagesActivity$1$1.onClick(PagesActivity.java:49)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.Handler.dispatchMessage(Handler.java:99)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.Looper.loop(Looper.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.lang.reflect.Method.invoke(Method.java:525)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-31 03:39:48.741: E/AndroidRuntime(15972): at dalvik.system.NativeStart.main(Native Method)
You are getting NetworkOnMainThreadException. See How to fix android.os.NetworkOnMainThreadException? . This exception is thrown when an application attempts to perform a networking operation on its main (UI) thread. Do the networking tasks using AsyncTask or inside a new thread. See the Android Documentation on NetworkOnMainThreadException for reasons of this Exception.
Here:
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
you are doing network related stuff on main UI thread. Try to do this in a new thread.
The JSONParser make a HTTP connect in UI thread(The oneClick is invoked in UI thread)and it was fobidden now.
So you need move the network codes to other thread.
In case you have not noticed; StrictMode for network access results in a fatal error as for Android 3.0 (Honeycomb) or later, unless your app is targeting an API version before Honeycomb.
The right way of solving this is to use Android AsyncTask for network access.
The lazy way of handling this is to turn the check of:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
As others mentioned, you shouldn't be doing networking on UI thread to make your app UI responsive.
Try this
public class JsonParser extends AsyncTask<String, Void, JSONObject> {
InputStream is = null;
JSONObject jObj = null;
String json = "";
#Override
protected JSONObject doInBackground(String... params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json
.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Put the above class in your activity class, then use new JsonParser().execute(url); to fetch data and update the database.

Cursor is Null in Service Class - But Returns Value in Standalone Activity Class

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.

Categories