Missing file through getAssets - java

I have a problem connected with reading a file in Java Application. Please help me as I'm trying to do it for four days and my CS teacher is not into Android Apps. Also any of the tutorials read does not help me.
I have a following app:
package com.bachosz.billionaires;
import android.support.v7.app.ActionBarActivity;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.StringTokenizer;
import android.content.ContextWrapper;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivityBillionaires extends ActionBarActivity {
private int currentQuestion;
private String [] answers;
private Button answerButton;
private Button questionButton;
private TextView questionView;
private TextView answerView;
private EditText answerText;
private Question [] questions;
private Button buttonA;
private Button buttonB;
private Button buttonC;
private Button buttonD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_billionaires);
try {
init();
} catch (IOException e) {
e.printStackTrace();
}
}
public void init() throws IOException
{
questions = new Question[2];
currentQuestion = 0;
InputStream inputStream = getResources().openRawResource(R.raw.questionstable);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
String content,a,b,c,d,correct;
int id, x = 0;
StringTokenizer st = null;
while ((line=reader.readLine()) != null)
{
st= new StringTokenizer(line, ",");
id = Integer.parseInt(st.nextToken());
content = st.nextToken();
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
d = st.nextToken();
correct = st.nextToken();
questions[x] = new Question(id, content, a, b, c, d, correct);
x++;
}
reader.close();
answerButton = (Button)findViewById(R.id.AnswerButton);
questionButton = (Button)findViewById(R.id.QuestionButton);
questionView = (TextView)findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
buttonA = (Button)findViewById(R.id.buttonA);
buttonB = (Button)findViewById(R.id.buttonB);
buttonC = (Button)findViewById(R.id.buttonC);
buttonD = (Button)findViewById(R.id.buttonD);
answerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
checkAnswer();
}});
questionButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showQuestion();
}});
}
public void showQuestion()
{
// if(currentQuestion == questions.length)
// currentQuestion =0;
questionView.setText(questions[0].toString());
answerView.setText("");
answerText.setText("");
currentQuestion++;
}
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(questions[currentQuestion].getCorrect()));
}
public void checkRight()
{
// String right
}
public void checkAnswer()
{
String answer = questions[currentQuestion].getCorrect();
if(isCorrect(answer))
answerView.setText("You're right!");
else
answerView.setText("Sorry, the correct answer is "+answers[currentQuestion]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_billionaires, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It is taken from Java application I was writing previously (that is why so many comments). How I can access the fileName in Android App? I was trying InputStream, get Assets, etc. but It does not work or I am doing it improperly. Currently it is throwing NullPointerException.
LOG CAT:
10-09 13:38:37.663: E/Trace(921): error opening trace file: No such file or directory (2)
10-09 13:38:39.354: D/AndroidRuntime(921): Shutting down VM
10-09 13:38:39.354: W/dalvikvm(921): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-09 13:38:39.384: E/AndroidRuntime(921): FATAL EXCEPTION: main
10-09 13:38:39.384: E/AndroidRuntime(921): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bachosz.billionaires/com.bachosz.billionaires.MainActivityBillionaires}: java.lang.NullPointerException
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.os.Looper.loop(Looper.java:137)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-09 13:38:39.384: E/AndroidRuntime(921): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 13:38:39.384: E/AndroidRuntime(921): at java.lang.reflect.Method.invoke(Method.java:511)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-09 13:38:39.384: E/AndroidRuntime(921): at dalvik.system.NativeStart.main(Native Method)
10-09 13:38:39.384: E/AndroidRuntime(921): Caused by: java.lang.NullPointerException
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.readFile(MainActivityBillionaires.java:111)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.init(MainActivityBillionaires.java:140)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.onCreate(MainActivityBillionaires.java:70)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.Activity.performCreate(Activity.java:5008)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-09 13:38:39.384: E/AndroidRuntime(921): ... 11 more

The error says you're getting a NPE (Null Pointer Exception) at com.bachosz.billionaires.MainActivityBillionaires. You need to look at the code section that you use to call that activity. (it is not in your code above - or else we don't know which line with the given information)
Another thing you have to make sure is that you have the appropriate context.
AssetManager assetManage = appContext.getAssets();
String[] filelist = assetManage.list("");

First you should clean up your code, at least to show it here where we don't know what are you doing.
It's easier to understand.
Why are you using assets? In Android the most common way to access resources is the .../res/raw folder.
It makes a reference of the file in the autogenerated R.class so you can access it anywhere.
Make sure your filename is lowercase and has no spaces. If you haven't raw folder under res, create it manually.
Try this:
InputStream inputStream = getResources().openRawResource(R.raw.YOURFILE);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null)
{
// Read file.
}

Firstly: copy YOURFILE to assets folder.
Then, AssetManager assetManage = getAssets();
Then,
InputStream myInput = null;
try {
myInput = assetManager.open("YOURFILE");
} catch (IOException e1) {
e1.printStackTrace();
}
And finally BufferedReader reader = new BufferedReader(new InputStreamReader(myInput));
follow the above code step by step.

Related

App just forcecloses and stops working, why?

I'm a newbie android developer and I am making, or trying to make a File explorer that wil be capable of opening almost all file types. From music files, through video files, document files and many others. BUT, I came across a huge problem that my app compiled successfully but it does not open. Here is my code:
package com.tstudios.openit;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
private ImageView mImageView=(ImageView) findViewById(R.id.gallery);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
String filename = f.getName();
String filenameArray[] = filename.split("\\.");
String extension = filenameArray[filenameArray.length-1];
TextView row=(TextView)findViewById(R.id.rowtext);
//if(extension=="jpg"){
//mImageView.setImageBitmap(BitmapFactory.decodeFile(dirPath));
//}
//if(extension!=null){
//row.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher,0,0,0);
//}
Arrays.sort(files, filecomparator);
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
item.add(file.getName());
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
Comparator<? super File> filecomparator = new Comparator<File>(){
public int compare(File file1, File file2) {
if(file1.isDirectory()){
if (file2.isDirectory()){
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}else{
return -1;
}
}else {
if (file2.isDirectory()){
return 1;
}else{
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}
}
}
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File file = new File(path.get(position));
String filename = file.getName();
String filenameArray[] = filename.split("\\.");
String extension = filenameArray[filenameArray.length-1];
if (file.isDirectory())
{
if(extension=="jpg"){
mImageView.setImageBitmap(BitmapFactory.decodeFile(filename));
getDir(path.get(position));
}else{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK", null).show();
}
}
}
and this is logcat I get when I lauch the app, btw I am using Sony Xperia Z1 Compact if that helps
08-28 12:10:54.779 4169-4169/com.tstudios.openit D/AndroidRuntime﹕ Shutting down VM
08-28 12:10:54.779 4169-4169/com.tstudios.openit W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4164cd88)
08-28 12:10:54.789 4169-4169/com.tstudios.openit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tstudios.openit, PID: 4169
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.tstudios.openit/com.tstudios.openit.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at com.tstudios.openit.MainActivity.<init>(MainActivity.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:212)
            at android.app.ActivityThread.main(ActivityThread.java:5135)
            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:877)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
         at dalvik.system.NativeStart.main(Native Method)
And another question, how to put icons before file names ? Depending on extension
Thank you very much for your help
Move the
mImageView=(ImageView) findViewById(R.id.gallery);
to onCreate() after setContentView(), leaving just the member variable declaration at the class level:
private ImageView mImageView;
Before onCreate() there's no window yet for the activity and you'll get the NPE.
Before setContentView() there's no view hierarchy to search from and a null is returned.
private ImageView mImageView=(ImageView) findViewById(R.id.gallery);
to use findViewById you need a valid Activity. It happens after the activity has been attached
Place this line private ImageView mImageView=(ImageView) findViewById(R.id.gallery); after setContentView . It will resolve null pointer exception. After this, if you get any other exception, Pls tell.

why my android app is unfortunately has stopped

I have the following code in android, but when I run it, it complains: unfortunately has stopped:
package com.example.trave;
import java.util.List;
import com.example.trave.data.NoteDataSource;
import com.example.trave.data.NoteItem;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private NoteDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataSource = new NoteDataSource(this);
List<NoteItem> notes = dataSource.findAll();
NoteItem note = notes.get(0);
note.setText("Updated!");
dataSource.update(note);
notes = dataSource.findAll();
note = notes.get(0);
Log.i("NOTES", note.getKey() + ": " + note.getText());
}
#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;
}
}
package com.example.trave.data;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import android.content.Context;
import android.content.SharedPreferences;
public class NoteDataSource {
private static final String PREFKEY = "notes";
private SharedPreferences notePrefs;
public NoteDataSource(Context context) {
notePrefs = context.getSharedPreferences(PREFKEY, Context.MODE_PRIVATE);
}
public List<NoteItem> findAll() {
Map<String, ?> notesMap = notePrefs.getAll();
SortedSet<String> keys = new TreeSet<String>(notesMap.keySet());
List<NoteItem> noteList = new ArrayList<NoteItem>();
for (String key : keys) {
NoteItem note = new NoteItem();
note.setKey(key);
note.setText((String)note.getKey());
noteList.add(note);
}
return noteList;
}
public boolean update(NoteItem note) {
SharedPreferences.Editor editor = notePrefs.edit();
editor.putString(note.getKey(), note.getText());
editor.commit();
return true;
}
public boolean remove(NoteItem note) {
if (notePrefs.contains(note.getKey())) {
SharedPreferences.Editor editor = notePrefs.edit();
editor.remove(note.getKey());
editor.commit();
}
return true;
}
}
package com.example.trave.data;
import android.annotation.SuppressLint;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class NoteItem {
private String key;
private String text;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#SuppressLint("SimpleDateFormat")
public static NoteItem getNew() {
Locale locale = new Locale("en_US");
Locale.setDefault(locale);
String pattern = "yyyy-MM-dd HH:mm:ss Z";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
String key = formatter.format(new Date());
NoteItem note = new NoteItem();
note.setKey(key);
note.setText("");
return note;
}
}
what is the problem and how to fix it?
The logCat:
09-08 11:15:23.674: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-08 11:15:23.793: E/Trace(1552): error opening trace file: No such file or directory (2)
09-08 11:15:24.533: D/AndroidRuntime(1552): Shutting down VM
09-08 11:15:24.533: W/dalvikvm(1552): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-08 11:15:24.543: E/AndroidRuntime(1552): FATAL EXCEPTION: main
09-08 11:15:24.543: E/AndroidRuntime(1552): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trave/com.example.trave.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.os.Handler.dispatchMessage(Handler.java:99)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.os.Looper.loop(Looper.java:137)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-08 11:15:24.543: E/AndroidRuntime(1552): at java.lang.reflect.Method.invokeNative(Native Method)
09-08 11:15:24.543: E/AndroidRuntime(1552): at java.lang.reflect.Method.invoke(Method.java:511)
09-08 11:15:24.543: E/AndroidRuntime(1552): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-08 11:15:24.543: E/AndroidRuntime(1552): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-08 11:15:24.543: E/AndroidRuntime(1552): at dalvik.system.NativeStart.main(Native Method)
09-08 11:15:24.543: E/AndroidRuntime(1552): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
09-08 11:15:24.543: E/AndroidRuntime(1552): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
09-08 11:15:24.543: E/AndroidRuntime(1552): at java.util.ArrayList.get(ArrayList.java:304)
09-08 11:15:24.543: E/AndroidRuntime(1552): at com.example.trave.MainActivity.onCreate(MainActivity.java:25)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.app.Activity.performCreate(Activity.java:5104)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-08 11:15:24.543: E/AndroidRuntime(1552): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-08 11:15:24.543: E/AndroidRuntime(1552): ... 11 more
09-08 11:15:24.552: W/ActivityManager(291): Force finishing activity com.example.trave/.MainActivity
09-08 11:15:24.562: W/WindowManager(291): Failure taking screenshot for (246x410) to layer 21015
you got IndexOutOfBoundsException at
List<NoteItem> notes = dataSource.findAll();
NoteItem note = notes.get(0);
or at
notes = dataSource.findAll();
note = notes.get(0);
because the list seems to be empty, you should check for size
List<NoteItem> notes = dataSource.findAll();
if (notes.size()>0)
NoteItem note = notes.get(0);
and check data you are providing to the lists
You get an IndexOutOfBoundsException because the NoteList is empty. Most likely at:
NoteItem note = notes.get(0);
in the onCreate method. You need to check for the empty result of NoteDataSource.findAll() like this:
List<NoteItem> notes = dataSource.findAll();
if(notes.isEmpty())
return; // Or whatever you must do in your App
else {
NoteItem note = notes.get(0);
// ... The rest of your onCreate code...
Additionally, in your NoteDataSource.update() and NoteDataSource.remove() please return the result of the commit() instead always true as of the contract: SharedPreferences.Editor.commit
otherwise there's not much sense in returning a boolean.

Open2.4.5 Android Crashes when I call Mat

This issue is been driving me crazy for days now. I'm trying to use opencv android the latest package. Everything is inserted and I don't have any errors, until I run the project on android and that's when it crashes. When I call a simple code like, Mat m = new Mat(); the app crashes, I saw some other people has the same problem but somehow they managed to fix it, here is my code, maybe it's something stupid I can't see! All I really need is Matrix library, I tried Jama and jblas but they work to some point but then they crash too, and they're very slow.
package com.ece.facerecog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;'
import java.util.Arrays;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import com.ece.facerecog.utils.UIHelper;
//import org.jblas.DoubleMatrix;
//import Jama.Matrix;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
//import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class Face extends Activity {
private Bitmap bitmap;
private int f = Crop.k;
private ImageView tv;
private static final String TAG = "OCVSample::Activity";
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
// #Override
// public void onResume()
// {
// super.onResume();
// OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5, this, k mLoaderCallback);
// }
private Bitmap ReadImage1(String fBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/preprocessed");
File file = new File(myDir , fBitmap); //or any other format supported
UIHelper.displayText(this, R.id.textView1, file.toString());
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = `BitmapFactory.decodeFile(file.getAbsolutePath(),options); //This gets the image `
return bitmap;
} catch (Exception e) {
e.printStackTrace();
UIHelper.displayText(this, R.id.textView1, "Doesn't exist");
}
return bitmap;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.face);
Log.i(TAG, "Trying to load OpenCV library");
if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5, this, mLoaderCallback))
{
Log.e(TAG, "Cannot connect to OpenCV Manager");
}
ImageView tv = (ImageView) findViewById(R.id.imageView1);
Bitmap bmp = ReadImage1("/Image-" + f+ ".jpg");
tv.setImageBitmap(bmp);
Mat m = new Mat();
}
}
`
Here's the log error,
04-13 23:14:17.412: E/AndroidRuntime(12111): FATAL EXCEPTION: main
04-13 23:14:17.412: E/AndroidRuntime(12111): java.lang.UnsatisfiedLinkError: Native method not found: org.opencv.core.Mat.n_Mat:()J
04-13 23:14:17.412: E/AndroidRuntime(12111): at org.opencv.core.Mat.n_Mat(Native Method)
04-13 23:14:17.412: E/AndroidRuntime(12111): at org.opencv.core.Mat.<init>(Mat.java:441)
04-13 23:14:17.412: E/AndroidRuntime(12111): at com.ece.facerecog.Face.onCreate(Face.java:147)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.Activity.performCreate(Activity.java:5104)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.os.Looper.loop(Looper.java:137)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread.main(ActivityThread.java:5039)
04-13 23:14:17.412: E/AndroidRuntime(12111): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 23:14:17.412: E/AndroidRuntime(12111): at java.lang.reflect.Method.invoke(Method.java:511)
04-13 23:14:17.412: E/AndroidRuntime(12111): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-13 23:14:17.412: E/AndroidRuntime(12111): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-13 23:14:17.412: E/AndroidRuntime(12111): at dalvik.system.NativeStart.main(Native Method)
Thanks for helping me out!
OpenCV functions such as Mat have to be invoked in either a thread or AsyncTask, I think. I faced the SAME issue for AGES without help.
For you to avoid crashes, you could declare Mat m as a global variable and initialize it in the AsyncInitialization block of OpenCV.
Something like this :
public class Face extends Activity {
private Bitmap bitmap;
private int f = Crop.k;
private ImageView tv;
Mat m;
private static final String TAG = "OCVSample::Activity";
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
m=new Mat();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
If it still crashes, I would suggest you execute whatever function you're trying in an AsyncTask like in my project. Mat functions however can be declared without the risk of the UnsatisfiedLinkError exception in OpenCV functions. Functions called in the UI however experience this. At least this is what I've seen.
I just faced the same problem and found another solution:
You can use another activity to call your activity ("Face"), like some introduction screen with a button that starts your activity. If you initialize OpenCV in this introduction activity (same way you did in your activity) you can use OpenCV functions in the next activity without any problem...
This way you don't have to declare OpenCV variables as a global variables and initialize them in the AsyncInitialization block of OpenCV.

Passing data from one Java file to another in Android

I am a newbie to Android development. I have two Java files in my project. One file contains my main activity so I want to transfer the data from one Java file to another which contains the main activity.
cordovaExample.java:
package org.apache.cordova.example;
import android.content.Context;
import android.content.Intent;
import android.telephony.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import org.apache.cordova.*;
public class cordovaExample extends DroidGap
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
Bundle extras = getIntent().getExtras();
String phno = extras.getString("novel.PhoneNumber");
Toast.makeText(getApplicationContext(),phno,Toast.LENGTH_LONG).show();
}
}
novel.java
package org.apache.cordova.example;
import android.content.Context;
import android.content.Intent;
import android.telephony.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class novel extends Activity
{
public String PhoneNumber;
Context mcontext;
public String getNumber()
{
TelephonyManager tMgr=(TelephonyManager)mcontext.getSystemService(Context.TELEPHONY_SERVICE);
Intent intent = new Intent(this, cordovaExample.class);
intent.putExtra("novel.PhoneNumber", PhoneNumber);
startActivity(intent);
return PhoneNumber = tMgr.getLine1Number();
}
}
So i want to transfer the "PhoneNumber" from novel.java to cordovaExample.java but in novel.java, After running the application i am getting "unfortunately app has stopped" in emulator.
this is the logcat
08-12 15:49:37.657: E/AndroidRuntime(779): FATAL EXCEPTION: main
08-12 15:49:37.657: E/AndroidRuntime(779): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.apache.cordova.example/org.apache.cordova.example.cordovaExample}: java.lang.NullPointerException
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.access$600(ActivityThread.java:123)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.os.Handler.dispatchMessage(Handler.java:99)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.os.Looper.loop(Looper.java:137)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.main(ActivityThread.java:4424)
08-12 15:49:37.657: E/AndroidRuntime(779): at java.lang.reflect.Method.invokeNative(Native Method)
08-12 15:49:37.657: E/AndroidRuntime(779): at java.lang.reflect.Method.invoke(Method.java:511)
08-12 15:49:37.657: E/AndroidRuntime(779): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-12 15:49:37.657: E/AndroidRuntime(779): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-12 15:49:37.657: E/AndroidRuntime(779): at dalvik.system.NativeStart.main(Native Method)
08-12 15:49:37.657: E/AndroidRuntime(779): Caused by: java.lang.NullPointerException
08-12 15:49:37.657: E/AndroidRuntime(779): at org.apache.cordova.example.cordovaExample.onCreate(cordovaExample.java:20)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.Activity.performCreate(Activity.java:4465)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
08-12 15:49:37.657: E/AndroidRuntime(779): ... 11 more
Also, if I try the simple program I get the same result:
cordovaExample.java
package org.apache.cordova.example;
import android.content.Context;
import android.content.Intent;
import android.telephony.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import org.apache.cordova.*;
public class cordovaExample extends DroidGap
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
novel c=new novel()
int a=c.getNumber();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_LONG).show();
}
}
novel.java
package org.apache.cordova.example;
import android.content.Context;
import android.content.Intent;
import android.telephony.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class novel extends Activity
{
public int a=0;
public int getNumber()
{
a=5;
return a;
}
}
How can I resolve this?
you are using intent statement after return block
return PhoneNumber = tMgr.getLine1Number();
Intent myIntent = new Intent(novel.this, cordovaExample.class);
After return block any code show unreachable error .
After passing intent parameter then you can call return.
TelephonyManager tMgr=(TelephonyManager)mcontext.getSystemService(Context.TELEPHONY_SERVICE);
Intent intent = new Intent(this, cordovaExample.class);
intent.putExtra("novel.PhoneNumber", PhoneNumber);
startActivity(intent);
return PhoneNumber = tMgr.getLine1Number();
Android API guide contains a definitive FAQ item about how to pass data between between Activities/Services within a single application.
try this,
do like this in novel to set the phone number
Intent myIntent = new Intent(novel.this, cordovaExample.class);
myIntent.putExtra("phone", 989898989);
startActivity(myIntent);
in cordovaExample file do following to get the phoneNumber
Bundle b = this.getIntent().getExtras();
String i = b.getString("phone");
if you are not able to pass the data then alternative way is to declare public method and pass them, see following example,
novel.java
private static String phoneNumber = "";
public void onCreate()
{
...
phoneNumber = "9898989898";
...
}
public static String getPhoneNumber()
{
return phoneNumber;
}
cordovaExample.java
private static String phoneNumber = "";
phoneNumber = novel.getPhoneNumber();
Change your code to this : You got NPE in cordovaExample.java becaus in novel you put null PhoneNumber in Extra.
TelephonyManager tMgr=(TelephonyManager)mcontext.getSystemService(Context.TELEPHONY_SERVICE);
Intent intent = new Intent(this, cordovaExample.class);
PhoneNumber = tMgr.getLine1Number(); // Check PhoneNumber not null here before send to cordovaExample
if (PhoneNumber !=null ){
intent.putExtra("novel.PhoneNumber", PhoneNumber);
startActivity(intent);}
}

Having trouble passing variable to be displayed on a screen on android

I am having trouble with developing my Android application, I am currently using Eclipse and a Phidget RFID. My aim is to display the ID of the RFID in a piece of text on the Android device.
I have managed to display the ID through a println in the following pieces of code.
package myFood.myFood;
import com.phidgets.*;
import com.phidgets.event.*;
public class RFID {
static String x ="NULL";
public static final Object main(String args[]) throws Exception {
RFIDPhidget rfid;
rfid = new RFIDPhidget();
rfid.openAny();
//Begin the TagGained event, allowing for users to read the RFID values
rfid.addTagGainListener(new TagGainListener()
{
public void tagGained(TagGainEvent oe)
{
Object y = (oe.getValue());
x= y.toString();
}
});
long StartTime,RunTime;
StartTime=System.currentTimeMillis();
do{
RunTime=System.currentTimeMillis();
if (x.equals("NULL")) {
//Continue waiting for input
}
else
StartTime = 10000; //Overload the result so the loop ends
}
while (RunTime-StartTime<5000);
rfid.close();
return x;
}
}
and then.
package myFood.myFood;
public class RFIDresult {
public static final Object main(String args[]) throws Exception {
System.out.println("Results");
Object x = RFID.main(args);
System.out.println(x);
return x;
}
}
However I want the ID to be displayed in a piece of text so I tried to develop the second piece of code into Android.
package myFood.myFood;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddFood extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addfood);
Button mybutton = (Button) findViewById(R.id.Button1);
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String[] args = null;
Object x = null;
try {
x = RFID.main(args);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView mytext=(TextView)findViewById(R.id.widget96);
mytext.setText((CharSequence) x);
}
});
}
}
And this just generates a force close. I am a bit of a novice at this and will appreciate all the advice I get.
LogCat Report;
ERROR/AndroidRuntime(519): FATAL EXCEPTION: main
ERROR/AndroidRuntime(519): java.lang.ExceptionInInitializerError
ERROR/AndroidRuntime(519): at myFood.myFood.RFID.main(RFID.java:9)
ERROR/AndroidRuntime(519): at myFood.myFood.AddFood$1.onClick(AddFood.java:26)<br/>
ERROR/AndroidRuntime(519): at android.view.View.performClick(View.java:2408)
ERROR/AndroidRuntime(519): at android.view.View$PerformClick.run(View.java:8816)
ERROR/AndroidRuntime(519): at android.os.Handler.handleCallback(Handler.java:587)
ERROR/AndroidRuntime(519): at android.os.Handler.dispatchMessage(Handler.java:92)
ERROR/AndroidRuntime(519): at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(519): at android.app.ActivityThread.main(ActivityThread.java:4627)
ERROR/AndroidRuntime(519): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(519): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(519): at om.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
ERROR/AndroidRuntime(519): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
ERROR/AndroidRuntime(519): at dalvik.system.NativeStart.main(Native Method)
ERROR/AndroidRuntime(519): Caused by: java.lang.ExceptionInInitializerError: Library phidget21 not found
ERROR/AndroidRuntime(519): Could not locate the Phidget C library (libphidget21.so).
ERROR/AndroidRuntime(519): Make sure it is installed, and add it's path to LD_LIBRARY_PATH.
ERROR/AndroidRuntime(519): at com.phidgets.Phidget.<clinit>(Phidget.java:34)
ERROR/AndroidRuntime(519): ... 13 more
You need to get myText from 'view' parameter. Try this:
TextView mytext=(TextView)**view**.findViewById(R.id.widget96);

Categories