This might be a very naive question but I can't get this java.lang.Exception error to go away. I also just started learning java and android so... this might be an easy problem to solve.
So I have a main activity in android and I want to implement a weka ml classifier within the app. Right now I'm just trying to load some data.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ml_classifiers ml_object = new ml_classifiers();
int number = ml_object.loadData();
Trying to load data...
public class ml_classifiers {
public int loadData() {
ConverterUtils.DataSource source = new ConverterUtils.DataSource("C:/Users/Seth/Desktop/iris.arff");
Instances data = source.getDataSet();
int num = data.numInstances();
return num;
}
}
Why does java.lang.exception occur?
Why does java.lang.exception occur?
In the future, when you encounter crashes, use LogCat to examine the Java stack trace associated with the crash. If you do not understand the stack trace or otherwise cannot identify the problem, and you want help here, post the stack trace along with the code. As it stands, we have to guess exactly what is going wrong in your app.
In this case, while you may be crashing elsewhere, you will definitely crash with:
ConverterUtils.DataSource source = new ConverterUtils.DataSource("C:/Users/Seth/Desktop/iris.arff");
assuming that this is code in your Android app.
You are attempting to read data from C:/Users/Seth/Desktop/iris.arff. That is a path to a file on a Windows machine. Android is not Windows. There are ~2 billion Android devices in use, and none of them have access to files on your Windows' machine's desktop.
You need to get this data onto the Android device, such as:
by putting it in the assets/ directory in your module (to package it with your app), then using AssetManager to get an InputStream on that asset, hopefully passing that directly to ConverterUtils.DataSource
downloading the file from the Internet, perhaps into internal storage (e.g., getCacheDir())
expecting the user to copy the file onto their device by hand, such as via external storage
Related
I've written an Android app that is a simpler version of the stock camera. It only records video.
Despite this being a custom app, I'd like to have the videos recorded by this be easily visible from the Photos and Gallery apps.
I was under the impression that this is what the "MediaScannerConnection" class is for. I've found common advice that shows how to use this in either a "sendBroadcast" mode, or a more manual "scanFile" approach. I've implemented both of these options and found that they appear to have no effect. When I stop the recorder, a valid video is stored (I can play it from a file browser afterwards), but neither Photos or Gallery is made aware of the new video.
I've been storing the videos in files like "/storage/emulated/0/DCIM/Camera/20151223_150115.mp4". That directory also contains videos taken by the stock camera app. The base path was obtained from "Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)". I originally tried replacing "Camera" with a directory name based on the name of my app, but as that wasn't working (Photos/Gallery not seeing it, despite it being stored properly), I decided to try storing them where the stock videos are stored. That isn't working either.
My test device is a Galaxy Note 3, running Android 5.0.
My first attempt at using MediaScannerConnection was with this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + outputFilePath)));
One of the values of "outputFilePath" is exactly the path shown above.
As this didn't appear to do anything, I then later tried this:
new SingleMediaScanner(getApplicationContext(), new File(outputFilePath));
Where "SingleMediaScanner" is this:
public static class SingleMediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
#Override
public void onMediaScannerConnected() {
mMs.scanFile(mFile.getAbsolutePath(), "image/*");
}
#Override
public void onScanCompleted(String path, Uri uri) {
mMs.disconnect();
}
}
I tried running the last implementation in the debugger, and I saw it get to "onScanCompleted", but neither of the aforementioned apps see the new video.
Update:
With the current implementation, the "onScanCompleted" callback method gets called with "path" and "uri" parameters, which have the following values:
path: /storage/emulated/0/DCIM/Camera/20151223_194434.mp4
uri.toString(): content://media/external/file/106639
Uri.fromFile(new File(Path)): file:///storage/emulated/0/DCIM/Camera/20151223_194434.mp4
I'm basically writing my first hello world in android studio and the java file says that the xml layout file and other resources in the res file don't exist. I took the references to these things from books/tutorials so they should work.
The book said to use
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main.xml);
}
But when that didn't work I changed it to res.layout.activity_main.xml
my project directory looks like this
How do I make it work?
http://i.stack.imgur.com/N71sl.png
//EDIT
http://i.stack.imgur.com/HUgsm.png
You are referencing res not R.
do something like this: setContentView( R.layout.activity_main);
Leave off the ".xml"
update your android studio in stable channel and restart android studio and build the project again .
You need to understand the concept of the R class in android.
The R class is auto generated every time you build your project and cannot be modified.
This class contains a map of all the projects assets. Every time you created or import a resource, set a dimension, a string, create a layout, add or change id etc. the R file is changed in the background.
So if you want to access a resource you simply call it using the R class.
For example:
layout: R.layout.activity_main
string: R.string.hello_world
id: R.id.et_main_helloWorld
And so on.
More info can be found here.
Make sure you also check Providing Resources and Accessing Resources for a better understanding.
Good luck and happy coding.
In the end I started a new project and added in everything piece by piece, I had put a mp3 file in the values directory which was messing up the R file.
When I build up the APK, I find out the KEYs of JSON changed when I use the Network. I just fund out that it is a problem about ProGuard.
I have added "#SerializedName" to every variables in Request/Response Folder. And added
-keepclassmembernames class com.mygroup.myapp.protocol.response.Responsexx {
public *;}
for every Resquest/Response JAVA program, which took me much time but doesn't work.
My app crashed after I get the response, the logcat says com.b.a.b.w cannot be cast to com.mygroup.myapp.b.g , and I have located the error:
private List<UserInfoModel> mUserList = new ArrayList<>();
private UserInfoModel UserInfo = new UserInfoModel();
if (mUserList.size()>0)
UserInfo = mUserList.get(0); //CRASHED HERE
I am sure that the size of mUserList is 1, I made a toast and saw it.
Please Help Me. Much Thanks.
Moreover, the IDE I am using is Android Studio.
I'm using Cordova v4.1.2. The app uses media volume by default, and I want it to use the ringer volume for the sounds it plays. (Like in WhatsApp)
I used setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);in the onCreate() function. But it gives an error.
This is my CordovaApp.java. (in platforms\android\src\com\XX\XX)
import android.os.Bundle;
import org.apache.cordova.*;
public class CordovaApp extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
}
It shows the following error on running:
There is no error when I remove the line setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); from the java file, and the app runs perfectly. Any views on how to fix this?
Fixed it myself. Really easy if you were an Android geek, but anyways such a question was never asked before so I'll post the answer for others running into this same trouble.
I was right in changing the audio stream, but I was changing that in the wrong file! Doh!
This is where you should change it..
\platforms\android\CordovaLib\src\org\apache\cordova\CordovaActivity.java
at line 351 change it to setVolumeControlStream(AudioManager.STREAM_RING);
If you want to use the ringer volume though.
If you build and press the hardware volume keys, it will change and appear to use the ringer volume of course. But my case was a bit different.
I was using the cordova Media plugin org.apache.cordova.media. So when I play an audio using this plugin, it re-wires the stream back to media stream (STREAM_MUSIC). I was back to ground zero. The idea is to re-wire the plugin itself to use the audio stream of your choice. No rocket science, just change 2 lines in 2 files.
File:
\platforms\android\src\org\apache\cordova\media\AndroidHandler.java
Line 383:
setVolumeControlStream(AudioManager.STREAM_RING);
File:
\platforms\android\src\org\apache\cordova\media\AudioPlayer.java
Line 526:
setVolumeControlStream(AudioManager.STREAM_RING);
And you're good to go. Remember to replace STREAM_RING with your desired audio stream.
My work computer that Eclipse is installed on does not have internet connectivity due to work related issues so all code and LogCat text has been hand typed instead of copy and pasted since I am on a separate laptop that Eclipse is installed right now. So bear with me for any typos.
Now to the issue. In the new version of my app, I am making it Spanish supported. I localized all my strings in strings.xml. Below is my Java code that I am not usuing to implement.
public class SplashScreen extends SwarmActivity {
Context c;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
loading = (TextView)findViewById(R.id.loading);
//loading.setText(c.getResources().setString(R.string.loading)); //This way gives NPE
//loading.setText(R.string.loading); //This way works
//loading.setText("Test"); //This way works
}
}
If I understand localization correctly, I have to getResources() first so the app knows what language of the string to display. But the getResources() is what is messing me up.
What do I need to do to get the string displaying correctly?
To answer your problem, your forgot to initialize your Context object. So c is null. Replace
loading.setText(c.getResources().setString(R.string.loading));
by
loading.setText(getResources().setString(R.string.loading));
But actually there is no need to do that.
Android loads the appropriate resources according to the locale settings of the device at run time.
You just have to respect this hierarchy in your project :
res/
values/
strings.xml
values-es / (here for spanish values)
strings.xml
values-fr /
strings.xml (here for french values)
You have this code
Context c;
public void onCreate(Bundle savedInstanceState) {
...
loading.setText(c.getResources().setString(R.string.loading)); //This way gives NPE
The member c is never set before it is used. This is the reason for the NullPointerException. You must first initialize c with View.getContext() for example.
Localization is handled automatically according to the device's capabilities and settings.
In your layout definition, you can define the text string with a reference to a string id and Android will automatically load the appropriate resource
In res/layout/splashscreen.xml:
...
<TextView android:id="#+id/loading"
android:text="#string/loading"
.../>
...
So there is no need to explicitly set the text string in your code, because Android will do so already. The only thing you have to do, is to define the appropriate text strings in the res/values*/strings.xml files.