NoClassDefFoundError: org.apache.poi.hssf.usermofdel.HSSFWorkbook - java

I am new to eclipse/android/java, so please bear with me. I have a couple of apps running so I thought I had grasped some of the concepts but this has stumped me.
I am writing an android app which references Excel spreadsheets, so I downloaded apache poi-3.9-20121203.jar and using project/properties/java_build_path/add_external_JARs added poi-3.9.jar to the Referenced libraries tab.
I clicked the poi-3.9 box on the Order and export tab
I hovered and imported over HSSFWorkbook workbook = new HSSFWorkbook(); and these are referenced in the import list. No errors in project but when I run it on a Nexus 7 I get the error
java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
The class is listed in the Reference libraries.
I am just starting with excel, and just cut and pasted the code from the tutorial here to get something working:
http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/
package com.procam.filetest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.RichTextString;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class MainActivity extends Activity {
Button butCreateSpreadsheet, butEmailFile;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
butCreateSpreadsheet = (Button) findViewById(R.id.butCreateSpreadsheet);
butEmailFile = (Button) findViewById(R.id.butEmailFile);
butCreateSpreadsheet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// copied code starts here
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
org.apache.poi.ss.usermodel.Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = ((org.apache.poi.ss.usermodel.Row) row).createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((RichTextString)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//ends here
}
});
}
#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;
}
}
It looks like to Referenced libraries are not going to the Nexus. I have searched on stackoverflow and found some references to linking referenced libraries to the project but don't understand enough to make sense of them.
Is it a problem with poi-3.9 library not going to the Nexus 7?
Simply explained help much appreciated.
* Not sure how to update the post, but I rebuilt the Class. This time I added the POI jar files BEFORE the code which referenced them, and it works.
Not sure why this is and don't have time to do the definitive testing, but case closed.
Thanks for help

Related

Fatal Exception main at onclick

Im getting E/AndroidRuntime: FATAL EXCEPTION: main at com.test.megatest.Main4Activity$1.onClick(Main4Activity.java:37).
Ive read tons of posts on this forum but I cant figure out what Im missing,
This is the Main4Activity.java:
package com.test.megatest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main4Activity extends AppCompatActivity {
EditText inputText;
TextView response;
Button saveButton, readButton;
private String filename = "SampleFile.txt";
private String filepath ="MyFileStorage";
File myExternalFile;
String myData ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
inputText = (EditText) findViewById(R.id.myInputText);
response = (TextView) findViewById(R.id.response);
saveButton =(Button) findViewById(R.id.saveExternalStorage);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(myExternalFile); //LINE 37
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText("");
response.setText("SampleFile.txt saved to somewhere..");
}
});
}
}
Can someone here just point me in the right direction? :)
The file you try to open an output stream for is NULL.
You declared it as a member but never initialized it.
Initialize file as
File myExternalFile=new File("SampleFile.txt");
Your Main4Activity has a "File" variable:
File myExternalFile;
But without assigning any object/value to that variable You are trying to use it in:
FileOutputStream fos = new FileOutputStream(myExternalFile);
Obviously you will get an Exception for that :P
You should initialise "myExternalFile" using any of the 4 public constructors specified at java.io.File (depending on your use case).
For example:
// If you need a "Persistent" file in private directory of your application
//
myExternalFile = new File(this.getFilesDir() ,"name_of_your_file.txt");
//
// or
// If you need a "Cache" file
myExternalFile = new File(this.getCacheDir() ,"name_of_your_file.txt");
Locations of above files on your Android filesystem is:
# Persistent: /data/data/com.test.megatest/files or
(Any File Manager App) /Android/data/com.test.megatest/files
# Cache: /data/data/com.test.megatest/cache or
(Any File Manager App) /Android/data/com.test.megatest/files
Reference:
1) java.io.FileOutputStream -> FileOutputStream (File file) public constructor
"Creates a file output stream to write to the file represented by the specified File object"

Android activity stops working when reading files from /data/data

My android application is kind of a text editor. I want to display the list of saved files. But whenever the activity listing the files is called, the activity stops. This code works completely fine when run in emulator but not on the actual device. Debugging the application on phone shows that the app stops when it tries to access the path although no error is displayed in logcat.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class File_List extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
Drawable background=getResources().getDrawable(R.drawable.background);
background.setAlpha(100);
final ListView list=(ListView)findViewById(R.id.listView1);
File folder = new File("/data/data/com.example.demo/files"); //for accessing the folder conatining the files
File[] listOfFiles = folder.listFiles(); //for listing the files within the folder
ArrayList<String> liste = new ArrayList<String>();
for(int i=0;i<listOfFiles.length;i++)
{
if(listOfFiles[i].isDirectory()==false)
liste.add(listOfFiles[i].getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, liste);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
// TODO Auto-generated method stub
//Log.e("selected",list.getAdapter().getItem(position).toString());
Common.CommonVar=2;
File file=new File("/data/data/com.example.demo/files/"+list.getAdapter().getItem(position).toString());
String content;
Log.e("file access", file.getName());
try
{
content = new Scanner(file).useDelimiter("\\A").nextLine();
Intent intent=new Intent(File_List.this,MainActivity.class);
intent.putExtra("File_data",content);
startActivity(intent);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Change the line as follows
File folder = new File("/data/data/com.example.demo/files");
if(!folder.exists()){
folder.mkdir();
}

Class resolved by unexpected DEX, how to avoid duplicate imports

I'm trying to build an plugin-system which is importing Fragments from other apks as described here.
Eclipse keeps telling me:
12-01 15:17:18.609: W/dalvikvm(23425): Class resolved by unexpected DEX: Lde/anthropotec/activityapp/firstplugin/UI;(0x42901520):0x57d93000 ref [Lde/anthropotec/activityapp/api/PluginAPI;] Lde/anthropotec/activityapp/api/PluginAPI;(0x428eb2b8):0x527e1000
(Lde/anthropotec/activityapp/firstplugin/UI; had used a different Lde/anthropotec/activityapp/api/PluginAPI; during pre-verification)
Which isn't a suprise, as I'm importing my PluginAPI-libary in both, the Host and the Plugin. As far as I understand, Eclipse seems to be afraid, that these libaries aren't identical. Is there a way to tell Eclipse to not import the libary, if it's already there in the other apk? Or is there any other way to go around this. Please tell me if you need more information. Here's my source:
The Host:
package de.anthropotec.activityapp.host;
import java.io.File;
import dalvik.system.DexClassLoader;
import de.anthropotec.activityapp.api.PluginAPI;
import de.anthropotec.activtiyapp.host.R;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
public class MainActivtiy extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Class<?> requiredClass = null;
final ApplicationInfo info = getPackageManager().getApplicationInfo("de.anthropotec.activityapp.firstplugin",0);
final String apkPath = info.sourceDir;
final File dexTemp = getDir("temp_folder", 0);
final String fullName = "de.anthropotec.activityapp.firstplugin.UI";
boolean isLoaded = true;
// Check if class loaded
try {
requiredClass = Class.forName(fullName);
} catch(ClassNotFoundException e) {
isLoaded = false;
}
if (!isLoaded) {
final DexClassLoader classLoader = new DexClassLoader(apkPath, dexTemp.getAbsolutePath(), null, getApplicationContext().getClassLoader());
requiredClass = classLoader.loadClass(fullName);
}
if (null != requiredClass) {
// Try to cast to required interface to ensure that it's can be cast
final PluginAPI holder = PluginAPI.class.cast(requiredClass.newInstance());
if (null != holder) {
final Fragment fragment = holder.getFragment();
if (null != fragment) {
final FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.add(R.id.pluginPlace, fragment, "MyFragment").commit();
}
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
The PluginApi:
package de.anthropotec.activityapp.api;
import android.app.Fragment;
public interface PluginAPI {
public Fragment getFragment();
}
And the Plugin-Fragment itself:
package de.anthropotec.activityapp.firstplugin;
import de.anthropotec.activityapp.api.PluginAPI;
import android.app.Fragment;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class UI extends Fragment implements PluginAPI{
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
// Note that loading of resources is not the same as usual, because it loaded actually from another apk
final XmlResourceParser parser = container.getContext().getPackageManager().getXml("de.anthropotec.testplugin", R.layout.ui, null);
return inflater.inflate(parser, container, false);
}
#Override
public Fragment getFragment() {
return this;
}
}
Each of the above as it's own Project (PluginAPI as libary). The question isn't quite new (e.g. here), but the already given answers advice to remove on of the imports, what doesn't seem to be a option in my case, as I need the API on both sides (Plugin and Host).
Ahww, sometimes it's so obvious. Just import the libary as extern libary in Properties->Java Build Path -> add external jar for the Plugin, and everything works just fine. Gnarf!

Doesn't read file

first I want to apologize for my bad english, I am from Slovakia ;)
So there is my problem
My friend wants to create a very simple translate aplication, very very very simple. We are beginners in programming for android and at all in java. The problem is, that our apk works great in Eclipse so we decided to create apk file and install it in our device. So when we installed it and there was a problem, our apk in device doesnt read file where are our words. So we tried it again in eclipse emulator and doesnt work too, but before creating apk it was fully working. Our file is in res/raw/dictionary
Here is our code
package com.example.dictionary;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView Vstup;
TextView Vystup;
Button presun;
String slovo;
String word;
String found;
Boolean click;
int i;
int j;
String sub;
String strf;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vstup = (TextView)findViewById(R.id.editText1);
Vystup = (TextView)findViewById(R.id.textView2);
presun = (Button)findViewById(R.id.button1);
presun.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
slovo = Vstup.getText().toString();
InputStream is = getResources().openRawResource(R.raw.dictionary);
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
while((strf = bufferedReader.readLine()) != null)
{
i = strf.indexOf(":"); // vrati prvu poziciu retazca
j = strf.indexOf(",");
sub = strf.substring(0,i); //vyberie zo stringu podretazec od indexu 0 po i
if(slovo.equals(sub))
{
found = strf.substring(i+1,j);
word = ("Výstup: " + found);
Vystup.setText(word.toString());
}
else {
word = ("Výstup: Word not found");
Vystup.setText(word.toString());
}
}
bufferedReader.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
});
}
#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;
}
}
error logcat
error opening trace file: no such file or directory(2)
getResources().openRawResource() gets an InputStream for a file in the res/raw/ directory of your Android project. The argument to openRawResource() is an int named R.raw.filename where filename is the name of the file without the extension.
So, the file won't be in the res/assets/ directory.
Although you can doublecheck that the file you're trying to read is actually in res/raw, it seems odd to me that you could build the APK and get an R.raw.filename entry if the file wasn't actually there. I'd use a debugger to step through the code and check the variables.

Android: Internet works in emulator but not on my phone

I'm making an app which reads a certain part of a website and posts it to the screen. The app currently works in my android emulator but when I transfer it to my galaxy S2, it doesn't seem to access the website at all.
package com.example.beam;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
String current = null;
Button check;
TextView text;
TextView url;
String[] lines = new String[12];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check = (Button) findViewById(R.id.checkstatus);
text = (TextView) findViewById(R.id.textView1);
url = (TextView) findViewById(R.id.url);
String[] lines = new String[12];
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// Attempt to the read the source from a website.
String bodyHtml = "null";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.spring8.or.jp/ext/ja/status/text.html");
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
bodyHtml = httpClient.execute(httpGet, resHandler);
} catch (Exception e) {
e.printStackTrace();
}
double current = 0;
try{
String derp = bodyHtml.substring(bodyHtml.lastIndexOf("mA") - 5, bodyHtml.lastIndexOf("mA"));
current = Double.parseDouble(derp);
}
catch(Exception e){
}
url.setText(current + " mA");
}
});
}
}
Apologies if the coding is a bit poor and messy, I'm quite new to all this. How do I fix this issue? Thank you
Also, I'm pretty sure I've set the permission correctly in the manifest.
Try this....
Its a good practice to Keep the UI work on UI thread and Non-UI work on Non-UI thread, but that became a LAW from the release of HONEYCOMB Android version.... That may be causing the error.
So you can do the following....
Do the Http on a separate thread, and then place the value on the UI using Handler, Handler Keep the reference of the thread in which it was created.
You can use AsyncTask which is specially designed for android to make a sync between
UI and Non-UI thread.
Note:
Please check the Internet Permission in AndroidManifest, though i know you have done it, cause the app ran on the emulator.... but still..no harm in checking it again.

Categories