I try to use jaudiotagger like this
but it crashes
Main app.java :
import java.io.File;
import java.io.IOException;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldDataInvalidException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.KeyNotFoundException;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class App extends Activity {
/** Called when the activity is first created. */
private TextView txt1;
private TextView txt2;
private TextView txt3;
private TextView txt4;
private TextView txt5;
private TextView txt6;
private TextView txt7;
private TextView txt8;
private TextView txt9;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// try
//{
File mp3 = new File("/sdcard/test.mp3");
AudioFile f = null;
try {
f = AudioFileIO.read(mp3);
} catch (CannotReadException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (TagException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (ReadOnlyFileException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (InvalidAudioFrameException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
}
Tag tag = f.getTag();
AudioHeader AudioHeader = f.getAudioHeader();
txt1.setText(tag.getFirst(FieldKey.ARTIST));
txt2.setText(tag.getFirst(FieldKey.ALBUM));
txt3.setText(tag.getFirst(FieldKey.TITLE));
txt4.setText(tag.getFirst(FieldKey.COMMENT));
txt5.setText(tag.getFirst(FieldKey.YEAR));
txt6.setText(tag.getFirst(FieldKey.TRACK));
txt7.setText(tag.getFirst(FieldKey.DISC_NO));
txt8.setText(tag.getFirst(FieldKey.COMPOSER));
txt9.setText(tag.getFirst(FieldKey.ARTIST_SORT));
try {
tag.setField(FieldKey.ARTIST,"Kings of Leon");
} catch (KeyNotFoundException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (FieldDataInvalidException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
}
try {
AudioFileIO.write(f);
} catch (CannotWriteException e) {
txt1.setText(e.toString());
}
/* }
catch(Exception x)
{
txt1.setText(x.toString());
}
*/
}
}
Logcat :
02-22 21:12:22.546: E/AndroidRuntime(19738): FATAL EXCEPTION: main
02-22 21:12:22.546: E/AndroidRuntime(19738):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.mp3.tag.editor.alexander.fuchs/com.mp3.tag.editor.alexander.fuchs.App}:
java.lang.NullPointerException 02-22 21:12:22.546:
E/AndroidRuntime(19738): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
android.app.ActivityThread.access$1500(ActivityThread.java:117) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
android.os.Handler.dispatchMessage(Handler.java:99) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
android.os.Looper.loop(Looper.java:130) 02-22 21:12:22.546:
E/AndroidRuntime(19738): at
android.app.ActivityThread.main(ActivityThread.java:3691) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
java.lang.reflect.Method.invokeNative(Native Method) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
java.lang.reflect.Method.invoke(Method.java:507) 02-22 21:12:22.546:
E/AndroidRuntime(19738): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
dalvik.system.NativeStart.main(Native Method) 02-22 21:12:22.546:
E/AndroidRuntime(19738): Caused by: java.lang.NullPointerException
02-22 21:12:22.546: E/AndroidRuntime(19738): at
com.mp3.tag.editor.alexander.fuchs.App.onCreate(App.java:72) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
02-22 21:12:22.546: E/AndroidRuntime(19738): ... 11 more
There two blockers
to using jaudiotagger on Android:
1 - javax.swing
2 - javax.imageio
these two Classes isn't supported by android and jaudiotagger uses them
To solve your problem:
Fix the sources so they don't depend no more on these two JAVAX Classes
Seems like this line causes the crash, because f is null:
Tag tag = f.getTag();
You shouldn't ignore the exception in the way you do, as if you got an exception, you just print something and continue with a bad state (in this case - f is still null)
You still need to check that f != null before you get the tag.
Tag r_tag = null;
File testFile = new File(filename);
MP3File f = null;
try {
f = (MP3File)AudioFileIO.read(testFile);
} catch (CannotReadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TagException e) {
e.printStackTrace();
} catch (ReadOnlyFileException e) {
e.printStackTrace();
} catch (InvalidAudioFrameException e) {
e.printStackTrace();
}
if(f != null) {
f.getTagOrCreateAndSetDefault();
r_tag = f.getID3v2TagAsv24();
}
return r_tag;
Related
I have been trying to play an MP3 file. It just won't work.
I did manage to play it and add all sorts of functionalities to it with the very same/similar code a few days ago. Just tried to make it all over again and now these errors...
Can someone point out the error also why does this happen.
Just to clarify I used different formats of URI, none of them work. Thought maybe its the prepare method.
package com.player.phoneagent.gui;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class AndroidClientActivity extends Activity {
/** Called when the activity is first created. */
private MediaPlayer mp;
String path = "android.resource://com.player.phoneagent/raw/test";
ImageButton btn_prev;
ImageButton btn_play;
ImageButton btn_pause;
ImageButton btn_next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_prev = (ImageButton) findViewById(R.id.ImageButton01);
btn_pause = (ImageButton) findViewById(R.id.ImageButton02);
btn_play = (ImageButton) findViewById(R.id.ImageButton03);
btn_next = (ImageButton) findViewById(R.id.ImageButton04);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mp.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
});
}
}
08-01 07:06:00.142: W/KeyCharacterMap(407): No keyboard for id 0
08-01 07:06:00.142: W/KeyCharacterMap(407): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
08-01 07:06:05.821: D/dalvikvm(407): GC_EXPLICIT freed 21K, 53% free 2568K/5379K, external 3207K/3962K, paused 55ms
08-01 07:06:20.311: D/dalvikvm(444): GC_EXTERNAL_ALLOC freed 52K, 53% free 2552K/5379K, external 1969K/2137K, paused 58ms
08-01 07:06:43.171: E/MediaPlayer(444): error (1, -2147483648)
08-01 07:06:43.171: W/System.err(444): java.io.IOException: Prepare failed.: status=0x1
08-01 07:06:43.171: W/System.err(444): at android.media.MediaPlayer.prepare(Native Method)
08-01 07:06:43.171: W/System.err(444): at com.player.phoneagent.gui.AndroidClientActivity$1.onClick(AndroidClientActivity.java:60)
08-01 07:06:43.171: W/System.err(444): at android.view.View.performClick(View.java:2485)
08-01 07:06:43.171: W/System.err(444): at android.view.View$PerformClick.run(View.java:9080)
08-01 07:06:43.181: W/System.err(444): at android.os.Handler.handleCallback(Handler.java:587)
08-01 07:06:43.181: W/System.err(444): at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 07:06:43.181: W/System.err(444): at android.os.Looper.loop(Looper.java:123)
08-01 07:06:43.181: W/System.err(444): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 07:06:43.181: W/System.err(444): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:06:43.181: W/System.err(444): at java.lang.reflect.Method.invoke(Method.java:507)
08-01 07:06:43.181: W/System.err(444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 07:06:43.181: W/System.err(444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 07:06:43.181: W/System.err(444): at dalvik.system.NativeStart.main(Native Method)
08-01 07:06:43.181: E/MediaPlayer(444): start called in state 0
08-01 07:06:43.181: E/MediaPlayer(444): error (-38, 0)
08-01 07:06:43.181: E/MediaPlayer(444): Error (-38,0)
I always had problems trying to use "raw" folder... I suggest putting the sound file in "assets" and using the methods here to set / prepare / and play:
http://droidapp.co.uk/2011/06/08/android-dev-playing-a-mp3-from-assets/
Just do something like:
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mp = MediaPlayer.create(this, R.raw.yourSongFileName);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
mp.release();
mp = null;
mp = MediaPlayer.create(this, R.raw.yourSongFileName);
mp.start();
//Other stuff below.
See if that works.
I'm new to android - I'm trying to populate textviews using data from external database but I'm receiving this error (LogCat below) I have had a long hard gander on the net but cant seem to find much to help me out.
LogCat
04-11 23:10:56.084: E/AndroidRuntime(333): FATAL EXCEPTION: main
04-11 23:10:56.084: E/AndroidRuntime(333): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thickcrustdesigns.ufood/com.thickcrustdesigns.ufood.recipePage}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.os.Handler.dispatchMessage(Handler.java:99)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.os.Looper.loop(Looper.java:123)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.lang.reflect.Method.invokeNative(Native Method)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.lang.reflect.Method.invoke(Method.java:507)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-11 23:10:56.084: E/AndroidRuntime(333): at dalvik.system.NativeStart.main(Native Method)
04-11 23:10:56.084: E/AndroidRuntime(333): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-11 23:10:56.084: E/AndroidRuntime(333): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.util.ArrayList.get(ArrayList.java:311)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.thickcrustdesigns.ufood.recipePage.onCreate(recipePage.java:44)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
04-11 23:10:56.084: E/AndroidRuntime(333): ... 11 more
recipePage
package com.thickcrustdesigns.ufood;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class recipePage extends Activity {
TextView txt_Recipe;
TextView txt_Ingredients;
TextView txt_Method;
Button btn_bk;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipepage);
Bundle data = getIntent().getExtras();
String recipe = data.getString("recipie");
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("request", "recipe"));
nvp.add(new BasicNameValuePair("recipe", recipe));
ArrayList<NameValuePair> nvp2 = new ArrayList<NameValuePair>();
nvp2.add(new BasicNameValuePair("request", "ingredients"));
nvp2.add(new BasicNameValuePair("recipe", recipe));
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
String title = null;
try {
title = jsondefs.get(0).getString("Name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String method = null;
try {
method = jsondefs.get(0).getString("Method");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<JSONObject> jsonIngredients = Request.fetchData(this, nvp2);
String ingredients = "";
for (int i = 0; i < jsonIngredients.size(); i++){
String ji = null;
try {
ji = jsonIngredients.get(i).getString("Name") + "\n";
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ingredients += ji;
}
txt_Recipe.setText(title);
txt_Method.setText(method);
txt_Ingredients.setText(ingredients);
// Listening to button event
btn_bk.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
UFoodAppActivity.class);
startActivity(i);
}
});
}
}
request.java
package com.thickcrustdesigns.ufood;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
//import android.widget.TextView;
public class CatogPage extends ListActivity {
ListView listView1;
Button btn_bk;
String[] defs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.definition_main);
btn_bk = (Button) findViewById(R.id.btn_bk);
listView1 = (ListView) findViewById(android.R.id.list);
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("request", "categories"));
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
defs = new String[jsondefs.size()];
for (int i = 0; i < jsondefs.size(); i++) {
try {
defs[i] = jsondefs.get(i).getString("Name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list,
defs);
listView1.setAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = defs[position];
Intent i = new Intent(getApplicationContext(), Results.class);
i.putExtra("category", item);
startActivity(i);
}
});
btn_bk.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), CatogPage.class);
startActivity(i);
}
});
}
}
Many Thanks
Start looking on line 44 of recipePage.java
com.thickcrustdesigns.ufood.recipePage.onCreate(recipePage.java:44)
04-11 23:10:56.084: E/AndroidRuntime(333): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-11 23:10:56.084: E/AndroidRuntime(333): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
MORE DETAILS:
Following line is not filling jsondefs
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
Looks like this call is unsafe:
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
String title = null;
try {
title = jsondefs.get(0).getString("Name"); //<--- Here jsondefs could be empty
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if jsondefs is empty, you could see the error you are mentionning.
Most likely thrown by one of the jsondefs.get(0)… You should add an if(!jsondefs.isEmpty()) and an else that prints something so that you know what the problem is.
I'm trying to create an ePub file in android. Below is my source code.
But I'm getting NullPointerException at
epubWriter.write(book, out);
I've put the cover.png and test1.html in assets folder.
What about *.css,mimetype,META-INF/container.xml,OEBPS/*.opf,*.otf files?
Are they compulsory to build an ePub file?
I'm able to create a file but that is not in proper format I guess as when I pull that file from device and try to view it in Calibre, it doesn't open by giving following error
calibre, version 0.8.38
ERROR: Could not open ebook: File is not a zip file
I'm absolute beginner to ePub development so any help/suggestion would be appreciated.
CreateEPub.java
public class CreateEPub extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AssetManager assetManager = getAssets();
try {
Book book = new Book();
book.getMetadata().addTitle("Epub test book 1");
book.getMetadata().addAuthor(new Author("Joe", "Tester"));
InputStream is = assetManager.open("cover.png");
book.getMetadata().setCoverImage(new Resource(is, "cover.png"));
// Add Chapter 1
InputStream is1 = assetManager.open("test1.html");
book.addSection("Introduction", new Resource(is1, "chapter1.html"));
EpubWriter epubWriter = new EpubWriter();
epubWriter.write(book, new FileOutputStream("test1_book1.epub"));
Log.v("ePub", "Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
LogCat
java.lang.NullPointerException
at org.kxml2.io.KXmlSerializer.attribute(KXmlSerializer.java:473)
at nl.siegmann.epublib.epub.PackageDocumentMetadataWriter.writeMetaData(PackageDocumentMetadataWriter.java:93)
at nl.siegmann.epublib.epub.PackageDocumentWriter.write(PackageDocumentWriter.java:45)
at nl.siegmann.epublib.epub.EpubWriter.writePackageDocument(EpubWriter.java:112)
at nl.siegmann.epublib.epub.EpubWriter.write(EpubWriter.java:53)
at com.createepub.CreateEPub.onCreate(CreateEPub.java:91)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
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:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Note that CreateEPub Line 91 refers to epubWriter.write(book, out);
I hope you are using siegmann lib for creating ePub.
Need to include 2 lib files(mandatory)
epublib-core-latest.jar
slf4j-android-1.6.1-RC1.jar
Download both jar from http://www.siegmann.nl/epublib/android
Sample Code
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import nl.siegmann.epublib.domain.Author;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.epub.EpubWriter;
import android.app.Activity;
import android.os.Bundle;
public class EpubAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Book b = new Book();
b.getMetadata().addTitle("test epub book");
b.getMetadata().addAuthor(new Author("author name"));
EpubWriter w = new EpubWriter();
FileOutputStream fos;
try {
File file = new File(getApplicationContext().getExternalFilesDir(null), "test.epub");
if(!file.exists()){
file.createNewFile();
}
fos = new FileOutputStream(file);
w.write(b, fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am new to android programming.I have been trying to establish connection between two emulators.While my server emulator is up and running,client has a problem.Here is the code and logcat error description.Please tell me the error in this.
public class SocketClient extends Activity
{
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "192.168.0.5";
private static final int REDIRECTED_SERVERPORT = 5000;
public void connect()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
tv.setText((CharSequence) serverAddr);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
System.out.println("Here");
}
catch (IOException e1)
{
e1.printStackTrace();
System.out.println("Here too");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
connect();
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception e)
{
tv.setText("Error3");
e.printStackTrace();
}
}
}
);
}
}
The logcat error is
01-31 04:42:51.170: W/dalvikvm(529): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-31 04:42:51.187: E/AndroidRuntime(529): FATAL EXCEPTION: main
01-31 04:42:51.187: E/AndroidRuntime(529): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.ServerClient/com.app.ServerClient.SocketClient}: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Looper.loop(Looper.java:137)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invokeNative(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invoke(Method.java:511)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-31 04:42:51.187: E/AndroidRuntime(529): at dalvik.system.NativeStart.main(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): Caused by: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.connect(SocketClient.java:25)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.onCreate(SocketClient.java:48)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Activity.performCreate(Activity.java:4465)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-31 04:42:51.187: E/AndroidRuntime(529): ... 11 more
Thanks in advance.
Thank You David and Jitendra.
I corrected the error and I get a nullPointerException in one part of the code.What did I do wrong?
public void onClick(View v)
{
try // The error is in this block
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception f) // I get the error here. java.lang.NullPointerException
{
tv.setText("Error3");
tv.setText(f.toString());
f.printStackTrace();
}
}
Your error is on this line:
tv.setText((CharSequence) serverAddr);
serverAddr is of type InetAddress, and you're trying to cast it to a CharSequence which cannot be done. Perhaps you meant:
tv.setText(serverIpAddress);
Exception is in following line:
tv.setText((CharSequence) serverAddr);
and it is because you are trying to cast serverAddr into CharSequence.
If you really want to print serverAddr use
tv.setText((CharSequence) serverAddr.toString());
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.