SAX parser raise some error - java

I got some issue with parsing, when I PHP based web service. I got stuck still from 2 day. I can't get any output in Activity. When I print it in Handler I got successfully print variable.
here are some logcate:
02-08 00:51:04.889: WARN/System.err(606): org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 805: not well-formed (invalid token)
02-08 00:51:04.893: WARN/System.err(606): at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:523)
02-08 00:51:04.893: WARN/System.err(606): at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:482)
02-08 00:51:04.893: WARN/System.err(606): at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:320)
02-08 00:51:04.893: WARN/System.err(606): at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:277)
02-08 00:51:04.893: WARN/System.err(606): at com.ESM.viewAllpartActivity.onCreate(viewAllpartActivity.java:69)
02-08 00:51:04.893: WARN/System.err(606): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-08 00:51:04.904: WARN/System.err(606): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-08 00:51:04.904: WARN/System.err(606): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-08 00:51:04.904: WARN/System.err(606): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-08 00:51:04.904: WARN/System.err(606): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-08 00:51:04.904: WARN/System.err(606): at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 00:51:04.914: WARN/System.err(606): at android.os.Looper.loop(Looper.java:123)
02-08 00:51:04.914: WARN/System.err(606): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-08 00:51:04.914: WARN/System.err(606): at java.lang.reflect.Method.invokeNative(Native Method)
02-08 00:51:04.914: WARN/System.err(606): at java.lang.reflect.Method.invoke(Method.java:521)
02-08 00:51:04.914: WARN/System.err(606): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-08 00:51:04.914: WARN/System.err(606): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-08 00:51:04.914: WARN/System.err(606): at dalvik.system.NativeStart.main(Native Method)
when I have call xml parsing.
here I have Past Code::-
package com.awe;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class viewAllpartActivity extends Activity implements
OnItemClickListener {
/** Called when the activity is first created. */
/* declare widgets */
String nickname;
String type;
boolean flag = true;
ListView lview3;
blog_list_adapter adapter;
String[] str_blogImage;
String[] str_blogtitle;
String[] str_morelink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_allparty);
Button home_logout;
final Intent homeintent;
homeintent = new Intent(viewAllpartActivity.this, MainActivity.class);
home_logout = (Button) findViewById(R.id.vap_logout);
home_logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(homeintent);
finish();
}
});
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"URL?api=ViewBooking_Admin");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
viewAllPartyHandler myXMLHandler = new viewAllPartyHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
viewAllPartydataset parsedLoginDataSet = myXMLHandler
.getParsedRegistrationData();
ArrayList<String> Bookingid = myXMLHandler.getbooking_id();
ArrayList<String> partyname = myXMLHandler.br3;
System.out.println("partyname :::: : "+partyname);
new xyz().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
viewAllpartActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please Wait...");
this.dialog.show();
this.dialog.setIndeterminate(true);
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"url?api=ViewBooking_Admin");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
viewAllPartyHandler myXMLHandler = new viewAllPartyHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
viewAllPartydataset parsedLoginDataSet = myXMLHandler
.getParsedRegistrationData();
ArrayList<String> Bookingid = myXMLHandler.getbooking_id();
ArrayList<String> partyname = myXMLHandler.br3;
System.out.println("partyname :::: : "+partyname);
/*str_blogImage = Bookingid.toArray(new String[Bookingid.size()]);
str_morelink = partyname.toArray(new String[partyname.size()]);*/
System.out.println("partyname :::: : "+partyname);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(final Void unused) {
lview3 = (ListView) findViewById(R.id.vap_listview);
/*lview3.setAdapter(new
ArrayAdapter<String>(viewAllpartActivity.this,android.R.layout.simple_list_item_1 ,
str_morelink));*/
lview3.setOnItemClickListener(viewAllpartActivity.this);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("str_morelink ::: " + arg2);
Bundle b = new Bundle();
b.putString("url", str_morelink[arg2]);
Intent i1 = new Intent(getBaseContext(), blogwebview.class);
i1.putExtras(b);
startActivity(i1);
// finish();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent homeback;
homeback = new Intent(viewAllpartActivity.this, home.class);
startActivity(homeback);
return true;
}
return super.onKeyDown(keyCode, event);
}
}

There is problem with your xml and specially wiht '&' chararcters so you could define a CDTA section to hold the value...

Looking at your example here, it's not well formed. It contains not encoded '&' chararcters.
The right solution is to change the XML generating process in order to get well-formed XML files.
But you can try a workaround by replacing all "&" with "&", in your whole file, before you parse it.

Related

Missing file through getAssets

I have a problem connected with reading a file in Java Application. Please help me as I'm trying to do it for four days and my CS teacher is not into Android Apps. Also any of the tutorials read does not help me.
I have a following app:
package com.bachosz.billionaires;
import android.support.v7.app.ActionBarActivity;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.StringTokenizer;
import android.content.ContextWrapper;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivityBillionaires extends ActionBarActivity {
private int currentQuestion;
private String [] answers;
private Button answerButton;
private Button questionButton;
private TextView questionView;
private TextView answerView;
private EditText answerText;
private Question [] questions;
private Button buttonA;
private Button buttonB;
private Button buttonC;
private Button buttonD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_billionaires);
try {
init();
} catch (IOException e) {
e.printStackTrace();
}
}
public void init() throws IOException
{
questions = new Question[2];
currentQuestion = 0;
InputStream inputStream = getResources().openRawResource(R.raw.questionstable);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
String content,a,b,c,d,correct;
int id, x = 0;
StringTokenizer st = null;
while ((line=reader.readLine()) != null)
{
st= new StringTokenizer(line, ",");
id = Integer.parseInt(st.nextToken());
content = st.nextToken();
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
d = st.nextToken();
correct = st.nextToken();
questions[x] = new Question(id, content, a, b, c, d, correct);
x++;
}
reader.close();
answerButton = (Button)findViewById(R.id.AnswerButton);
questionButton = (Button)findViewById(R.id.QuestionButton);
questionView = (TextView)findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
buttonA = (Button)findViewById(R.id.buttonA);
buttonB = (Button)findViewById(R.id.buttonB);
buttonC = (Button)findViewById(R.id.buttonC);
buttonD = (Button)findViewById(R.id.buttonD);
answerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
checkAnswer();
}});
questionButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showQuestion();
}});
}
public void showQuestion()
{
// if(currentQuestion == questions.length)
// currentQuestion =0;
questionView.setText(questions[0].toString());
answerView.setText("");
answerText.setText("");
currentQuestion++;
}
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(questions[currentQuestion].getCorrect()));
}
public void checkRight()
{
// String right
}
public void checkAnswer()
{
String answer = questions[currentQuestion].getCorrect();
if(isCorrect(answer))
answerView.setText("You're right!");
else
answerView.setText("Sorry, the correct answer is "+answers[currentQuestion]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_billionaires, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It is taken from Java application I was writing previously (that is why so many comments). How I can access the fileName in Android App? I was trying InputStream, get Assets, etc. but It does not work or I am doing it improperly. Currently it is throwing NullPointerException.
LOG CAT:
10-09 13:38:37.663: E/Trace(921): error opening trace file: No such file or directory (2)
10-09 13:38:39.354: D/AndroidRuntime(921): Shutting down VM
10-09 13:38:39.354: W/dalvikvm(921): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-09 13:38:39.384: E/AndroidRuntime(921): FATAL EXCEPTION: main
10-09 13:38:39.384: E/AndroidRuntime(921): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bachosz.billionaires/com.bachosz.billionaires.MainActivityBillionaires}: java.lang.NullPointerException
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.os.Looper.loop(Looper.java:137)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-09 13:38:39.384: E/AndroidRuntime(921): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 13:38:39.384: E/AndroidRuntime(921): at java.lang.reflect.Method.invoke(Method.java:511)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-09 13:38:39.384: E/AndroidRuntime(921): at dalvik.system.NativeStart.main(Native Method)
10-09 13:38:39.384: E/AndroidRuntime(921): Caused by: java.lang.NullPointerException
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.readFile(MainActivityBillionaires.java:111)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.init(MainActivityBillionaires.java:140)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.onCreate(MainActivityBillionaires.java:70)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.Activity.performCreate(Activity.java:5008)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-09 13:38:39.384: E/AndroidRuntime(921): ... 11 more
The error says you're getting a NPE (Null Pointer Exception) at com.bachosz.billionaires.MainActivityBillionaires. You need to look at the code section that you use to call that activity. (it is not in your code above - or else we don't know which line with the given information)
Another thing you have to make sure is that you have the appropriate context.
AssetManager assetManage = appContext.getAssets();
String[] filelist = assetManage.list("");
First you should clean up your code, at least to show it here where we don't know what are you doing.
It's easier to understand.
Why are you using assets? In Android the most common way to access resources is the .../res/raw folder.
It makes a reference of the file in the autogenerated R.class so you can access it anywhere.
Make sure your filename is lowercase and has no spaces. If you haven't raw folder under res, create it manually.
Try this:
InputStream inputStream = getResources().openRawResource(R.raw.YOURFILE);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null)
{
// Read file.
}
Firstly: copy YOURFILE to assets folder.
Then, AssetManager assetManage = getAssets();
Then,
InputStream myInput = null;
try {
myInput = assetManager.open("YOURFILE");
} catch (IOException e1) {
e1.printStackTrace();
}
And finally BufferedReader reader = new BufferedReader(new InputStreamReader(myInput));
follow the above code step by step.

XML parsing failure

I am writing an application for XML parser in android But when I download the code and run it, it runs perfectly ,
But I wrote the same code but not working, Why so?
Is there any prerequisite for that? Please help me with this
I am getting an error in XMLParser.java
package com.xmlparser;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
My Log Cat
11-22 15:35:53.675: E/AndroidRuntime(19208): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xmlparser/com.xmlparser.Xparser}: android.os.NetworkOnMainThreadException
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread.access$600(ActivityThread.java:140)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.os.Handler.dispatchMessage(Handler.java:99)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.os.Looper.loop(Looper.java:137)
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.app.ActivityThread.main(ActivityThread.java:4898)
11-22 15:35:53.675: E/AndroidRuntime(19208): at java.lang.reflect.Method.invokeNative(Native Method)
11-22 15:35:53.675: E/AndroidRuntime(19208): at java.lang.reflect.Method.invoke(Method.java:511)
11-22 15:35:53.675: E/AndroidRuntime(19208): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
11-22 15:35:53.675: E/AndroidRuntime(19208): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
11-22 15:35:53.675: E/AndroidRuntime(19208): at dalvik.system.NativeStart.main(Native Method)
11-22 15:35:53.675: E/AndroidRuntime(19208): Caused by: android.os.NetworkOnMainThreadException
11-22 15:35:53.675: E/AndroidRuntime(19208): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
11-22 15:19:21.500: E/AndroidRuntime(16631): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-22 15:19:21.500: E/AndroidRuntime(16631): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-22 15:19:21.500: E/AndroidRuntime(16631): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
11-22 15:19:21.500: E/AndroidRuntime(16631): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-22 15:19:21.500: E/AndroidRuntime(16631): at com.xmlparser.XMLParser.getXmlFromUrl(XMLParser.java:45)
11-22 15:19:21.500: E/AndroidRuntime(16631): at com.xmlparser.Xparser.onCreate(Xparser.java:37)
11-22 15:19:21.500: E/AndroidRuntime(16631): at android.app.Activity.performCreate(Activity.java:5206)
11-22 15:19:21.500: E/AndroidRuntime(16631): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
11-22 15:19:21.500: E/AndroidRuntime(16631): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
this is my Xparser.java
package com.xmlparser;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Xparser extends ListActivity {
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML key nodes
static final String KEY_ITEM = "item";
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xmlparser);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);// getting XML
Document doc = parser.getDomElement(xml);// getting Dom Element
NodeList n1 = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for(int i=0 ; i < n1.getLength(); i++){
HashMap<String,String> map = new HashMap<String,String>();
Element e = (Element) n1.item(i);
//adding each child to Hashmap node key
map.put(KEY_ID, parser.getValue(e,KEY_ID));
map.put(KEY_NAME, parser.getValue(e,KEY_NAME));
map.put(KEY_COST, "Rs."+ parser.getValue(e,KEY_COST));
map.put(KEY_DESC, parser.getValue(e,KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_select_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String desc = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
Intent in = new Intent();
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_DESC, desc);
in.putExtra(KEY_COST, cost);
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.xmlparser, menu);
return true;
}
}
The exception tells you everything you need to know. You are trying to submit data on the main thread. Do the networking operations in a separate thread.
There's a link in the docs that explains it, and this might help you to move on.

Unable to retrieve the value of textfield

i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}

Java NullPointer loading remote image to android gallery with imageadapter

Hello i am trying to load images from a server into a gallery but always keep giving me this error:
04-28 00:54:47.596: W/dalvikvm(715): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-28 00:54:47.608: E/AndroidRuntime(715): FATAL EXCEPTION: main
04-28 00:54:47.608: E/AndroidRuntime(715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.plateamobile/com.plateamobile.ProdDetails}: java.lang.NullPointerException
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.os.Looper.loop(Looper.java:123)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-28 00:54:47.608: E/AndroidRuntime(715): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 00:54:47.608: E/AndroidRuntime(715): at java.lang.reflect.Method.invoke(Method.java:521)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-28 00:54:47.608: E/AndroidRuntime(715): at dalvik.system.NativeStart.main(Native Method)
04-28 00:54:47.608: E/AndroidRuntime(715): Caused by: java.lang.NullPointerException
04-28 00:54:47.608: E/AndroidRuntime(715): at com.plateamobile.ProdDetails.set_info(ProdDetails.java:138)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.plateamobile.ProdDetails.onCreate(ProdDetails.java:49)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-28 00:54:47.608: E/AndroidRuntime(715): ... 11 more
This is my code:
package com.plateamobile;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.Gallery.LayoutParams;
public class ProdDetails extends Activity {
private ImageSwitcher mSwitcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prod_details);
Bundle extras = getIntent().getExtras();
((TextView)findViewById(R.id.prod_name)).setText(extras.getString("name"));
((TextView)findViewById(R.id.price_prod)).setText(new general().formatNumb(extras.getString("price")));
set_info();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.prod_details, menu);
return true;
}
public void set_info(){
ObjConexion object = new ObjConexion();
SoapObject request = new SoapObject(object.NameSpace(), "getProdinfo");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
Bundle extras = getIntent().getExtras();
PropertyInfo idPro =new PropertyInfo();
idPro.setName("id");
idPro.setValue(extras.getString("id"));
idPro.setType(String.class);
request.addProperty(idPro);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(object.Url());
androidHttpTransport.debug = true;
try {
androidHttpTransport.call("getProdinfo", envelope);
List<SoapPrimitive> response = (List<SoapPrimitive>) envelope.getResponse();
((TextView)findViewById(R.id.commerce)).setText(response.get(0).toString());
((TextView)findViewById(R.id.description)).setContentDescription(response.get(1).toString());
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(this,e.getMessage().toString(),Toast.LENGTH_LONG).show();
}
request = new SoapObject(object.NameSpace(), "getProdImg");
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
idPro =new PropertyInfo();
idPro.setName("id");
idPro.setValue(extras.getString("id"));
idPro.setType(Integer.class);
request.addProperty(idPro);
envelope.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(object.Url());
androidHttpTransport.debug = true;
ArrayList<SoapObject> imagesList = new ArrayList<SoapObject>();
try {
androidHttpTransport.call("getProdImg", envelope);
List<SoapObject> response = (List<SoapObject>) envelope.getResponse();
for (int cont=0; cont<response.size() ;cont++){
SoapObject responseChild = (SoapObject) response.get(cont);
imagesList.add(responseChild);
}
}catch (Exception e) {
e.printStackTrace();
if (e.getMessage() == null){
Toast.makeText(this,"Error en la conexion",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,e.getMessage().toString(),Toast.LENGTH_LONG).show();
}
}
Gallery _gallery_ = (Gallery) findViewById(R.id.images_prod);
if (imagesList!=null){
_gallery_.setAdapter(new ImageAdapter(getApplicationContext(), imagesList));
}else{
Log.e("DEBUGTAG", "Remtoe Image Exception");
}
}
public void goBack(View v){
Intent intent = new Intent(ProdDetails.this, main_win.class);
startActivity(intent);
}
public class ImageAdapter extends BaseAdapter {
/** The parent context */
private Context myContext;
/** URL-Strings to some remote images. */
private ArrayList<SoapObject> pckg_data;
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c, ArrayList<SoapObject> data) {
this.myContext = c;
this.pckg_data = data;
}
/** Returns the amount of images we have defined. */
public int getCount() { return this.pckg_data.size(); }
/* Use the array-Positions as unique IDs */
public Object getItem(int position) { return position; }
public long getItemId(int position) { return position; }
/** Returns a new ImageView to
* be displayed, depending on
* the position passed. */
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(pckg_data.get(position).getPropertyAsString(1));
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
/* Apply the Bitmap to the ImageView that will be returned. */
i.setImageBitmap(bm);
} catch (IOException e) {
Log.e("DEBUGTAG", "Remtoe Image Exception", e);
}
/* Image should be scaled as width/height are set. */
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
/* Set the Width/Height of the ImageView. */
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
return i;
}
/** Returns the size (0.0f to 1.0f) of the views
* depending on the 'offset' to the center. */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
}
The first time your app is created there is no intent calling it. So Bundle extras = getIntent().getExtras(); causes the NullPointerException.
Enclose the statement in a try block.
try
{
Bundle extras = getIntent().getExtras();
}
catch(Exception E){
//do nothing
}
But this isn't the right way to do it.
If this activity is going to be called again, I suggest you use onNewIntent() method and make this activity singleTop.
http://developer.android.com/reference/android/app/Activity.html
http://developer.android.com/guide/topics/manifest/activity-element.html

Cannot Resolve NullPointerException On Service Class

I have been tasked to resolve an issue for a group project at my university however I cannot seem to resolve an issue with a NullPointerException in my service class. Our goal is to create a script which continually monitors the android history until it finds a match - then executes a warning class if the service class finds a match in the browser history. The issue occurs on line 71 (of service class) however I do not know how to resolve the issue.
Service Class:
public class Service_class extends Service {
String Dirty1 = "www.pornhub.com";
String Dirty2 = "www.playboy.com";
String Dirty3 = "www.playboy.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();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
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(Service_class.this, Warning.class);
Service_class.this.startActivity(intent);
}
} while (cursor.moveToNext());
// tv.setText(urls);
}
}
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;
}}
Main.java
import java.util.Calendar;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Main.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
}}
LOGCAT:
04-15 13:58:49.980: D/AndroidRuntime(1994): Shutting down VM
04-15 13:58:50.000: W/dalvikvm(1994): threadid=1: thread exiting with uncaught exception (group=0x40cc7930)
04-15 13:58:50.000: E/AndroidRuntime(1994): FATAL EXCEPTION: main
04-15 13:58:50.000: E/AndroidRuntime(1994): java.lang.RuntimeException: Unable to create service com.nfc.linked.Service_class: java.lang.NullPointerException
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2539)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.access$1600(ActivityThread.java:141)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.os.Looper.loop(Looper.java:137)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-15 13:58:50.000: E/AndroidRuntime(1994): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 13:58:50.000: E/AndroidRuntime(1994): at java.lang.reflect.Method.invoke(Method.java:511)
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-15 13:58:50.000: E/AndroidRuntime(1994): at dalvik.system.NativeStart.main(Native Method)
04-15 13:58:50.000: E/AndroidRuntime(1994): Caused by: java.lang.NullPointerException
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.nfc.linked.Service_class.onCreate(Service_class.java:71)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2529)
04-15 13:58:50.000: E/AndroidRuntime(1994): ... 10 more
04-15 14:00:23.770: D/AndroidRuntime(2047): Shutting down VM
04-15 14:00:23.770: W/dalvikvm(2047): threadid=1: thread exiting with uncaught exception (group=0x40cc7930)
Your method managedQuery() returns null
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
So when you try to execute a method on null you will get a NullPointerException.
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null); // cursor will be null
String urls = "";
if (cursor.moveToFirst()) { // this will be NPE
Make your managedQuery() method return an instantiated Cursor object.

Categories