Doesn't read file - java

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.

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"

Why am I getting this error "Expected resource of type raw" in Android Studio?

I was trying to set the default wallpaper by using a button but for some reason when i set the InputStream in the OnCreate Method, i get this error "expected resource of type raw". I am referencing the drawable folder and using the icon.png image which is in the drawable folder. I was following the tutorials in the NewBoston Series and it seems to work fine for Travis but for some reason mine doesnt work in Android Studio. What could be the error? Thanks
Camera.java:
package com.example.user.cameraapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Switch;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by user on 16-08-2015.
*/
public class Camera extends Activity implements View.OnClickListener{
ImageView iv;
Button b1,b2;
ImageButton img;
Intent i;
final static int cameractivity = 0;
Bitmap b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
inititalize();
InputStream is = getResources().openRawResource(R.drawable.icon);
b = BitmapFactory.decodeStream(is);
}
private void inititalize() {
iv = (ImageView)findViewById(R.id.iView1);
img = (ImageButton)findViewById(R.id.imgbtn);
b1 = (Button)findViewById(R.id.btn1);
b2 = (Button)findViewById(R.id.btn2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn1:
try {
getApplicationContext().setWallpaper(b);
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.imgbtn:
i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,cameractivity);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK)
{
Bundle extras = data.getExtras();
b = (Bitmap)extras.get("data");
iv.setImageBitmap(b);
}
}
}
Image:
The error occurred because Android Studio expected a resource file of type raw.
Solution 1:
Create a new folder in your "res" folder called "raw", and put your icon there. The raw folder should contain all your media files of your app.
Then replace
InputStream is = getResources().openRawResource(R.drawable.icon);
with
InputStream is = getResources().openRawResource(R.raw.icon);
Solution 2:
Another solution is to do it like this. This doesn't require you to create a raw folder:
InputStream is = getResources().openRawResource(+ R.drawable.icon);
Replace
InputStream is = getResources().openRawResource(R.drawable.icon);
With
InputStream is = getResources().openRawResource(+ R.drawable.icon);
Let's look at documentation for openRawResource
Open a data stream for reading a raw resource. This can only be used
with resources whose value is the name of an asset files -- that is,
it can be used to open drawable, sound, and raw resources; it will
fail on string and color resources.
So the solution - leave it as it is, i. e.
InputStream is = getResources().openRawResource(R.drawable.icon);
The inspection in Android Studio is just wrong. You can add
#SuppressWarnings("ResourceType")
to hide the error.
Note
Using + R.drawable.icon just fools the inspection, because it can no longer determine which kind of resource it is.

read from file in android using assets

I am trying to read file from assets in android. I want every button to print a paragraph, for example the first button prints the first paragraph and the second button print the second paragraph.
I tried with the code below but its not working.
I get this error message:
03-03 18:40:17.800: E/AndroidRuntime(977): FATAL EXCEPTION: main
03-03 18:40:17.800: E/AndroidRuntime(977): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.hajjapp.AfterHajj }
03-03 18:40:17.800: E/AndroidRuntime(977): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1622)
03-03 18:40:17.800: E/AndroidRuntime(977): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
03-03 18:40:17.800: E/AndroidRuntime(977): at android.app.Activity.startActivityForResult(Activity.java:3370) –
Can anyone tell me where the problem is?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Dialog;
import android.content.res.AssetManager;
public class BeforeHajj extends ActionBarActivity {
Button whatHajj;
TextView text;
Button hajjTime;
String before;
String [] s;
String timeHajj="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_before_hajj);
whatHajj = (Button)findViewById(R.id.whatisHajj);
hajjTime = (Button)findViewById(R.id.hajjTime);
text = (TextView)findViewById(R.id.text);
whatHajj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try
{
AssetManager assetmanager=getAssets();
InputStream input=assetmanager.open("beforehaj.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(input));
String st="";
StringBuilder sb=new StringBuilder();
while((st=br.readLine())!=null)
{
sb.append(st);
before+=sb.toString();
s=before.split("*");
}
text.setText(before);
}
catch(IOException ep) {
text.append(ep.toString());
}
}
});
hajjTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// custom dialog
try
{
AssetManager assetmanager=getAssets();
InputStream input=assetmanager.open("beforehaj.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(input));
String st="";
StringBuilder sb=new StringBuilder();
while((st=br.readLine())!=null){
sb.append(st);
before+=sb.toString();
s=before.split("*");
}
}
catch(IOException ep) {
text.append(ep.toString());
}
final Dialog dialog = new Dialog(BeforeHajj.this);
dialog.setContentView(R.layout.guide_dialog);
dialog.setTitle("Hajj Time");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
text.append(s[0]);
ImageView image = (ImageView) dialog.findViewById(R.id.dialog_image);
image.setImageResource(R.drawable.dolheja);
Button dialogButton = (Button) dialog.findViewById(R.id.dialog_button);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.before_hajj, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Somewhere, you are trying to start an activity that is supposed to be implemented in the Java class com.example.hajjapp.AfterHajj. The error message is telling you that there is no <activity> element in the manifest for this class. Also note that the code you pasted into your question is from a Java class named BeforeHajj.
Use new line character to split the paragraphs. All paragraphs start with a new line, so use
before.split("\\\n");
This shall do the job for you.
Use escape symbols to make the '*' be recognized by split, e.g. s.split("\\*");

Delete file function allow to delete only a specific file. How to adapt to a ListView with switch statement?

I have a list view that display files stored in internal storage (files are display without their extension).
i have implement the OnItemLongClickListener with "switch" statement, to allow the user to delete a file of his choice from the list.
Unfortunately i was able just to add a function that can delete only a specific file.
I need a delete function that can delete the file pressed in the list. Because of the "switch method" that change position to the files on the list if one or more files are deleted, this make my problem even worst!.
MainActivity.java
import java.io.File;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView lv;
ArrayAdapter<String> adapter;
public void list(){
lv = (ListView) findViewById(R.id.listView1);
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/");
File[] filelist = dir.listFiles();
String[] theNamesOfFiles = new String[filelist.length];
for (int i = 0; i < theNamesOfFiles.length; i++) {
String temp = filelist[i].getName();
theNamesOfFiles[i] = temp.substring(0, temp.lastIndexOf('.'));
}
Arrays.sort(theNamesOfFiles);
adapter = new ArrayAdapter<String>(this, R.layout.list_row, theNamesOfFiles);
lv.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// setting onItemLongClickListener and passing the position to the function
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch(position){
case 0:{
}
break;
case 1:{
}
break;
case 2:{
}
break;
case 3:{
}
break;
case 4:{
}
break;
}
return true;
}
});
}
public void doDeleteFile(int position){
File fileToDelete = new File(Environment.getExternalStorageDirectory().getPath() + "/path/", "A.map");
if(!fileToDelete.isDirectory()){
try{
if(fileToDelete.delete()){
System.out.println("File delete operation success");
}
else{
System.out.println("File delete operation failed");
}
}catch(Exception ex){
System.out.println("Exception :"+ex.getMessage());
}
}else{
System.out.println("It is not a file");
}
}
}
Going to need more details than this.
But it looks like you should be passing the name of the file to your delete function and using that to create the file reference. You say you're not displaying the file extension. If you know they're all the same extension, you can add it manually. If not, you're going to have search for it.
Write a Custom Array Adapter that works on File instead of String and trigger the delete method on the specific File-Object. Override getView method in the Adapter to show the filename without the extension. Use this as an example how to write a Custom Adapter. The way you do it now, by Strings and espacially the line:
File fileToDelete = new File(Environment.getExternalStorageDirectory().getPath() + "/path/", "A.map")
is very error-prone. Work on the File objects instead. I'm confused about your switch-statement it doesn't make sense there. (Maybe try other things while learning to program?)

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

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

Categories