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);
Related
i made a small method to check whether defined folder has files with a specific extension or not. I m getting null point exception on run.pls help to find mistake.method is checking .mp4 files and returning true if found and message is displayed.
Here is Code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView filecheck;
filecheck = (TextView) findViewById(R.id.filecheck);
filecheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (accept()) {
Toast.makeText(MainActivity.this, "Files Found", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Files Not Found", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean accept() {
final File pathname = new File("/sdcard/test/");
String files[] = pathname.list();
System.out.println(files.length);
for (String s : files) {
if (s.contains(".mp4")) {
System.out.println(s);
return true;
}
return false;
}
return false;
}
}
Here is exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: jss.testmethods, PID: 23659
java.lang.NullPointerException
at jss.testmethods.MainActivity.accept(MainActivity.java:38)
at jss.testmethods.MainActivity$1.onClick(MainActivity.java:24)
at android.view.View.performClick(View.java:4478)
at android.view.View$PerformClick.run(View.java:18698)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
i was expecting simple error, i missed to add permission for read storage. it is working now.
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.
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.
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);
I need to load a text file which is placed in res/raw directory into memory. Here is my code:
package com.ggd543.android;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
public class FileActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadText();
}
private void loadText() {
// InputStream is = Resources.getSystem().openRawResource(R.raw.text);
InputStream is = getResources().openRawResource(R.raw.text);
try {
byte[] buf = new byte[is.available()];
is.read(buf, 0, buf.length);
((TextView) findViewById(R.layout.main)).setText(new String(buf, "UTF-8"));
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
When I deploy the .apk on emulator and start it up, I got the following error:
12-25 14:33:38.096: ERROR/AndroidRuntime(3077): Uncaught handler: thread main exiting due to uncaught exception
12-25 14:33:38.106: ERROR/AndroidRuntime(3077): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ggd543.android/com.ggd543.android.FileActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x7f030000
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
at android.app.ActivityThread.access$2200(ActivityThread.java:119)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f030000
at android.content.res.Resources.getValue(Resources.java:891)
at android.content.res.Resources.openRawResource(Resources.java:816)
at android.content.res.Resources.openRawResource(Resources.java:798)
at com.ggd543.android.FileActivity.loadText(FileActivity.java:23)
at com.ggd543.android.FileActivity.onCreate(FileActivity.java:19)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
... 11 more
Could anyone give me suggestion ?
Thx
Move the file to the assets folder.
Then retrieve the stream like this InputStream is = getAssets().open("fileName");
if you have assets/mytxtfile.txt
then fileName = "mytxtfile.txt"
What is the file name ? coz as per odcs, if you've a file called 'abcd.txt' in /res/raw, you're suppose to open it using resource ID "R.raw.abcd", i.e. excluding the 3 digit extension.