java.lang.NullPointerException xml parsing - java

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.

Related

An Error occurs when I was making a code to create a show list by ListView{in content_main.xml} like contact view

I was making a code to create a show list by ListView{in content_main.xml} like contact view.
I build a database in the (SQLite Expert Professional) with a table(name: "contact") that was contained a few name and family and numbers, with ID,NAME,fAMILY and PHONE NUMBER columns.
ID was unique, auto increment and primary key...other were Text except number that was CHAR.
then I calling them to my ListView as you see in below.(before it I made a row_list activity to made my listview , custom) but there was an Error and I can't find it.
{I could find my database.db file with that's table in the source data files that means my mistake wasn't from creating database.}
plz help me.I wanna learn android (as fast as i can) to get a JOB and I need it..
Errors.Android Monitor.Logcat
09-08 05:27:32.005 5692-5692/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x94c4fb20)
09-08 05:27:32.005 5692-5692/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: mizco.phonebook, PID: 5692
java.lang.RuntimeException: Unable to start activity ComponentInfo{mizco.phonebook/mizco.phonebook.Main}: android.database
.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at mizco.phonebook.database.getfulllist(database.java:97)
at mizco.phonebook.Main.onCreate(Main.java:36)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Main.java
package mizco.phonebook;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends AppCompatActivity {
private database db;
private String [][] res ;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
list = (ListView) findViewById(R.id.main_list);
db = new database(this);
db.startusing();
db.open();
res = db.getfulllist();
db.close();
list.setAdapter(new AA());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
class AA extends ArrayAdapter<String>{
public AA() {
super(Main.this, R.layout.row_list, res[0]);
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater in = getLayoutInflater();
View row = in.inflate(R.layout.row_list,parent,false);
TextView name = (TextView) row.findViewById(R.id.row_name);
TextView number = (TextView) row.findViewById(R.id.row_number);
name.setText(res[0][position]+" "+res[1][position]);
number.setText(res[2][position]);
return row;
}
}
}
Class : database.java
package mizco.phonebook;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Mahdi on 9/2/2017.
*/
public class database extends SQLiteOpenHelper {
public static String dbname= "database";
public static String dbpath="";
private Context mctxt;
private SQLiteDatabase mydb;
public database(Context context) {
super(context, dbname, null, 1);
mctxt = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private boolean existdatabase(){
File m312 = new File(dbpath+dbname);
return m312.exists();
}
private void copydatabase(){
try {
InputStream IS = mctxt.getAssets().open(dbname);
OutputStream OS = new FileOutputStream(dbpath+dbname);
byte[] buffer = new byte[1024];
int length;
while ((length = IS.read(buffer))>0){
OS.write(buffer,0,length);
}
OS.flush();
OS.close();
IS.close();
} catch (Exception e) {
}
}
public void open(){
mydb = SQLiteDatabase.openDatabase(dbpath+dbname, null, SQLiteDatabase.OPEN_READWRITE);
}
public void close(){
mydb.close();
}
public void startusing () {
dbpath = mctxt.getFilesDir().getParent() + "/databases/";
if (!existdatabase()) {
this.getWritableDatabase();
copydatabase();
}
}
public String[][] getfulllist(){
Cursor cu = mydb.rawQuery("select * from Contact",null);
String [][] r = new String[3][cu.getCount()];
for (int i= 0;i<=cu.getCount();i++){
cu.moveToPosition(i);
r[0][i]=cu.getString(1);
r[1][i]=cu.getString(2);
r[2][i]=cu.getString(3);
}
return r;
}
}
You're stepping off the end of the cursor. Your code should read
for (int i= 0;i < cu.getCount();i++){
cu.moveToPosition(i);
r[0][i]=cu.getString(1);
r[1][i]=cu.getString(2);
r[2][i]=cu.getString(3);
}
return r;

android app crashes when killing one activity and start another one

There is one button I set in Scene2.java.I want to use the button to get in other activities Scene3.java,GameOver.java Everything worked fine until its about to open the new activity,every time the app crashed there. I want to know if there're any mistake I made in the connection,which I mean the newIntent and getIntent inScene2.java GameOver.javaand Scene3.java
Scene2.java
package com.group5.littlered;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Scene2 extends Activity {
MediaPlayer bird;
MediaPlayer bgm;
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
final String[] ListStr = { "Wake up and ask her", "Peek her secretly" };
int plot = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene2);
Intent intent1 = getIntent();
conversation = getResources().getStringArray(R.array.scene2);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 2) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
if (plot < 1) {
AlertDialog choice = new AlertDialog.Builder(
Scene2.this).create();
choice.setTitle("Pick a choice");
choice.setMessage(" ");
choice.setButton("Get up and ask her what happened",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 1;
}
});
choice.setButton2("Peek her secretly",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 2;
position = 4;
}
});
choice.show();
} else {
if (plot < 2) {
if (position < 4) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent2 = new Intent(Scene2.this,
GameOver.class);
startActivity(intent2);
finish();
}
} else {
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent3 = new Intent(Scene2.this,
Scene3.class);
startActivity(intent3);
finish();
}
}
}
}
}
});
// BGM
bgm = MediaPlayer.create(Scene2.this, R.raw.voyager);
bgm.setLooping(true);
bgm.start();
// bird
bird = MediaPlayer.create(Scene2.this, R.raw.bird);
bird.setLooping(false);
bird.start();
}
}
Scene3.java
package com.group5.littlered;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Scene3 extends Activity {
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene3);
Intent intent3 = getIntent();
conversation = getResources().getStringArray(R.array.scene1);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
{
}
}
}
});
}
}
Again sorry for my poor ENGLISH, plz tell me what I need to post more to help you understand my problem.
my logcat
04-30 09:37:39.497: E/AndroidRuntime(4862): FATAL EXCEPTION: main
04-30 09:37:39.497: E/AndroidRuntime(4862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group5.littlered/com.group5.littlered.Scene3}: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Looper.loop(Looper.java:137)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invoke(Method.java:525)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-30 09:37:39.497: E/AndroidRuntime(4862): at dalvik.system.NativeStart.main(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): Caused by: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.group5.littlered.Scene3.onCreate(Scene3.java:45)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Activity.performCreate(Activity.java:5133)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-30 09:37:39.497: E/AndroidRuntime(4862): ... 11 more
The line that is crashing is the line 45 of Scene3:
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() { // <-- THIS ONE
...
});
The cause is a NullPointerException. This means that the identifier "wtf" exists in R (this wouldn't compile otherwise) but is not found in the layer activity_scene3, as we wave the following statement line 38 of Scene3.onCreate():
setContentView(R.layout.activity_scene3); // and later on findViewById() returns `null`
You have to revisit this layout to ensure that the Button you are willing to access to actually exists, with the ID wtf.
Generally speaking, this is the danger in using a same ID in different layouts. This is prone to hide errors that would easily be found otherwise as this would just not compile.
Check your manifest file and add Scene3.java in it
<activity
android:name=".Scene3" >
</activity>
Always post question with exception, second this is may be you have not mention your other activity in manifest file like:
<activity
android:name=".Scene3">
</activity>
<activity
android:name=".GameOver">
</activity>

Structure and sending two arrays to the same receiving function

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

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.

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

Categories