convert array by split to integer - java

I get error :
FATAL EXCEPTION: main at java.lang.Integer.invalidInt
for this block :
int f = Integer.parseInt(c[1]);
limitter.setProgress(f);
limit.setText(f + " A");
MAIN CODE:
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
String[] c = data.split("limit");
int x = c.length;
if(x>1){
int f = Integer.parseInt(c[1]);
limitter.setProgress(f);
limit.setText(f + " A");
}
What is wrong?
Here is the stack trace:
FATAL EXCEPTION: main
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.tos.hidro.Terminal$2$1.run(Terminal.java:207)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4987)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

Related

RuntimeException: "Number of sync samples doesn't match the number of stills" while making video from images using mp4parser

I want to create a video from multiple images using mp4parser. And I found answer from this link : https://github.com/sannies/mp4parser/issues/182
I have tried it using below code.
DataSource videoFile = new FileDataSourceImpl(new File(Environment.getExternalStorageDirectory() + File.separator + "myvideo.mp4"));
Movie sor = MovieCreator.build(videoFile);
List<Track> videoTracks = sor.getTracks();
Track referenceTrack = null;
for (Track candidate : sor.getTracks()) {
if (candidate.getSyncSamples() != null && "vide".equals(candidate.getHandler()) && candidate.getSyncSamples().length > 0) {
referenceTrack = candidate;
OneJpegPerIframe oneJpegPerIframe = null;
try {
oneJpegPerIframe = new OneJpegPerIframe("eng", arr,referenceTrack);
} catch (IOException e) {
e.printStackTrace();
}
Movie movie = new Movie();
movie.addTrack(oneJpegPerIframe);
Container out = new DefaultMp4Builder().build(movie);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + File.separator + "output.mp4"));
out.writeContainer(fos.getChannel());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But I got error like "java.lang.RuntimeException: Number of sync samples doesn't match the number of stills (30 vs. 4)" which I have shown below :
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { (has extras) }} to activity {orafox.videomaker/orafox.videomaker.activity.MainActivity}: java.lang.RuntimeException: Number of sync samples doesn't match the number of stills (30 vs. 4)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
at android.app.ActivityThread.access$1100(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Number of sync samples doesn't match the number of stills (30 vs. 4)
at com.googlecode.mp4parser.authoring.tracks.mjpeg.OneJpegPerIframe.<init>(OneJpegPerIframe.java:39)
at activity.MainActivity.onActivityResult(MainActivity.java:135)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410) 
at android.app.ActivityThread.access$1100(ActivityThread.java:141) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
I do not want to use "ffmpeg" library.
If anybody knew how to solve it please help me. Thanks in advance.

java.lang.NumberFormatException: Invalid int: "" model texture

I would like to add texture to my model but I keep getting this error . Any help would be appreciated. Thanks
for (String i : faces) {
for (String j : i.split(" ")) {
iCoords[faceIndex] = (short) faceIndex++;
String[] faceComponent = j.split("/");
String vertex = vertexes.get(Integer.parseInt(faceComponent[0]) - 1);
// this line throws NFE
String texture = textures.get(Integer.parseInt(faceComponent[1]) - 1);
String vertexComp[] = vertex.split(" ");
String textureComp[] = texture.split(" ");
for (String v : vertexComp) {
vCoords[vertexIndex++] = Float.parseFloat(v);
}
for (String t : textureComp) {
tCoords[textureIndex++] = Float.parseFloat(t);
}
}
}
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.app.glapp/com.app.glapp.MainActivity}:
java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5603)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:137)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:331)
at com.mingatronenterprices.glapp.mesh.(mesh.java:72)
at com.mingatronenterprices.glapp.ClearRenderer.(MainActivity.java:70)
at com.app.glapp.ClearGLSurfaceView.(MainActivity.java:54)
at com.app.glapp.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5458)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5603)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Try to modify like this:
for (String v : vertexComp) {
try {
vCoords[vertexIndex++] = Float.parseFloat(v);
}
catch (NumberFormatException e) {
}
}
for (String t : textureComp) {
try {
tCoords[textureIndex++] = Float.parseFloat(t);
}
catch (NumberFormatException e) {
}
}

Android - App wont start up

My app wont start up with the following errors:
11-08 03:20:58.265: E/AndroidRuntime(306): FATAL EXCEPTION: main
11-08 03:20:58.265: E/AndroidRuntime(306): java.lang.NoClassDefFoundError: android.media.audiofx.Equalizer
11-08 03:20:58.265: E/AndroidRuntime(306): at com.example.audiotest.MainActivity.onCreate(MainActivity.java:86)
11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-08 03:20:58.265: E/AndroidRuntime(306): at android.os.Handler.dispatchMessage(Handler.java:99)
11-08 03:20:58.265: E/AndroidRuntime(306): at android.os.Looper.loop(Looper.java:123)
11-08 03:20:58.265: E/AndroidRuntime(306): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-08 03:20:58.265: E/AndroidRuntime(306): at java.lang.reflect.Method.invokeNative(Native Method)
11-08 03:20:58.265: E/AndroidRuntime(306): at java.lang.reflect.Method.invoke(Method.java:521)
11-08 03:20:58.265: E/AndroidRuntime(306): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-08 03:20:58.265: E/AndroidRuntime(306): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-08 03:20:58.265: E/AndroidRuntime(306): at dalvik.system.NativeStart.main(Native Method)
11-08 03:20:58.285: E/AudioThread(306): Thread Loop Exception: java.lang.IllegalArgumentException: Invalid audio buffer size.
My codes for OnCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Audio, mic to speaker
setVolumeControlStream(AudioManager.STREAM_MUSIC);
initControls();
mAudioThread = new AudioThread();
mAudioThread.start();
//end
//Equalizer
enabled = (CheckBox)findViewById(R.id.enabled);
enabled.setOnCheckedChangeListener (this);
flat = (Button)findViewById(R.id.flat);
flat.setOnClickListener(this);
bass_boost = (SeekBar)findViewById(R.id.bass_boost);
bass_boost.setOnSeekBarChangeListener(this);
bass_boost_label = (TextView) findViewById (R.id.bass_boost_label);
sliders[0] = (SeekBar)findViewById(R.id.slider_1);
slider_labels[0] = (TextView)findViewById(R.id.slider_label_1);
//more sliders till [4]
mEqualizer = new Equalizer(0, mAudioTrack.getAudioSessionId());
mEqualizer.setEnabled(true);
eq = new Equalizer (0, 0);
if (eq != null)
{
eq.setEnabled (true);
int num_bands = eq.getNumberOfBands();
num_sliders = num_bands;
short r[] = eq.getBandLevelRange();
min_level = r[0];
max_level = r[1];
for (int i = 0; i < num_sliders && i < MAX_SLIDERS; i++)
{
int[] freq_range = eq.getBandFreqRange((short)i);
sliders[i].setOnSeekBarChangeListener(this);
slider_labels[i].setText (formatBandLabel (freq_range));
}
}
for (int i = num_sliders ; i < MAX_SLIDERS; i++)
{
sliders[i].setVisibility(View.GONE);
slider_labels[i].setVisibility(View.GONE);
}
bb = new BassBoost (0, 0);
if (bb != null)
{
}
else
{
bass_boost.setVisibility(View.GONE);
bass_boost_label.setVisibility(View.GONE);
}
updateUI();
}
For my AudioThread:
public class AudioThread extends Thread {
// Handler message constants
public static final int PLAY = 0;
public static final int STOP = 1;
// Class variables
private boolean mRunning = false;
private boolean mPlayAudio = false;
private static class AudioThreadHandler extends Handler {
private final WeakReference<AudioThread> mThread;
public AudioThreadHandler(AudioThread thread) {
mThread = new WeakReference<AudioThread>(thread);
}
#Override
public void handleMessage(Message msg) {
AudioThread thread = mThread.get();
if (thread != null) {
switch(msg.what) {
case PLAY:
thread.mPlayAudio = true;
break;
case STOP:
thread.mPlayAudio = false;
break;
}
}
}
};
static final int bufferSize = 320000;
final short[] buffer = new short[bufferSize];
short[] readBuffer = new short[bufferSize];
private final AudioThreadHandler mAudioThreadHandler = new AudioThreadHandler(this);
#Override
public void run() {
try {
int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);
AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);
atrack.setPlaybackRate(11025);
byte[] buffer = new byte[buffersize];
arec.startRecording();
atrack.play();
mRunning = true;
while(mRunning) {
if (mPlayAudio) {
arec.read(buffer, 0, buffersize);
atrack.write(buffer, 0, buffer.length);
}else {
}
}
} catch (Exception e) {
Log.e("AudioThread", "Thread Loop Exception: " + e);
}
}
public void close() {
mRunning = false;
}
public Handler getHandler() {
return mAudioThreadHandler;
}
}
Sorry, everything may seem very messy. But this error have been stuck with me for a long time. Hope you guys could really help.
Take a look at my project if you would and provide me the the instructions for things I've done wrong.
double check and make sure you have import this class:
android.media.audiofx.Equalizer
try to cleanup your project ( Project
-> Clean... ), the rebuild your apk
edit:
your error line was here:
mEqualizer = new Equalizer(0, mAudioTrack.getAudioSessionId());
and i think you forgot to create instance of mAudioTrack, so you found null there..
mAudioTrack = new AudioTrack(streamType, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes, mode);
API level 10, New API
Hope this work for you
Problem might be here-
mEqualizer = new Equalizer(0, mAudioTrack.getAudioSessionId());
You need to extend mMediaPlayer.getAudioSessionId() instead of mAudioTrack.getAudioSessionId()
Please check the links- EqualizerSettings MediaPlayer
You have minSdkVersion="8" in manifest but Equalizer was added in API level 9.
This does not cause the crash directly but running the code in an API level 8 device will. Change the minimum SDK version to 9 and test on a device with API level 9 or higher. Or just remove the reference to Equalizer.

logcat have error about ArrayList

program not error but logcat error about index array list so picture I can't solve . please help me.
public class MainActivity extends MapActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mv = (MapView) findViewById(R.id.mapview);
mv.setBuiltInZoomControls(true);
MapController mc = mv.getController();
ArrayList all_geo_points = getDirections(16.821219, 100.260457, 13.913698, 100.510954);
GeoPoint moveTo = (GeoPoint) all_geo_points.get(0);
mc.animateTo(moveTo);
mc.setZoom(12);
mv.getOverlays().add(new MyOverlay(all_geo_points));
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public static ArrayList getDirections(double lat1, double lon1, double lat2, double lon2) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" +lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
String tag[] = { "lat", "lng" };
ArrayList list_of_geopoints = new ArrayList();
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
if (doc != null) {
NodeList nl1, nl2;
nl1 = doc.getElementsByTagName(tag[0]);
nl2 = doc.getElementsByTagName(tag[1]);
if (nl1.getLength() > 0) {
list_of_geopoints = new ArrayList();
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
Node node2 = nl2.item(i);
double lat = Double.parseDouble(node1.getTextContent());
double lng = Double.parseDouble(node2.getTextContent());
list_of_geopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
}
} else {
// No points found
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list_of_geopoints;
}
public class MyOverlay extends Overlay {
private ArrayList all_geo_points;
public MyOverlay(ArrayList allGeoPoints) {
super();
this.all_geo_points = allGeoPoints;
}
#Override
public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
super.draw(canvas, mv, shadow);
drawPath(mv, canvas);
return true;
}
public void drawPath(MapView mv, Canvas canvas) {
int xPrev = -1, yPrev = -1, xNow = -1, yNow = -1;
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(4);
paint.setAlpha(100);
if (all_geo_points != null)
for (int i = 0; i < all_geo_points.size() - 4; i++) {
GeoPoint gp = (GeoPoint) all_geo_points.get(i);
Point point = new Point();
mv.getProjection().toPixels(gp, point);
xNow = point.x;
yNow = point.y;
if (xPrev != -1) {
canvas.drawLine(xPrev, yPrev, xNow, yNow, paint);
}
xPrev = xNow;
yPrev = yNow;
}
}
}
}
This is code About google maps is line drive so input point latitude and longtitude two point for way line to driver and input is array . In code don't error but code have warning about array 8 wraning it all warning about array. run program have error logcat about array index.
01-18 00:37:29.720: E/AndroidRuntime(667): FATAL EXCEPTION: main
01-18 00:37:29.720: E/AndroidRuntime(667): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.getgoogledirection/com.example.getgoogledirection.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.os.Handler.dispatchMessage(Handler.java:99)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.os.Looper.loop(Looper.java:137)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-18 00:37:29.720: E/AndroidRuntime(667): at java.lang.reflect.Method.invokeNative(Native Method)
01-18 00:37:29.720: E/AndroidRuntime(667): at java.lang.reflect.Method.invoke(Method.java:511)
01-18 00:37:29.720: E/AndroidRuntime(667): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-18 00:37:29.720: E/AndroidRuntime(667): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-18 00:37:29.720: E/AndroidRuntime(667): at dalvik.system.NativeStart.main(Native Method)
01-18 00:37:29.720: E/AndroidRuntime(667): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
01-18 00:37:29.720: E/AndroidRuntime(667): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
01-18 00:37:29.720: E/AndroidRuntime(667): at java.util.ArrayList.get(ArrayList.java:304)
01-18 00:37:29.720: E/AndroidRuntime(667): at com.example.getgoogledirection.MainActivity.onCreate(MainActivity.java:45)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.Activity.performCreate(Activity.java:5008)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
It would be much easier to help you, if you put the output of logcat here.
As you mention, the error probably comes from the method getDirections.

Music Player - Function doesn't work when trying to use objects

I am making a music player application for my Computing project. I got it working but found that using objects would get more more marks. As a result, I changed some of my code to incorporate the use of objects, but it doesn't work when I execute my application. Btw I am quite new to Java so it's possible I made a silly mistake.
When I used this code the function I tried to implement worked:
private void SongTitleEndTime(){
try {
TextViewSongTitle = (TextView)findViewById(R.id.songTitle);
if (id != 0 ){
String where = MediaStore.Audio.Media._ID + " = " + "'" + id + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID.toString(), MediaStore.Audio.Media.ALBUM_ID.toString()}, where , null,
null);
mCursor.moveToFirst();
String title = mCursor.getString(0);
String artist = mCursor.getString(1);
String name = title + " - " + artist;
TextViewSongTitle.setText(name);
String fulltime;
albumfullid = Long.parseLong(mCursor.getString(3));
TextView EndTime = (TextView) findViewById(R.id.endtime);
long Minutes = TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration());
long Seconds = TimeUnit.MILLISECONDS.toSeconds(mMediaPlayer.getDuration()) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration()));
if (Seconds < 10) {
String second = "0" + String.valueOf(Seconds);
fulltime = Minutes + ":" + second;
} else {
//else display as normal
fulltime = Minutes + ":" + Seconds;
}
EndTime.setText(fulltime);
//display the duration of song
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} //catch for errors
}
But when I tried this, I got an error:
Main Class:
private void SongTitleEndTime() {
try {
final TextView TextViewSongTitle = (TextView) findViewById(R.id.songTitle);
if (CurrentSongID != 0) {
final Song CurrentSong = new Song(CurrentSongID);
SongName = CurrentSong.SongName;
TextViewSongTitle.setText(SongName);
AlbumID = CurrentSong.AlbumID;
final TextView EndTime = (TextView) findViewById(R.id.endtime);
final String TotalSongDuration = CurrentSong.TotalDuration;
EndTime.setText(TotalSongDuration);
}
} catch (final IllegalArgumentException e) {
e.printStackTrace();
} catch (final IllegalStateException e) {
e.printStackTrace();
}
}
Object Class:
package com.example.music.test;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.MediaColumns;
public class Song extends Activity {
private final String where;
public String SongName;
public long AlbumID;
public String TotalDuration;
public Song(final long SongID) {
where = MediaStore.Audio.Media._ID + " = " + "'" + SongID + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media._ID.toString(),
MediaStore.Audio.Media.ALBUM_ID.toString() }, where, null, null);
mCursor.moveToFirst();
final String SongTitle = getSongTitle(mCursor);
final String SongArtist = getSongArtist(mCursor);
SongName = SongTitle + " - " + SongArtist;
AlbumID = getAlbumID(mCursor);
TotalDuration = getTotalDuration();
}
public String getSongTitle(final Cursor mCursor) {
final String songtitle = mCursor.getString(0);
return songtitle;
}
public String getSongArtist(final Cursor mCursor) {
final String songartist = mCursor.getString(1);
return songartist;
}
public long getAlbumID(final Cursor mCursor) {
final long AlbumID = Long.parseLong(mCursor.getString(3));
return AlbumID;
}
public String getTotalDuration() {
String TotalTime;
final long Minutes = TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration());
final long Seconds = TimeUnit.MILLISECONDS
.toSeconds(Player.mMediaPlayer.getDuration())
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration()));
if (Seconds < 10) {
final String second = "0" + String.valueOf(Seconds);
TotalTime = Minutes + ":" + second;
} else {
TotalTime = Minutes + ":" + Seconds;
}
return TotalTime;
}
}
The error I get is:
01-02 21:55:41.941: E/AndroidRuntime(717): FATAL EXCEPTION: main
01-02 21:55:41.941: E/AndroidRuntime(717): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.music.test/com.example.music.test.Player}: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Looper.loop(Looper.java:137)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invoke(Method.java:511)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-02 21:55:41.941: E/AndroidRuntime(717): at dalvik.system.NativeStart.main(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): Caused by: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:91)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.managedQuery(Activity.java:1737)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Song.<init>(Song.java:21)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.SongTitleEndTime(Player.java:90)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.AllActivities(Player.java:80)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.onCreate(Player.java:66)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.performCreate(Activity.java:5008)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-02 21:55:41.941: E/AndroidRuntime(717): ... 11 more
Song is an Activity. Thus you can't call manageQuery before onCreate has been called. That's your error.

Categories

Resources