Good morning,
I'm trying to send two arrays (returned from getValuesGraph(doc) and getValuesFooter(doc) respectively) to the same function (OnPostExecute), I'm newbie at Java and Android and I don't now if the app code structure It's correct. So my apologies for the "disaster".
LogCat says:
02-21 00:07:25.852: W/dalvikvm(3282): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
02-21 00:07:25.862: E/AndroidRuntime(3282): FATAL EXCEPTION: main
02-21 00:07:25.862: E/AndroidRuntime(3282): java.lang.NullPointerException
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.example.kwhora1.MainActivity$BackGroundTask.onPostExecute(MainActivity.java:159)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.example.kwhora1.MainActivity$BackGroundTask.onPostExecute(MainActivity.java:1)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.Looper.loop(Looper.java:137)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.app.ActivityThread.main(ActivityThread.java:5041)
02-21 00:07:25.862: E/AndroidRuntime(3282): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 00:07:25.862: E/AndroidRuntime(3282): at java.lang.reflect.Method.invoke(Method.java:511)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-21 00:07:25.862: E/AndroidRuntime(3282): at dalvik.system.NativeStart.main(Native Method)
Here's the code:
package com.example.kwhora1;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
}
#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, menu);
return true;
}
class BackGroundTask extends AsyncTask<Void, Void, String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text(); // NUMBER MAX VALUE
values[5] = elements.get(5).text(); // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text(); // NUMBER MIN VALUE
return values;
}
#Override
public String[] doInBackground(Void... params) {
try {
URL url= new URL("http://www.mywebtoextractdata.com");
Document doc = Jsoup.connect(url.toString()).get();
getValuesGraph(doc);
getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] values) {
/*tvactualval.setText();*/
tvmax.setText(values[4]);
tvmid.setText(values[5]);
tvmin.setText(values[6]);
/*System.out.println(val[4]);*/
super.onPostExecute(values);
}
}
}
Thank you in advance for your help and time.
In String[] doInBackground(Void... params) { you are supposed to return a String array. So create one
String arr [] = new String [2];
and then add the result of getValuesGraph() to it.
arr[0] = getValuesGraph(doc);
arr[1] = getValuesFooter(doc);
then return then arr
Related
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.
I'm debugging an Asynctask that simply downloads a file: here the code:
public class AsyncDownloadFilesTask extends AsyncTask<String, Integer, Boolean> {
public AsyncResponse<Boolean> delegate=null;
protected Boolean doInBackground(String... params) {
android.os.Debug.waitForDebugger();
try {
URL url = new URL(params[0]);
int count;
String fileName = new String(params[1]);
URLConnection connessione = url.openConnection();
connessione.connect();
int lenghtOfFile = connessione.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileName);
long total = 0;
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return Boolean.valueOf(true);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Boolean result) {
delegate.processFinish(result);
}
}
I obtain a strange behaviour: when execution arrive to return
Boolean.valueOf(true);
it skips to
return null;
into the catch block, but Exception e is null, and then debugger goto line 1 of AsyncTask, that is simply
package com.example.compa.asynctasks;
Then execution goes on (executing onPostExecute method) and, of course, returned result is null
What happens? Why debug jump in this way?
Task download correctly the file.
Here code of the Activity that instantiates and calls Async Task
package com.example.compa.activities;
import android.app.Activity;
import ...
public class CoverActivity extends Activity implements AsyncResponse<Boolean>{
ImageView coverImg;
Drawable d;
CompassesFileManager cfm;
int coverId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cover);
coverId = getIntent().getExtras().getInt("coverId");
cfm = new CompassesFileManager(this);
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
d = cfm.getCover(coverId);
if (d!=null){
coverImg.setImageDrawable(d);
} else {
AsyncDownloadFilesTask task = new AsyncDownloadFilesTask();
task.delegate = this;
task.execute(cfm.getCoverURL(coverId), cfm.getCoverFileName(coverId));
}
}
#Override
public void processFinish(Boolean output) {
if (output){
Drawable d = cfm.getCover(coverId);
coverImg.setImageDrawable(d);
} else {
finish();
}
}
}
Stacktrace of error:
02-21 19:37:29.520: E/AndroidRuntime(407): FATAL EXCEPTION: main
02-21 19:37:29.520: E/AndroidRuntime(407): java.lang.NullPointerException
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:1)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Looper.loop(Looper.java:176)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.app.ActivityThread.main(ActivityThread.java:5419)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-21 19:37:29.520: E/AndroidRuntime(407): at dalvik.system.NativeStart.main(Native Method)
line:
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
is the last one of AsyncDownloadFilesTask class, and is a closing bracket, }
Thank you
I don't have enough points to comment, but it looks like delegate is null in your onPostExecute
delegate.processFinish(result); // delegate is null
if that's not the case, you're code stub above doesn't define it though.
I solved on my own.
1st, I move call to the Async Task in the onStart() method, instead of onCreate()
2nd, I made a mistake, in change line
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
in
coverImg = (ImageView)findViewById(R.id.cover_image);
to avoid a stupid null pointer (I already declared coverImg)!
Anyway, I still don't understand debug's behaviour, but I solved my problem.
Thank you everybody
this code should parse the xml and show it ! but it has exeption :
02-02 12:36:49.508: I/Choreographer(1184): Skipped 32 frames! The application may be doing too much work on its main thread.
02-02 12:36:50.926: W/System.err(1184): java.lang.NullPointerException
02-02 12:36:50.926: W/System.err(1184): at com.example.sample.itcuties.android.reader.ITCutiesReaderAppActivity.onCreate(ITCutiesReaderAppActivity.java:52)
02-02 12:36:50.946: W/System.err(1184): at android.app.Activity.performCreate(Activity.java:5008)
02-02 12:36:50.946: W/System.err(1184): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
02-02 12:36:50.946: W/System.err(1184): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
02-02 12:36:50.966: W/System.err(1184): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-02 12:36:50.966: W/System.err(1184): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-02 12:36:50.986: W/System.err(1184): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-02 12:36:50.986: W/System.err(1184): at android.os.Handler.dispatchMessage(Handler.java:99)
02-02 12:36:50.998: W/System.err(1184): at android.os.Looper.loop(Looper.java:137)
02-02 12:36:51.006: W/System.err(1184): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-02 12:36:51.018: W/System.err(1184): at java.lang.reflect.Method.invokeNative(Native Method)
02-02 12:36:51.026: W/System.err(1184): at java.lang.reflect.Method.invoke(Method.java:511)
02-02 12:36:51.026: W/System.err(1184): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-02 12:36:51.036: W/System.err(1184): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-02 12:36:51.036: W/System.err(1184): at dalvik.system.NativeStart.main(Native Method)
02-02 12:36:51.046: I/System.out(1184): xml activity Excpetion = java.lang.NullPointerException
02-02 12:36:51.736: I/Choreographer(1184): Skipped 39 frames! The application may be doing too much work on its main thread.
02-02 12:36:53.596: D/dalvikvm(1184): GC_CONCURRENT freed 180K, 4% free 8234K/8519K, paused 96ms+114ms, total 356ms
I cant find the reason!!!!
package com.example.sample.itcuties.android.reader;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Main application activity.
*
* #author ITCuties
*
*/
public class ITCutiesReaderAppActivity extends Activity {
NodeList nodeList;
/**
* This method creates main application view
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view
try{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
LongOperation lOp = new LongOperation(this);
lOp.execute("");
if(nodeList.getLength() > 0)
{
name = new TextView[nodeList.getLength()];
website = new TextView[nodeList.getLength()];
category = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = " + ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = " + ((Node) websiteList.item(0)).getNodeValue());
category[i].setText("Website Category = " + websiteElement.getAttribute("category"));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
}
/** Set the layout view to display */
setContentView(layout);
} catch (Exception e) {
System.out.println("xml activity Excpetion = " + e);
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
Context LongOperation;
public LongOperation(Context context){
this.LongOperation = context;
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("item");
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
LongOperation lOp = new LongOperation(this); lOp.execute("");
From this line, it seems you are filling nodeList in an AsyncTask, but instead of waiting for it to be filled, you start parsing it immediately. Make sure to start parsing from onPostExecuted in your LongOperation.
BTW, it would not be a bad idea to also do the parsing in the background.
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
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.