I am a beginner in android app development and was trying to build a simple MCQ quiz app.
What I did was make a two dimensional array and stored the questions, possible answers and the correct solution in it.
A sample from the table can be seen in this image:
So I named my array database. The code for creating this array called database[][] is below:
database = new String[][]{
{"Before marking the finishing line on a running track, a groundsman measures out its 100 m length. Which instrument is the most appropriate for this purpose?",
"measuring tape","metre rule","30 cm ruler","micrometer", "A"},
{"A car of mass 1500 kg travels along a horizontal road. It accelerates steadily from 10 m / s to 25 m / s in 5.0 s. What is the force needed to produce this acceleration?",
"300N","500N","4500N","D.7500N", "C"},
{"A lorry of mass 10 000 kg takes 5000 kg of sand to the top of a hill 50 m high, unloads the sand and then returns to the bottom of the hill. The gravitational field strength is 10 N / kg. What is the overall gain in potential energy?",
"250 000 J","750 000 J","2 500 000 J","D.7 500 000J", "C"},
{"A liquid-in-glass thermometer contains mercury. Which physical property of the mercury varies with temperature, enabling the thermometer to operate?",
"mass","melting point","resistance","volume", "D"},
{"Thermal energy of 12 000 J is supplied to a 2.0 kg mass of copper. The specific heat capacity of copper is 400 J / (kg °C). What is the rise in temperature?",
"15 Degree C","30 Degree C","60 Degree C","100 Degree C", "A"},
};
So each row is basically a new question with its own set of possible answers.
As for the interface, there is a textview that shows the question. There are four buttons which show each of the answers. You click on a button to answer. Then the next question is showed.
textviewQuestion.setText(database[x][y]);
buttonA.setText("A. " + database[x][1]);
buttonB.setText("B. " + database[x][2]);
buttonC.setText("C. " + database[x][3]);
buttonD.setText("D. " + database[x][4]);
Now my question is, if I want to make this app more versatile is it better to use other ways to implement the questions? I mean maybe I can store the questions in a text file? Or should I use SQLite? I don't know the pros and cons and basically what are the limitations?
I have the questions in pdf format, so can I use that to somehow link those questions directly from the pdf to the app?
Also I want to be able to ask questions which include some images. How to achieve that? Please help me out by pointing me to some good resources. Thanks a lot!
following code is help for opening pdf in your app
File pdfFile = new File(path);
if(pdfFile.exists())
{
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(uractivity.this, "File does not exist", Toast.LENGTH_LONG).show();
}
}
Related
For a little game I'm programming I'm trying to supply the user with some voice lines for flavor reasons. I've already recorded several lines, and they're all in the format of languageCode_packageName_name01.mp3.
Since I don't want the same few lines to play all the time, I intend to record several versions, and randomly pick one when retrieving them. For example, retrieving lines for "start" two times could result in playback of de_std_start01 and then de_std_start06.
Since I am quite new to android I'd like to ask for help regarding this implementation. I'm not sure whether I should utilize the raw folder for this task, or the assets folder. If possible, I would like to implement a folder structure like this, which would to my understanding need the use of the assets folder, in order to be able to simply drag & drop new files inside the folder, which will then be taken into account for random selection.:
<root folder>
- de
-- std
--- start
---- start01.mp3
---- start02.mp3
...
When given arguments specifying de, std and start, how would I go about retrieving the different files and randomly pick one of them? Thanks for your help!
If you include them in the raw folder, you should be able to access them as so:
//from your activity
AudioService audioService = new AudioService;
int randomTune = audioService.getRandom();
MediaPlayer mediaPlayer = MediaPlayer.create(context, randomTune);
mediaplayer.start;
//From a seperate service class
Class AudioService {
private int[] audioFiles = {
R.raw.song1, R.raw.song2, R.raw.song3, R.raw.song4, R.raw.song5, R.raw.song6
};
I believe that your folder structure will be somewhat flexible since you are wrapping the actual resource with the R class and referencing that in your code.
public int getRandom(){
// Here i am asking for a random number between 0 and 1, multiplying by 6, rounding
// it down, and explicitly casting to int.
// Result will be random int between 0 and 5. This will be the array index that
// randomly chooses the song.
private int randomIndex;
randomindex = (int) Math.floor(6 * Math.random);
return this.audioFiles[randomIndex];
}
}
I am creating a blood bank app in which I am showing the user, his current position and different donors available near him on a map. When the user clicks on the blood request button, I show him a list of different donors available near him. Now on the list with the names of donors, I want to show the distance of that donor from the user current location. Right now I am getting distance by line which always shows 56 KM less than the actual distance. For that I am doing this :
donarLat = profiles.getLatitude();
donarLong = profiles.getLongitude();
String distance = "";
if (currentLat != null && currentLong != null && donarLat != null && donarLong != null) {
origin = new LatLng(currentLat, currentLong);
dest = new LatLng(donarLat, donarLong);
float[] result = new float[1];
// Location.distanceBetween(currentLat, currentLong,donarLat, donarLong, result);
distance = String.valueOf(SphericalUtil.computeDistanceBetween(origin,dest));
System.out.println("d9" + profiles.getName()+ " : " + distance);
I have also got the distance using Location as you can see the commented line in code but it all gives location by line but I want to get the Location by road for which I have seen a lot of answers on StackOverflow which was answered minimum 6 years ago and also tried but sometimes it crashes app or some times it does nothing. I assume that for location by the road, I have to use google direction API but how I don't understand how to use it. I have tried that API in postman but first, it gave me an error to enable direction API after doing that it asked me to enable billing method. I am attaching the photo of Postman. And will be really thankful if someone shows me how to use API properly to get the exact distance by road.
Google API is not FREE now
Some API is free for some period but charge cost after that trial period.
And they require an API key with billing info to use trial.
In your case you have to your API key is not valid.
Create an API key with billing info form this link and be sure you can use it for a trial period. If not you may get changed.
I'm developing an Android app, for a research, and im reading several Sensor data like accelerometer, gyroscope, barometer etc.
So I have 4 Nexus 6P devices all with the newest Factory Image and freshly set up with no other app installed than the standard once which are pre-installed.
So the Problem that occurs now is that one of the phones is constantly lagging behind, so for example i record for half an hour the accelerometer at 105 Hz (so the max possible rate for the accelerometer is 400Hz), just to make sure i get at least about the amount of samples i would expect for 100Hz and the results are the following:
Smapling for Half an hour at 100Hz -> 180000 Samples
Smapling for Half an hour at 105Hz -> 189000 Samples
(This is now just an example for the accelerometer but is the same for every other sensor on each device. So device 1,3,4 get about the same good results for other senors while device 2 gets the same bad results on all other sensors).
Device 1: 180000 Samples
Device 2: 177273 Samples <- the phone that is lagging behind
Device 3: 181800 Samples
Device 4: 179412 Samples
So the problem is at device number 2 where I'm missing almost 3000 Samples (I know this is crying at a high level) and my guess for this problem is that it is probably Hardware related. That it might be a performance issue i can probably rule out since it does not matter how many Sensors im reading and also reading them at 400Hz works as expected (if wanted i can also offer the Samples for this too). I also tried to set the sampling rate to 400Hz so to the fastest and then take recordings according to the timestamp which led to the same result.
So just in case I'll provide how I register the Sensor Listener:
protected void onCreate(Bundle savedInstanceState){
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
unaccDataSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED);
}
....
private void Start(){
sensorManager.registerListener(unaccDataListener, unaccDataSensor, 10000);
}
So what i want is to get at least about the amount of samples that i should expect so above is no problem and just a bit below is also acceptable.
So if anyone has an idea about what else I can try or what can cause the problem i would be really thankful.
This is my first Post so if anything is missing or if i explained something in a bad way im sorry and i try my best to fix it.
I work with Android sensors a lot, and i can tell you the hardware is of variable quality. I usually use a filter if I need the results to be consistent across phones:
// Filter to remove readings that come too often
if (TS < LAST_TS_ACC + 100) {
//Log.d(TAG, "onSensorChanged: skipping");
return;
}
however this means you can only set the phones to match the lowest common denominator. If it helps I find that getting any more than 25hz is overkill for most applications, even medical ones.
It can also help to make sure any file writes you are doing are done off thread, and in batches, as writing to file is an expensive operation.
accelBuffer = new StringBuilder();
accelBuffer.append(LAST_TS_ACC + "," + event.values[0] + "," + event.values[1] + "," + event.values[2] + "\n");
if((accelBuffer.length() > 500000) && (writingAccelToFile == false) ){
writingAccelToFile = true;
AccelFile = new File(path2 +"/Acc/" + LAST_TS_ACC +"_Service.txt");
Log.d(TAG, "onSensorChanged: accelfile created at : " + AccelFile.getPath());
File parent = AccelFile.getParentFile();
if(!parent.exists() && !parent.mkdirs()){
throw new IllegalStateException("Couldn't create directory: " + parent);
}
//Try threading to take of UI thread
new Thread(new Runnable() {
#Override
public void run() {
//Log.d(TAG, "onSensorChanged: in accelbuffer");
// Log.d(TAG, "run: in runnable");
//writeToStream(accelBuffer);
writeStringBuilderToFile(AccelFile, accelBuffer);
accelBuffer.setLength(0);
writingAccelToFile = false;
}
}).start();
}
Doing all of the above has got me reasonably good results, but it will never be perfect due to differences in the hardware.
Good luck!
so, the last days I've been playing arround with the Google speech API to perform simple voice recognition tasks. I got one upload script - working perfectly - uploading an .wav file and receiving the said words back. I also got a good microphone. The problem is:
When listening to my microphone input from System Settings or from Audacity, there is no noise in the background. But as soon as I record with Java, my samples get inaccurate and impossible for Googles servers to parse. I already tried to smooth out the audio, with success on the result, but the servers can't process the sounds when the consonants like "T" or "K" are missing.
So, now I would like to do a bandpass filter, to filter out the frequency spectrum I want (voice spectrum from about 100Hz to 600Hz). The problem is, I don't know where to start. I would like to add the filter to the following method:
static int spikesensitivity = 50;
static int sens = 7;
static byte smoothedValue = 0;
static int smoothing = 2;
public static byte[] removeNoise(byte[] b, TargetDataLine line ){
byte[] returnThis = new byte[b.length];
for( int i = 0; i < b.length; i++){
smoothedValue += (b[i] - smoothedValue) / smoothing;
returnThis[i] = smoothedValue;
}
return returnThis;
}
The TargetDataLines datarates are: 16000Hz, 8 bit, mono, PCM, 1 channel (1 byte per frame).
Just in case someone experienced something similar: Why is audio recording in Java so bad? All my other programs (non-Java) seem to get better voice input than I can obtain using Java. The noise is always there, no matter what frequency or setup i choose - but as soon as I try the same settings in any other program, the noise is gone :/
Thank you in advance for your time reading/replying to this :)
Line opening snippet: http://pastebin.com/qtEyNmCe
I know how to get the current GPS location of a mobile phone.
I also know how to save the GPS location to the photo when you take it. (Camera option Samsung galaxy s2).
But how can I get the GPS location of that photo (later)?
When I open the photo on the computer, I can see the GPS location data, but got no idea how to extract them later in android. So could someone put me in the good direction?
To make question more clearly:
How can I get the GPS location of a photo that is already taken?
Thanks already,
Bigflow
josnidhin made this answer possible, so be sure to give him credit too :)
Here we go:
import android.media.ExifInterface;
exif = new ExifInterface(filePath);
String lat = ExifInterface.TAG_GPS_LATITUDE;
String lat_data = exif.getAttribute(lat);
After that, lat_data will be something like: 51/1,58/1,32/1
This is the same as: 51, 58, 32. (typing this in google maps will give bad result)
To get the gps coordinates of this you need to do some math, here it comes:
Calculate the total number of seconds:
58′32″ = (58*60 + 32) = 3512
seconds.
The fractional part is total number of seconds divided by 3600:
3512 / 3600 = ~0.975556
Add fractional degrees to whole degrees to produce the final result:
51 + 0.975556 = 51.975556
If it is a West longitude coordinate, negate the result. (it isn't this time)
answer: 51.975556
This is also the same when you with TAG_GPS_LONGITUDE
I think the geotag is in the EXIF data of the photo taken. Find a suitable EXIF data reader which will help you extract the data you want.