Open2.4.5 Android Crashes when I call Mat - java

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.

Related

NullPointerException in onCreateOptionsMenu in Android FragmentActivity

Here, this is detailActivity.java which gathers data from openWeatherAPI and populates the data into a listView. When I click on the item on listView there is NPE in OnCreateOptionsMenu.
package com.example.sunshine2;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.sunshine2.data.WeatherContract.WeatherEntry;
public class DetailActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, 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) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class DetailFragment extends Fragment implements
LoaderCallbacks<Cursor> {
private static final String LOG_TAG = DetailFragment.class
.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private ShareActionProvider mShareActionProvider;
private String mForecast;
private static final int DETAIL_LOADER = 0;
private static final String[] FORECAST_COLUMNS = {
WeatherEntry.TABLE_NAME + "." + WeatherEntry._ID,
WeatherEntry.COLUMN_DATE, WeatherEntry.COLUMN_SHORT_DESC,
WeatherEntry.COLUMN_MAX_TEMP, WeatherEntry.COLUMN_MIN_TEMP, };
// these constants correspond to the projection defined above, and must
// change if the
// projection changes
private static final int COL_WEATHER_ID = 0;
private static final int COL_WEATHER_DATE = 1;
private static final int COL_WEATHER_DESC = 2;
private static final int COL_WEATHER_MAX_TEMP = 3;
private static final int COL_WEATHER_MIN_TEMP = 4;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is
// present.
inflater.inflate(R.menu.detail_fragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat
.getActionProvider(menuItem);
// If onLoadFinished happens before this, we can go ahead and set
// the share intent now.
if (mForecast != null) {
mShareActionProvider
.setShareIntent(createShareForecastIntent());
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast
+ FORECAST_SHARE_HASHTAG);
return shareIntent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.v(LOG_TAG, "In onCreateLoader");
Intent intent = getActivity().getIntent();
if (intent == null) {
return null;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(getActivity(), intent.getData(),
FORECAST_COLUMNS, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.v(LOG_TAG, "In onLoadFinished");
if (!data.moveToFirst()) {
return;
}
String dateString = Utility.formatDate(data
.getLong(COL_WEATHER_DATE));
String weatherDescription = data.getString(COL_WEATHER_DESC);
boolean isMetric = Utility.isMetric(getActivity());
String high = Utility.formatTemperature(
data.getDouble(COL_WEATHER_MAX_TEMP), isMetric);
String low = Utility.formatTemperature(
data.getDouble(COL_WEATHER_MIN_TEMP), isMetric);
mForecast = String.format("%s - %s - %s/%s", dateString,
weatherDescription, high, low);
TextView detailTextView = (TextView) getView().findViewById(
R.id.detail_text);
detailTextView.setText(mForecast);
// If onCreateOptionsMenu has already happened, we need to update
// the share intent now.
if (mShareActionProvider != null) {
mShareActionProvider
.setShareIntent(createShareForecastIntent());
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
}
And Here is the LogCat
04-13 01:22:51.916: E/AndroidRuntime(20197): FATAL EXCEPTION: main
04-13 01:22:51.916: E/AndroidRuntime(20197): Process: com.example.sunshine2, PID: 20197
04-13 01:22:51.916: E/AndroidRuntime(20197): java.lang.NullPointerException
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.example.sunshine2.DetailActivity$DetailFragment.onCreateOptionsMenu(DetailAc tivity.java:117)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1582)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1967)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivityDelegateICS.onCreatePanelMenu(ActionBarActivityDelegateICS.java:146)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivity.onCreatePanelMenu(ActionBarActivity.java:199)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.onCreatePanelMenu(ActionBarActivityDelegateICS.java:293)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:803)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:221)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Handler.handleCallback(Handler.java:733)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Handler.dispatchMessage(Handler.java:95)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Looper.loop(Looper.java:149)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.app.ActivityThread.main(ActivityThread.java:5077)
04-13 01:22:51.916: E/AndroidRuntime(20197): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 01:22:51.916: E/AndroidRuntime(20197): at java.lang.reflect.Method.invoke(Method.java:515)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
04-13 01:22:51.916: E/AndroidRuntime(20197): at dalvik.system.NativeStart.main(Native Method)
I've tried debugging the code, but the
- mShareActionProvider gives me null, which I can't figure out how
I think the problem is you have a onClick function declared in your XML menu layout file but no corresponding function in your code.

Missing file through getAssets

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.

Bluetooth Messenger application crashing at start up itself

I have tried to learn to write an application which is basically a bluetooth messenger. Things had been fine unless I tried to install and run it. It gets installed successfully but crashes down at start up itself. Can you please tell me what is wrong ?
This is the code for the main activity. There are three more activities apart from this.
import java.io.IOException;
import java.util.ArrayList;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public final static String UUID = "3606f360-e4df-11e0-9572-0800200c9a66";
BluetoothAdapter bluetoothAdapter;
BroadcastReceiver discoverDevicesReceiver;
BroadcastReceiver discoveryFinishedReceiver;
//---store all the discovered devices---
ArrayList<BluetoothDevice> discoveredDevices;
ArrayList<String> discoveredDevicesNames;
//---store all the paired devices---
ArrayList<BluetoothDevice> pairedDevices;
static TextView txtData;
EditText txtMessage;
//---thread for running the server socket---
ServerThread serverThread;
//---thread for connecting to the client socket---
ConnectToServerThread connectToServerThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---init the ArrayList objects and bluetooth adapter---
discoveredDevices = new ArrayList<BluetoothDevice>();
discoveredDevicesNames = new ArrayList<String>();
pairedDevices = new ArrayList<BluetoothDevice>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//---for displaying the messages received---
txtData = (TextView) findViewById(R.id.txtData);
txtMessage = (EditText) findViewById(R.id.txtMessage);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//---make yourself discoverable---
public void MakeDiscoverable(View view)
{
Intent i = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(i);
}
/*
//---find all the previously paired devices---
private void QueryPairedDevices(){
Set<BluetoothDevice> allPairedDevices =
bluetoothAdapter.getBondedDevices();
//---if there are paired devices---
if (allPairedDevices.size() > 0) {
//---loop through paired devices---
for (BluetoothDevice device : allPairedDevices) {
//---add the name and address to an array adapter
// to show in a ListView---
Log.d("UsingBluetooth", device.getName() + "\n" +
device.getAddress());
pairedDevices.add(device);
}
}
}
*/
//---used to discover other bluetooth devices---
private void DiscoveringDevices() {
if (discoverDevicesReceiver == null) {
discoverDevicesReceiver = new BroadcastReceiver() {
//---fired when a new device is discovered---
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//---a device is discovered---
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//---get the BluetoothDevice object from
// the Intent---
BluetoothDevice device =
intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE);
//---add the name and address to an array
// adapter to show in a ListView---
//---only add if the device is not already
// in the list---
if (!discoveredDevices.contains(device)) {
//---add the device---
discoveredDevices.add(device);
//---add the name of the device; used for
// ListView---
discoveredDevicesNames.add(device.getName());
//---display the items in the ListView---
setListAdapter(new
ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_list_item_1,
discoveredDevicesNames));
}
}
}
};
}
if (discoveryFinishedReceiver==null) {
discoveryFinishedReceiver = new BroadcastReceiver() {
//---fired when the discovery is done---
#Override
public void onReceive(Context context, Intent intent) {
//---enable the listview when discovery is over; about 12 seconds---
getListView().setEnabled(true);
Toast.makeText(getBaseContext(),
"Discovery completed. Select a device to start chatting.",
Toast.LENGTH_LONG).show();
unregisterReceiver(discoveryFinishedReceiver);
}
};
}
//---register the broadcast receivers---
IntentFilter filter1 = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
IntentFilter filter2 = new
IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoverDevicesReceiver, filter1);
registerReceiver(discoveryFinishedReceiver, filter2);
//---disable the listview when discover is in progress---
getListView().setEnabled(false);
Toast.makeText(getBaseContext(),
"Discovery in progress...please wait...",
Toast.LENGTH_LONG).show();
bluetoothAdapter.startDiscovery();
}
//---discover other bluetooth devices---
public void DiscoverDevices(View view)
{
//---query for all paired devices---
//QueryPairedDevices();
//---discover other devices---
DiscoveringDevices();
}
#Override
public void onPause() {
super.onPause();
//---cancel discovery of other bluetooth devices
bluetoothAdapter.cancelDiscovery();
//---unregister the broadcast receiver for
// discovering devices---
if (discoverDevicesReceiver != null) {
try {
unregisterReceiver(discoverDevicesReceiver);
} catch(Exception e) {
}
}
//---if you are currently connected to someone...---
if (connectToServerThread!=null) {
try {
//---close the connection---
connectToServerThread.bluetoothSocket.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
}
//---stop the thread running---
if (serverThread!=null) serverThread.cancel();
}
//---used for updating the UI on the main activity---
static Handler UIupdater = new Handler() {
#Override
public void handleMessage(Message msg) {
int numOfBytesReceived = msg.arg1;
byte[] buffer = (byte[]) msg.obj;
//---convert the entire byte array to string---
String strReceived = new String(buffer);
//---extract only the actual string received---
strReceived = strReceived.substring(
0, numOfBytesReceived);
//---display the text received on the TextView---
txtData.setText(txtData.getText().toString() +
strReceived);
}
};
#Override
public void onResume() {
super.onResume();
//---start the socket server---
serverThread = new ServerThread(bluetoothAdapter);
serverThread.start();
}
//---when a client is tapped in the ListView---
public void onListItemClick(ListView parent, View v,
int position, long id) {
//---if you are already talking to someone...---
if (connectToServerThread!=null) {
try {
//---close the connection first---
connectToServerThread.bluetoothSocket.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
}
//---connect to the selected Bluetooth device---
BluetoothDevice deviceSelected =
discoveredDevices.get(position);
connectToServerThread = new
ConnectToServerThread(deviceSelected, bluetoothAdapter);
connectToServerThread.start();
//---tell the user that he is connected to who---
Toast.makeText(this, "You have connected to " +
discoveredDevices.get(position).getName(),
Toast.LENGTH_SHORT).show();
}
private class WriteTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... args) {
try {
connectToServerThread.commsThread.write(args[0]);
} catch (Exception e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
return null;
}
}
//---send a message to the connected socket client---
public void SendMessage(View view)
{
if (connectToServerThread!=null) {
///=========
//connectToServerThread.commsThread.write(
// txtMessage.getText().toString());
new WriteTask().execute(txtMessage.getText().toString());
///=========
} else {
Toast.makeText(this, "Select a client first",
Toast.LENGTH_SHORT).show();
}
}
}
ServerThread class :
import java.io.IOException;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ServerThread extends Thread {
//---the server socket---
private final BluetoothServerSocket bluetoothServerSocket;
public ServerThread(BluetoothAdapter bluetoothAdapter) {
BluetoothServerSocket tmp = null;
try {
//---UUID must be the same for both the client and
// the server---
tmp =
bluetoothAdapter.listenUsingRfcommWithServiceRecord(
"BluetoothApp", UUID.fromString(MainActivity.UUID));
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
}
bluetoothServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
//---keep listening until exception occurs
// or a socket is returned---
while (true) {
try {
socket = bluetoothServerSocket.accept();
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
break;
}
//---if a connection was accepted---
if (socket != null) {
//---create a separate thread to listen for
// incoming data---
CommsThread commsThread = new CommsThread(socket);
commsThread.run();
}
}
}
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
}
}
}
LogCat
04-13 18:25:06.684: D/AndroidRuntime(397): Shutting down VM
04-13 18:25:06.684: W/dalvikvm(397): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-13 18:25:06.704: E/AndroidRuntime(397): FATAL EXCEPTION: main
04-13 18:25:06.704: E/AndroidRuntime(397): java.lang.RuntimeException: Unable to resume activity {net.learn2develop.usingbluetooth/net.learn2develop.usingbluetooth.MainActivity}: java.lang.NullPointerException
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.os.Looper.loop(Looper.java:123)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-13 18:25:06.704: E/AndroidRuntime(397): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 18:25:06.704: E/AndroidRuntime(397): at java.lang.reflect.Method.invoke(Method.java:507)
04-13 18:25:06.704: E/AndroidRuntime(397): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-13 18:25:06.704: E/AndroidRuntime(397): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-13 18:25:06.704: E/AndroidRuntime(397): at dalvik.system.NativeStart.main(Native Method)
04-13 18:25:06.704: E/AndroidRuntime(397): Caused by: java.lang.NullPointerException
04-13 18:25:06.704: E/AndroidRuntime(397): at net.learn2develop.usingbluetooth.ServerThread.<init>(ServerThread.java:21)
04-13 18:25:06.704: E/AndroidRuntime(397): at net.learn2develop.usingbluetooth.MainActivity.onResume(MainActivity.java:235)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.Activity.performResume(Activity.java:3832)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
04-13 18:25:06.704: E/AndroidRuntime(397): ... 12 more
04-13 18:25:08.764: I/Process(397): Sending signal. PID: 397 SIG: 9
04-13 18:25:10.354: D/AndroidRuntime(415): Shutting down VM
04-13 18:25:10.354: W/dalvikvm(415): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-13 18:25:10.364: E/AndroidRuntime(415): FATAL EXCEPTION: main
04-13 18:25:10.364: E/AndroidRuntime(415): java.lang.RuntimeException: Unable to resume activity {net.learn2develop.usingbluetooth/net.learn2develop.usingbluetooth.MainActivity}: java.lang.NullPointerException
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.os.Looper.loop(Looper.java:123)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-13 18:25:10.364: E/AndroidRuntime(415): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 18:25:10.364: E/AndroidRuntime(415): at java.lang.reflect.Method.invoke(Method.java:507)
04-13 18:25:10.364: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-13 18:25:10.364: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-13 18:25:10.364: E/AndroidRuntime(415): at dalvik.system.NativeStart.main(Native Method)
04-13 18:25:10.364: E/AndroidRuntime(415): Caused by: java.lang.NullPointerException
04-13 18:25:10.364: E/AndroidRuntime(415): at net.learn2develop.usingbluetooth.ServerThread.<init>(ServerThread.java:21)
04-13 18:25:10.364: E/AndroidRuntime(415): at net.learn2develop.usingbluetooth.MainActivity.onResume(MainActivity.java:235)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.Activity.performResume(Activity.java:3832)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
04-13 18:25:10.364: E/AndroidRuntime(415): ... 12 more
04-13 18:25:13.304: I/Process(415): Sending signal. PID: 415 SIG: 9
Possible changes you can try which might help you.
In ServerThread.java
public void run() {
....
while(!Thread.currentThread().isInterrupted()){
//do something
}
}
If this works fine, otherwise try:
In MainActivity.java
#Override
public void onCreate() {
....
//Start your thread here
//---start the socket server---
serverThread = new ServerThread(bluetoothAdapter);
serverThread.start();
}
#Override
public void onResume() {
super.onResume();
//handle your thread here - the following maynot be helpful, but logiaclly speaking, //you must handle your threads here
if(serverThread.isAlive())
serverThread.resume();
else
serverThread.interrupt();
}

How can I access a function in another class?

I am developing an app for android that has to access another class, but i don't know why it doesn't work.
When run the App in android 2.3.3 it force closes, and I don't understand why. I think that the method is correct.
Log in the force close the phone android:
> app_vercode:1
device_model:u8800
build_version:111180
condition:1
processName:beta.tester
pid:13277
uid:10088
tag:null
shortMsg:java.lang.NullPointerException
longMsg:java.lang.NullPointerException: Unable to start activity ComponentInfo{beta.tester/beta.tester.BetaTesterActivity}: java.lang.NullPointerException
stackTrace:java.lang.RuntimeException: Unable to start activity ComponentInfo{beta.tester/beta.tester.BetaTesterActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3703)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at beta.tester.BetaTesterActivity.onCreate(BetaTesterActivity.java:23)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1628)
... 11 more
Detail logs:
EDIT: This code already is correctly.
The code:
class BetaTesterActivity:
package beta.tester;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class BetaTesterActivity extends Activity {
public TextView text1;
private teste cmd;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text1 = (TextView) findViewById(R.id.text1);
//Start the function
cmd = new teste();
cmd.start(this);
}
}
class teste:
package beta.tester;
public class teste {
//Function that I will start
public void start(BetaTesterActivity zav){
zav.text1.setText("Hello");
}
//
}
In class teste, you are creating a new BetaTesterActivity, which is useless. You need to use the instance created by the framework. Change your class teste to this:
public class teste {
//Function that I will start
public void start(BetaTesterActivity zav){
zav.text1.setText("Hello");
}
}
Then in the onCreate method of your activity class, you need to initialize cmd and then call start like this:
cmd.start(this);

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