Can't read the same file in another activity - java

I have this code witch returns the content of a file:
private ArrayList<String> readFromFile1(Context context) {
ArrayList<String> list = new ArrayList<String>();
try {
ObjectInputStream ois = new ObjectInputStream( context.openFileInput("jokesNames2.bjk"));
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
I'm calling it like that:
System.out.println("FILE CONTENT: " + readFromFile1(this));
and everything runs just purfect.
Now In another activity I'm using almost the same code, but it wont run.
Here it is:
#SuppressLint("NewApi")
public class FavoriteJokes extends Activity {
public static ArrayAdapter<String> adapter;
public static ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_jokes);
final GlobalsHolder globals = (GlobalsHolder)getApplication();
TextView text = (TextView) findViewById(R.id.txtJoke);
text.setText(globals.getList().get(globals.clickedPosition));
ArrayList<String> jokeNamesList = new ArrayList<String>();
jokeNamesList.addAll(readFromFile1(this));
System.out.println("FILE CONTENT: " + readFromFile1(this));
globals.setFavJokeNamesList(readFromFile1(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favorite_jokes, menu);
return true;
}
/* Read file's content */
private ArrayList<String> readFromFile1(Context context) {
ArrayList<String> list = new ArrayList<String>();
try {
ObjectInputStream ois = new ObjectInputStream( context.openFileInput("jokesNames2.bjk"));
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
}
And here is the error output:
03-03 10:50:21.055: E/AndroidRuntime(1038): FATAL EXCEPTION: main
03-03 10:50:21.055: E/AndroidRuntime(1038): Process: com.gs.britishjokes, PID: 1038
03-03 10:50:21.055: E/AndroidRuntime(1038): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gs.britishjokes/com.gs.britishjokes.FavoriteJokes}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.app.ActivityThread.access$700(ActivityThread.java:135)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.os.Handler.dispatchMessage(Handler.java:102)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.os.Looper.loop(Looper.java:137)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.app.ActivityThread.main(ActivityThread.java:4998)
03-03 10:50:21.055: E/AndroidRuntime(1038): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 10:50:21.055: E/AndroidRuntime(1038): at java.lang.reflect.Method.invoke(Method.java:515)
03-03 10:50:21.055: E/AndroidRuntime(1038): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-03 10:50:21.055: E/AndroidRuntime(1038): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-03 10:50:21.055: E/AndroidRuntime(1038): at dalvik.system.NativeStart.main(Native Method)
03-03 10:50:21.055: E/AndroidRuntime(1038): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-03 10:50:21.055: E/AndroidRuntime(1038): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
03-03 10:50:21.055: E/AndroidRuntime(1038): at java.util.ArrayList.get(ArrayList.java:308)
03-03 10:50:21.055: E/AndroidRuntime(1038): at com.gs.britishjokes.FavoriteJokes.onCreate(FavoriteJokes.java:31)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.app.Activity.performCreate(Activity.java:5243)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-03 10:50:21.055: E/AndroidRuntime(1038): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
03-03 10:50:21.055: E/AndroidRuntime(1038): ... 11 more
I really can't understand what is wrong with my code. I'm pretty sure that I'm missing a really small part, but I'm unable to find it. Can you give me a push?

The error log (logcat) indicates an IndexOutOfBoundsException exception: an access to element 0 of an empty array.
It seems to be this line that cause the problem: text.setText(globals.getList().get(globals.clickedPosition));
Maybee you can check the size of globals.getList() ?

Related

Java Apache POI error inserting spreadsheet Picture

I'm trying to insert an image in a sheet using Apache POI, but I'm getting the following error:
03-03 20:21:50.898: E/SELinux(28413): selinux_android_seapp_context_reload: Error reading /seapp_contexts, line 16, name levelFrom, value container
03-03 20:21:50.908: D/dalvikvm(28413): Late-enabling CheckJNI
03-03 20:21:51.668: D/libEGL(28413): loaded /vendor/lib/egl/libEGL_adreno.so
03-03 20:21:51.678: D/libEGL(28413): loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
03-03 20:21:51.708: D/libEGL(28413): loaded /vendor/lib/egl/libGLESv2_adreno.so
03-03 20:21:51.718: I/Adreno-EGL(28413): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_3.2_RB3.04.03.00.134.050_msm8610_JB_3.2_RB3__release_AU ()
03-03 20:21:51.718: I/Adreno-EGL(28413): OpenGL ES Shader Compiler Version: 20.00.02
03-03 20:21:51.718: I/Adreno-EGL(28413): Build Date: 11/12/13 Tue
03-03 20:21:51.718: I/Adreno-EGL(28413): Local Branch:
03-03 20:21:51.718: I/Adreno-EGL(28413): Remote Branch: quic/jb_3.2_rb3.21
03-03 20:21:51.718: I/Adreno-EGL(28413): Local Patches: NONE
03-03 20:21:51.718: I/Adreno-EGL(28413): Reconstruct Branch: AU_LINUX_ANDROID_JB_3.2_RB3.04.03.00.134.050 + NOTHING
03-03 20:21:51.978: D/OpenGLRenderer(28413): Enabling debug mode 0
03-03 20:21:52.518: W/IInputConnectionWrapper(28413): getExtractedText on inactive InputConnection
03-03 20:21:52.528: W/IInputConnectionWrapper(28413): getTextBeforeCursor on inactive InputConnection
03-03 20:21:52.538: W/IInputConnectionWrapper(28413): getSelectedText on inactive InputConnection
03-03 20:21:52.538: W/IInputConnectionWrapper(28413): getTextAfterCursor on inactive InputConnection
03-03 20:21:58.468: E/SpannableStringBuilder(28413): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-03 20:21:58.468: E/SpannableStringBuilder(28413): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-03 20:21:58.978: E/SpannableStringBuilder(28413): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-03 20:21:58.978: E/SpannableStringBuilder(28413): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-03 20:22:02.368: D/dalvikvm(28413): GC_FOR_ALLOC freed 235K, 11% free 9609K/10696K, paused 15ms, total 15ms
03-03 20:22:02.418: D/dalvikvm(28413): GC_FOR_ALLOC freed 11K, 9% free 10061K/10972K, paused 13ms, total 13ms
03-03 20:22:02.458: D/dalvikvm(28413): GC_FOR_ALLOC freed 9K, 8% free 10532K/11424K, paused 15ms, total 15ms
03-03 20:22:02.928: D/dalvikvm(28413): GC_FOR_ALLOC freed 734K, 13% free 11166K/12760K, paused 24ms, total 24ms
03-03 20:22:03.398: W/dalvikvm(28413): Exception Ljava/lang/RuntimeException; thrown while initializing Lorg/apache/poi/ddf/DefaultEscherRecordFactory;
03-03 20:22:03.398: D/AndroidRuntime(28413): Shutting down VM
03-03 20:22:03.398: W/dalvikvm(28413): threadid=1: thread exiting with uncaught exception (group=0x41d23898)
03-03 20:22:03.428: E/AndroidRuntime(28413): FATAL EXCEPTION: main
03-03 20:22:03.428: E/AndroidRuntime(28413): java.lang.IllegalStateException: Could not execute method of the activity
03-03 20:22:03.428: E/AndroidRuntime(28413): at android.view.View$1.onClick(View.java:3839)
03-03 20:22:03.428: E/AndroidRuntime(28413): at android.view.View.performClick(View.java:4476)
03-03 20:22:03.428: E/AndroidRuntime(28413): at android.view.View$PerformClick.run(View.java:18795)
03-03 20:22:03.428: E/AndroidRuntime(28413): at android.os.Handler.handleCallback(Handler.java:730)
03-03 20:22:03.428: E/AndroidRuntime(28413): at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 20:22:03.428: E/AndroidRuntime(28413): at android.os.Looper.loop(Looper.java:176)
03-03 20:22:03.428: E/AndroidRuntime(28413): at android.app.ActivityThread.main(ActivityThread.java:5493)
03-03 20:22:03.428: E/AndroidRuntime(28413): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 20:22:03.428: E/AndroidRuntime(28413): at java.lang.reflect.Method.invoke(Method.java:525)
03-03 20:22:03.428: E/AndroidRuntime(28413): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
03-03 20:22:03.428: E/AndroidRuntime(28413): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
03-03 20:22:03.428: E/AndroidRuntime(28413): at dalvik.system.NativeStart.main(Native Method)
03-03 20:22:03.428: E/AndroidRuntime(28413): Caused by: java.lang.reflect.InvocationTargetException
03-03 20:22:03.428: E/AndroidRuntime(28413): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 20:22:03.428: E/AndroidRuntime(28413): at java.lang.reflect.Method.invoke(Method.java:525)
03-03 20:22:03.428: E/AndroidRuntime(28413): at android.view.View$1.onClick(View.java:3834)
03-03 20:22:03.428: E/AndroidRuntime(28413): ... 11 more
03-03 20:22:03.428: E/AndroidRuntime(28413): Caused by: java.lang.ExceptionInInitializerError
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.hssf.record.AbstractEscherHolderRecord.convertToEscherRecords(AbstractEscherHolderRecord.java:78)
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.hssf.record.AbstractEscherHolderRecord.convertRawBytesToEscherRecords(AbstractEscherHolderRecord.java:73)
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.hssf.record.DrawingGroupRecord.processChildRecords(DrawingGroupRecord.java:79)
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.hssf.model.InternalWorkbook.findDrawingGroup(InternalWorkbook.java:2051)
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.hssf.usermodel.HSSFWorkbook.initDrawings(HSSFWorkbook.java:1588)
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.hssf.usermodel.HSSFWorkbook.addPicture(HSSFWorkbook.java:1608)
03-03 20:22:03.428: E/AndroidRuntime(28413): at pro.kondratev.androidreadxlsx.ReadXlsx.criar(ReadXlsx.java:136)
03-03 20:22:03.428: E/AndroidRuntime(28413): ... 14 more
03-03 20:22:03.428: E/AndroidRuntime(28413): Caused by: java.lang.RuntimeException: java.lang.NoSuchFieldException: RECORD_ID
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.ddf.DefaultEscherRecordFactory.recordsToMap(DefaultEscherRecordFactory.java:135)
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.ddf.DefaultEscherRecordFactory.<clinit>(DefaultEscherRecordFactory.java:42)
03-03 20:22:03.428: E/AndroidRuntime(28413): ... 21 more
03-03 20:22:03.428: E/AndroidRuntime(28413): Caused by: java.lang.NoSuchFieldException: RECORD_ID
03-03 20:22:03.428: E/AndroidRuntime(28413): at java.lang.Class.getField(Class.java:673)
03-03 20:22:03.428: E/AndroidRuntime(28413): at org.apache.poi.ddf.DefaultEscherRecordFactory.recordsToMap(DefaultEscherRecordFactory.java:129)
03-03 20:22:03.428: E/AndroidRuntime(28413): ... 22 more
Code is:
public void criar (View view) throws IOException {
String nome = ((String) txtnome.getText().toString());
String foto = ((String) txtstring.getText().toString());
FileInputStream input_document = new FileInputStream(new File("sdcard/projetos/enguelber/formulario.xls"));
HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
HSSFSheet sheet = my_xls_workbook.getSheetAt(0);
// Nome do cliente
Row row = sheet.getRow(7);
Cell cell = row.getCell(1);
String cliente = ((String) txtcliente.getText().toString());
cell.setCellValue(cliente);
// CPF do cliente
Row row1 = sheet.getRow(7);
Cell cell1 = row.getCell(7);
String cpf = ((String) txtcpf.getText().toString());
cell1.setCellValue(cpf);
// Hora
String hora = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss",
Locale.getDefault()).format(new Date());
Row row2 = sheet.getRow(35);
Cell cell2 = row2.getCell(1);
cell2.setCellValue(hora);
// Foto do relatorio
InputStream inputStream = new FileInputStream("sdcard/projetos/enguelber/fotos/02.03.2016 21.15.27.jpg");
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = my_xls_workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
inputStream.close();
CreationHelper helper = my_xls_workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize();
// foto
// Row row3 = sheet.getRow(13);
// Cell cell3 = row3.getCell(1);
// cell3.setCellValue(foto);
input_document.close();
FileOutputStream fileOut = null;
FileOutputStream output_file =new FileOutputStream(new File("sdcard/projetos/enguelber/"+ nome + ".xls"));
my_xls_workbook.write(output_file);
output_file.close();
}
The application works normally if I remove the lines:
InputStream inputStream = new FileInputStream("sdcard/projetos/enguelber/fotos/02.03.2016 21.15.27.jpg");
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = my_xls_workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
inputStream.close();
CreationHelper helper = my_xls_workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize();
Stack trace: http://freetexthost.com/qakvlvuxlm

Getting java.lang.ExceptionInIntiliazerError in Android

I'm very new to Android programming and I'm trying to write an Android app that would parse an OWL file (.owl file) and display the classes and subclasses. When ever the user clicks the button, the file is read from the assets folder of the Eclipse Project, the OWL file is parsed and the names of the classes are printed on to the console.
But whenever I click the button, the emulator crashes throwing the following exceptions:
02-23 16:49:36.430: E/AndroidRuntime(597): FATAL EXCEPTION: main
02-23 16:49:36.430: E/AndroidRuntime(597): java.lang.ExceptionInInitializerError
02-23 16:49:36.430: E/AndroidRuntime(597): at com.Sample.SampleApp.StartingPoint.parseOWLFile(StartingPoint.java:105)
02-23 16:49:36.430: E/AndroidRuntime(597): at com.Sample.SampleApp.StartingPoint$3.onClick(StartingPoint.java:68)
Here is my the Java code I wrote:
public class StartingPoint extends ActionBarActivity {
private static final int REQUEST_PATH = 1;
String currentFile;
EditText et1;
Button browse, ok, exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et1 = (EditText)findViewById(R.id.editText);
browse = (Button) findViewById(R.id.browseButton);
browse.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
getfile(v);
}
});
exit = (Button)findViewById(R.id.ExitButton);
exit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});
ok = (Button)findViewById(R.id.OKButton);
ok.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
parseOWLFile();
}
});
}
public void getfile(View view)
{
Intent i1 = new Intent(this, FileChooser.class);
startActivityForResult(i1, REQUEST_PATH);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == REQUEST_PATH)
{
if(resultCode == RESULT_OK)
{
currentFile = data.getStringExtra("GetFileName");
et1.setText(currentFile);
}
}
}
public void parseOWLFile()
{
//String file = et1.getText().toString(); //Uncomment this when using on phone/tablet
String file = "antibiotics.owl";
try
{
//System.out.println("File name is "+file);
//File f = new File(file);
InputStream fis = getAssets().open(file);
OntModel base = ModelFactory.createOntologyModel( OntModelSpec.OWL_DL_MEM );
base.read(fis, null);
String ns = base.getNsPrefixURI("Ontology");
Resource r = base.getResource(ns+" Concept");
OntClass theClass = r.as(OntClass.class);
Individual indiv = base.createIndividual(ns+"IndivTest", theClass);
for (Iterator<Resource> i = indiv.listRDFTypes(true); i.hasNext(); )
System.out.println( indiv.getURI() + " is asserted in class " + i.next() );
OntModel inf = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_MICRO_RULE_INF, base );
Individual ind = inf.getIndividual( ns + "indivTest" );
for (Iterator<Resource> i = ind.listRDFTypes(true); i.hasNext(); )
System.out.println( ind.getURI() + " is inferred to be in class " + i.next() );
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I have imported the AndroJena 0.5 version jars into my Eclipse Project.
Here are some more exceptions that I got:
02-23 16:49:36.430: E/AndroidRuntime(597): Caused by: java.lang.ExceptionInInitializerError
02-23 16:49:36.430: E/AndroidRuntime(597): at com.hp.hpl.jena.ontology.OntModelSpec.<clinit>(OntModelSpec.java:54)
02-23 16:49:36.430: E/AndroidRuntime(597): Caused by: java.lang.ExceptionInInitializerError
02-23 16:49:36.430: E/AndroidRuntime(597): at com.hp.hpl.jena.ontology.ProfileRegistry.<clinit>(ProfileRegistry.java:48)
02-23 16:49:36.430: E/AndroidRuntime(597): Caused by: java.lang.ExceptionInInitializerError
02-23 16:49:36.430: E/AndroidRuntime(597): at com.hp.hpl.jena.rdf.model.ModelFactory.createDefaultModel(ModelFactory.java:122)
02-23 16:49:36.430: E/AndroidRuntime(597): at com.hp.hpl.jena.rdf.model.ModelFactory.createDefaultModel(ModelFactory.java:116)
Update
Here's the updated stack trace:
02-24 21:29:24.273: E/AndroidRuntime(534): FATAL EXCEPTION: main
02-24 21:29:24.273: E/AndroidRuntime(534): java.lang.ExceptionInInitializerError
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.<init>(XMLHandler.java:367)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.rdf.arp.impl.RDFXMLParser.<init>(RDFXMLParser.java:52)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.rdf.arp.impl.RDFXMLParser.create(RDFXMLParser.java:85)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.rdf.arp.JenaReader.<init>(JenaReader.java:62)
02-24 21:29:24.273: E/AndroidRuntime(534): at java.lang.Class.newInstanceImpl(Native Method)
02-24 21:29:24.273: E/AndroidRuntime(534): at java.lang.Class.newInstance(Class.java:1319)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.rdf.model.impl.RDFReaderFImpl.getReader(RDFReaderFImpl.java:114)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:220)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.OntDocumentManager.findMetadata(OntDocumentManager.java:895)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.OntDocumentManager.initialiseMetadata(OntDocumentManager.java:853)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.OntDocumentManager.<init>(OntDocumentManager.java:201)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.OntDocumentManager.<init>(OntDocumentManager.java:183)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.OntDocumentManager.<init>(OntDocumentManager.java:167)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.OntDocumentManager.getInstance(OntDocumentManager.java:245)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.OntModelSpec.getDocumentManager(OntModelSpec.java:340)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.impl.OntModelImpl.getDocumentManager(OntModelImpl.java:181)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.impl.OntModelImpl.loadImports(OntModelImpl.java:1887)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.impl.OntModelImpl.<init>(OntModelImpl.java:148)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.ontology.impl.OntModelImpl.<init>(OntModelImpl.java:128)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.rdf.model.ModelFactory.createOntologyModel(ModelFactory.java:410)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.Sample.SampleApp.StartingPoint.parseOWLFile(StartingPoint.java:105)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.Sample.SampleApp.StartingPoint$3.onClick(StartingPoint.java:68)
02-24 21:29:24.273: E/AndroidRuntime(534): at android.view.View.performClick(View.java:3511)
02-24 21:29:24.273: E/AndroidRuntime(534): at android.view.View$PerformClick.run(View.java:14105)
02-24 21:29:24.273: E/AndroidRuntime(534): at android.os.Handler.handleCallback(Handler.java:605)
02-24 21:29:24.273: E/AndroidRuntime(534): at android.os.Handler.dispatchMessage(Handler.java:92)
02-24 21:29:24.273: E/AndroidRuntime(534): at android.os.Looper.loop(Looper.java:137)
02-24 21:29:24.273: E/AndroidRuntime(534): at android.app.ActivityThread.main(ActivityThread.java:4424)
02-24 21:29:24.273: E/AndroidRuntime(534): at java.lang.reflect.Method.invokeNative(Native Method)
02-24 21:29:24.273: E/AndroidRuntime(534): at java.lang.reflect.Method.invoke(Method.java:511)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-24 21:29:24.273: E/AndroidRuntime(534): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-24 21:29:24.273: E/AndroidRuntime(534): at dalvik.system.NativeStart.main(Native Method)
02-24 21:29:24.273: E/AndroidRuntime(534): Caused by: java.lang.NoClassDefFoundError: com.hp.hpl.jena.iri.IRIFactory
02-24 21:29:24.273: E/AndroidRuntime(534): at com.hp.hpl.jena.rdf.arp.ARPOptions.<clinit>(ARPOptions.java:60)
02-24 21:29:24.273: E/AndroidRuntime(534): ... 33 more
How can I eliminate this exception and get to parse the OWL file?
The Javadoc for this exception says:
Signals that an unexpected exception has occurred in a static initializer. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.
You then say:
But, I'm not using any static variable in my code.
However, your code >>is<< triggering static initialization of some class, and that static initialization is throwing an unchecked exception which is not being caught.
Normally, the stacktrace of the ExceptionInInitializerError would include the traces of the unchecked exception that caused the problem. I don't see this in the fragments of stacktrace that you have included ... but I expect that it is in the complete stacktrace.
If you want further help, provide the complete unedited stacktrace rather than random fragments of one or more stacktraces.
UPDATE
The salient part of the stacktrace is at the end:
Caused by: java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory
at com.hp.hpl.jena.util.Metadata.<clinit>(Metadata.java:26)
... 21 more
The JVM has been unable to load (or possibly initialize) the org.slf4j.LoggerFactory class. The problem is most likely that the SLF4J jar file is missing.
The dependencies of that version of Jena should be explained in the documentation.

android.os.NetworkOnMainThreadException and java.lang.reflect.InvocationTargetException [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I have a problem.
I want to know where did the android.os.NetworkOnMainThreadException and
java.lang.reflect.InvocationTargetException Exception come from !
Please, I'm new to Android and I need your help guys!
My LogCat:
12-19 13:00:27.049: E/AndroidRuntime(1170): FATAL EXCEPTION: main
12-19 13:00:27.049: E/AndroidRuntime(1170): java.lang.IllegalStateException: Could not execute method of the activity
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3633)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View.performClick(View.java:4240)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$PerformClick.run(View.java:17721)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.handleCallback(Handler.java:730)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Looper.loop(Looper.java:137)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-19 13:00:27.049: E/AndroidRuntime(1170): at dalvik.system.NativeStart.main(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: java.lang.reflect.InvocationTargetException
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3628)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 11 more
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: android.os.NetworkOnMainThreadException
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.Socket.connect(Socket.java:842)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.ensem.sehaty.MainActivity.recupererListMed(MainActivity.java:58)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 14 more
12-19 13:05:27.366: I/Process(1170): Sending signal. PID: 1170 SIG: 9
MainActivity.java
public class MainActivity extends Activity {
Button btnRecupListMed = null;
ListView listeMed = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRecupListMed = (Button) findViewById(R.id.btnListMed);
listeMed = (ListView) findViewById(R.id.listMed);
}
public void recupererListMed(View v){
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(sb.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<TextView
android:text="#string/lbl_sehaty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/btnListMed"
android:text="#string/lbl_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="recupererListMed"
/>
<ListView
android:id="#+id/listMed"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginTop="60dp">
</ListView>
And my Manifest contains the following permission
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Thanks.
This error comes when you try to make a server call on UI thread.
You should create an AsyncTask and put your server call in it.
And on click of button call execute on the object of asynctask.
Ex:
public class ServiceTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
return sb;
}
#Override
protected void onPostExecute(String result) {
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(result.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
}
And inside your onClick event:
public void recupererListMed(View v){
new ServiceTask().execute();
}
This will execute doInBackground method on a different thread and once result is fetched onPostExecute is called on UI thread.

Android App crashes right on start

I have an app that's supposed to get some string from a server depending on the webpage, and it crashes every time I run it. I don't understand how to even debug it, and I've tried numerous changes. It started crashing ever since I messed with the GUI, and added the ability to switch views if that provides any sort of help.
Here is the code:
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener{
private WebView mWebview;
EditText addressBar;
String currentWebpage = "http://www.aljazeera.com/news/americas/2013/07/20137113200544375.html";
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
View main = (View) findViewById(R.layout.activity_main);
View readOut = (View) findViewById(R.layout.read_out);
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("Showing Activity_Main...");
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
super.onCreate(savedInstanceState);
//setContentView(R.menu.main);
addressBar = (EditText)findViewById(R.id.addressBar);
addressBar.setText(currentWebpage);
mWebview = (WebView)findViewById(R.id.webview);
mWebview.getSettings().setJavaScriptEnabled(true); // enables javascript
mWebview.setWebViewClient(new WebViewClient());
System.out.println("Loading Webpage...");
mWebview.loadUrl(currentWebpage);
}
public void speakOut(String text) {
TextToSpeech tts = new TextToSpeech(this, this);
System.out.println("Speaking");
if(tts.isLanguageAvailable(Locale.ENGLISH) != -1){
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
public int speakFull(String text){
switchToRead();
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
speakOut(sentences[i]);
if(i == sentences.length - 1){
return 1;
}
}
return 0;
}
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://someserver.net:8080/" + webPage));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
private class tts extends AsyncTask<String, Void, String>{//Async http request to get text
#Override
protected String doInBackground(String... arg0) {
try {
System.out.println("Running seperate thread for TTS.");
int complete = 0;
while(complete == 0){
System.out.println("Speaking full..");
complete = speakFull(getText(mWebview.getUrl()));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
}
}
public void clickPlay(View v){
new tts().execute("");
}
public void clickGo(View v){
if(addressBar.getText() != null){
currentWebpage = addressBar.getText().toString();
System.out.println("Current webpage changed to: " + currentWebpage);
mWebview.loadUrl(currentWebpage);
}
}
public void clickPause(View v){
System.out.println("Clicked pause.");
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
System.out.println("Swtiching view to Read.");
viewGroup.removeView(main);
viewGroup.addView(View.inflate(this, R.layout.read_out, null));
}
public void switchToMain(){
System.out.println("Switching view to Main.");
viewGroup.removeView(readOut);
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
}
}
Also here are the numerous errors I encounter when launching my app:
08-01 14:53:10.210: E/Trace(812): error opening trace file: No such file or directory (2)
08-01 14:53:10.600: D/AndroidRuntime(812): Shutting down VM
08-01 14:53:10.631: W/dalvikvm(812): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:10.660: E/AndroidRuntime(812): FATAL EXCEPTION: main
08-01 14:53:10.660: E/AndroidRuntime(812): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:10.660: E/AndroidRuntime(812): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): Caused by: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:10.660: E/AndroidRuntime(812): ... 11 more
08-01 14:53:27.439: D/AndroidRuntime(860): Shutting down VM
08-01 14:53:27.439: W/dalvikvm(860): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:27.449: E/AndroidRuntime(860): FATAL EXCEPTION: main
08-01 14:53:27.449: E/AndroidRuntime(860): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:27.449: E/AndroidRuntime(860): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): Caused by: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:27.449: E/AndroidRuntime(860): ... 11 more
Move your view initialization inside onCreate after setContentView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
...// rest of the code

The application has stopped unexcepetedly

Android tells me that The application has stopped unexcepetedly, but there are no error's in my code.
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TableLayout;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i = 0; i < 6; i++) {
TableLayout tl = (TableLayout) findViewById(R.id.T);
for(int j = 0; j < 6; j++) {
ImageView img = (ImageView) tl.getChildAt(j);
img.setImageResource(R.drawable.w);
}
}
}
}
Logcat says:
03-03 19:25:43.550: WARN/dalvikvm(487): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): FATAL EXCEPTION: main
03-03 19:25:43.580: ERROR/AndroidRuntime(487): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloandroid/com.example.helloandroid.HelloAndroid}: java.lang.ClassCastException: android.widget.TableRow
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.os.Looper.loop(Looper.java:123)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.app.ActivityThread.main(ActivityThread.java:3683)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at java.lang.reflect.Method.invoke(Method.java:507)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at dalvik.system.NativeStart.main(Native Method)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): Caused by: java.lang.ClassCastException: android.widget.TableRow
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at com.example.helloandroid.HelloAndroid.onCreate(HelloAndroid.java:17)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-03 19:25:43.580: ERROR/AndroidRuntime(487): ... 11 more
EDIT: The problem was on the layout:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i = 0; i < 7; i++) {
TableLayout tl = (TableLayout) findViewById(R.id.T);
TableRow tr = (TableRow) tl.getChildAt(i);
for(int j = 0; j < 7; j++) {
ImageView img = (ImageView) tr.getChildAt(j);
img.setImageResource(R.drawable.w);
}
}
}
}
Look at Logcat to see the stack trace which will pinpoint the fault location.
My guess is that findViewById() or getChildAt() is returning null, i.e. your layout isn't quite what you think it is.
TableLayout tl = (TableLayout) findViewById(R.id.T); :
The result of findViewById(R.id.T) is most likely not of type TableLayout (but not null).
Try to print out findViewById(R.id.T).getClass().getName();
That's what this tells me:
Caused by: java.lang.ClassCastException: android.widget.TableRow
at com.example.helloandroid.HelloAndroid.onCreate(HelloAndroid.java:17)
I was getting this error for the reason of wrong encoding for layout.xml. Instead of...
<?xml version="1.0" encoding="iso-8859-1"?>
...it should have been in my case:
<?xml version="1.0" encoding="utf-8"?>
Little hard to figure this one out.

Categories