FileInputStream in Another class? - java

I'm loading a file that has been saved by another class via the FileOutputstream method. Anyway, I want to load that file in another class, but it either gives me syntax errors or crashes my App.
The only tutorials I could find where they saved and loaded the file in the same class, but I want to load it up in another class and couldn't find how to solve the problem of loading into another class.
Thanks
My Code:
public class LogIn extends Activity implements OnClickListener {
EditText eTuser;
EditText eTpassword;
CheckBox StaySignedIn;
Button bSubmit;
String user;
String pass;
FileOutputStream fos;
FileInputStream fis = null;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
eTuser = (EditText) findViewById(R.id.eTuser);
eTpassword = (EditText) findViewById(R.id.eTpassword);
StaySignedIn = (CheckBox) findViewById(R.id.Cbstay);
bSubmit = (Button) findViewById(R.id.bLogIn);
bSubmit.setOnClickListener(this);
File file = getBaseContext().getFileStreamPath(FILENAME);
if (file.exists()) {
Intent i = new Intent(LogIn.this, ChatService.class);
startActivity(i);
}
// if if file exist close bracket
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch bracket
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch
} // create ends here
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
String user = eTuser.getText().toString();
String pass = eTpassword.getText().toString();
Bundle userandpass = new Bundle();
userandpass.putString("user", user);
userandpass.putString("pass", pass);
Intent login = new Intent(LogIn.this, logincheck.class);
login.putExtra("pass", user);
login.putExtra("user", pass);
startActivity(login);
if (StaySignedIn.isChecked())
;
String userstaysignedin = eTuser.getText().toString();
String passstaysignedin = eTpassword.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(userstaysignedin.getBytes());
fos.write(passstaysignedin.getBytes());
fos.close();
} catch (IOException e) {
// end of try bracket, before the Catch IOExceptions e.
e.printStackTrace();
} // end of catch bracket
} // switch and case ends here
}// Click ends here
}// main class ends here
Class B( Class that loads the data.)
public class ChatService extends Activity {
String collected = null;
FileInputStream fis = null;
String FILENAME;
TextView userandpass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
userandpass = (TextView) findViewById(R.id.textView1);
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] dataArray = null;
try {
dataArray = new byte[fis.available()];
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (fis.read(dataArray) != -1)
;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
// while statement
}
userandpass.setText(collected);
}// create ends here
}// class ends here
LogCat:
03-03 21:03:34.725: E/AndroidRuntime(279): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-03 21:03:34.725: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.makeFilename(ContextImpl.java:1599)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.openFileInput(ContextImpl.java:399)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:152)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:25)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-03 21:03:34.725: E/AndroidRuntime(279): ... 11 more

The FILENAME string in the ChatService class is null. So you get a NullPointerException when you try to load a file using fis = openFileInput(FILENAME).
Also, your read loop throws away the data:
while (fis.read(dataArray) != -1)
;
It needs to collect the data and set the value of your collected String.

The stack trace tells you everything you need to know.
The error is a NullPointerException (meaning that you pass a null reference to a method expecting a non null reference, or that you call a method on a null reference).
The error occurs inside some android code (ContextWrapper.openFileInput()), which is called by your ChatService.onCreate() method, on line 25.
The line 25 is the following line:
fis = openFileInput(FILENAME);
So the error is clear: FILENAME is null. You haven't initialized it before this method is called.

I'm not sure about your program flow and if your two classes are running in the same thread, but it looks like you have a program flow issue. You are trying to open the file and getting a NullPointerException. Make sure the file is created and you have the correct reference to it before attempting to read.
If they are running in separate threads then you might try something like this:
try {
int waitTries=1;
fis = openFileInput(FILENAME);
while(fis.available()<EXPECTEDSIZE && waitTries++<10)
Tread.sleep(50);
}
If you know how large the file should be (EXPECTEDSIZE is some constant you will set), then this may be what you are looking for.

Related

App force closes when I try to implement an EditText search in a Listview

I am new to android. I have created an app which was a pull parser in order to extract items from an Rss feed, into a ListView. Unfortunately my app seems to force close when I try and place code in order implement some sort of filtering mechanism in my ListView. This is the code I have so far, and I have no idea why it seems to crash. Any help would be appreciated.
public class RssFeed extends ListActivity {
// Listview Adapter
ArrayAdapter<string> adapter;
EditText SearchBox;
List titles;
public static List description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss);
// Initialising instance variables
titles = new ArrayList();
description = new ArrayList();
try {
URL url = new URL("http://my.url");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
/** While the rss feed has not displayed end_document, pull the title and description information */
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
titles.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem)
description.add(xpp.nextText());
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
SearchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
RssFeed.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
And the LogCat:
04-12 20:43:00.792: D/dalvikvm(324): GC freed 7597 objects / 316440 bytes in 88ms
04-12 20:43:00.852: D/AndroidRuntime(324): Shutting down VM
04-12 20:43:00.852: W/dalvikvm(324): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-12 20:43:00.852: E/AndroidRuntime(324): Uncaught handler: thread main exiting due to uncaught exception
04-12 20:43:00.862: E/AndroidRuntime(324): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.me.myandroidstuff.simpleRssReader/org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed}: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Looper.loop(Looper.java:123)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invoke(Method.java:521)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-12 20:43:00.862: E/AndroidRuntime(324): at dalvik.system.NativeStart.main(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): Caused by: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed.onCreate(RssFeed.java:142)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-12 20:43:00.862: E/AndroidRuntime(324): ... 11 more
04-12 20:43:00.892: I/dalvikvm(324): threadid=7: reacting to signal 3
04-12 20:43:00.892: E/dalvikvm(324): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
First of all: the class you posted doesn't have 142 lines, be sure to post the whole class.
Second: SearchBox is null here.
That is because you declared it with
EditText SearchBox;
but never assigned it which you would usually do from your layout like
SearchBox = (EditText) findViewById(R.id.searchBox);
(just an example)
SeachBox does not have an assigned value at this point so you can't use any methods on it.
Third: Use lower case names like searchBox, it'll make your code easier to read for others and yourself.

GoogleMap Android API V2 Capture Error

I try #Tarsem answer already but have fatal error occur can I know why?
#Tarsem answer:
https://stackoverflow.com/a/18308611/2398886
<--- these are my error codes in eclipse: --->
08-21 18:52:23.399: W/dalvikvm(29376): threadid=1: thread exiting with uncaught exception (group=0x40018578)
08-21 18:52:23.409: E/AndroidRuntime(29376): FATAL EXCEPTION: main
08-21 18:52:23.409: E/AndroidRuntime(29376): java.lang.NoClassDefFoundError: com.example.testing01.MainActivity2$6
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2.CaptureMapScreen(MainActivity2.java:410)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2$3.onClick(MainActivity2.java:182)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View.performClick(View.java:2485)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View$PerformClick.run(View.java:9080)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.handleCallback(Handler.java:587)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Looper.loop(Looper.java:130)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invoke(Method.java:507)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:867)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-21 18:52:23.409: E/AndroidRuntime(29376): at dalvik.system.NativeStart.main(Native Method)
<--- these are my error codes in eclipse: --->
and these are my coding, is it my coding any bug?
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
map.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
my Stop Button function:
//End Button Function
Button timerStopButton = (Button) findViewById(R.id.btnTimerStop);
timerStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
String latitude3=Double.toString(latitude1);
String latitude4=Double.toString(latitude2);
String longitude3=Double.toString(longitude1);
String longitude4=Double.toString(longitude2);
String Kcalories=String.format("%.2f", calories);
Intent intent = new Intent(view.getContext(),NewDataActivity.class);
intent.putExtra("lat1", latitude3);
intent.putExtra("lat2", latitude4);
intent.putExtra("long1", longitude3);
intent.putExtra("long2", longitude4);
intent.putExtra("timer", timerStop1);
intent.putExtra("distance", distance2 + " m");
intent.putExtra("Ccalories", Kcalories + " kcal");
Toast.makeText(getApplicationContext(), "Calories (kcal):" + Kcalories, Toast.LENGTH_LONG).show();
startActivity(intent);
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//kill task timer and other
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
});
Is it my coding have any bug or my logic any probelm?
can anyone help me? thanks :)
Note Your code to Capture Map Screen is Correct and if still you have confusion than
Please Make sure Each Step Below:-
Below are the steps to capture screen shot of Google Map V2 with example
Step 1. open Android Sdk Manager (Window > Android Sdk Manager) then Expand Extras now update/install Google Play Services to Revision 10 ignore this step if already installed
Read Notes here https://developers.google.com/maps/documentation/android/releases#august_2013
Step 2. Restart Eclipse
Step 3. import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;
Step 4. Make Method to Capture/Store Screen/image of Map like below
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
myMap.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
Step 5. Now call this CaptureMapScreen() method where you want to capture the image
in my case i am calling this method on Button click in my onCreate() which is working fine
like:
Button btnCap = (Button) findViewById(R.id.btnTakeScreenshot);
btnCap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
Check Doc here and here

Why does this FileOutputStream give a NullPointerException?

so I am running an app that creates a NullPointerException when I try to write a file.
My first activity (see below) calls the NewSet activity when the user presses the new set button. When I try to write the input in the NewSet activity, it throws a NullPointerException. Printing out fileOut displays me with it having a value of null, which it shouldn't. fileOut is declared globally, but initialized in onCreate. The Two classes are below. (... represents omitted code due to being irrelevant.)
public class MainActivity extends Activity {
static ArrayList sets;
FileOutputStream fileOut;
BufferedReader read;
String line;
ArrayAdapter<String> adapter;
ListView listView;
Intent newSetIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
newSetIntent=new Intent(this,NewSet.class);
listView=(ListView)findViewById(R.id.setList);
sets=new ArrayList();
try {
read=new BufferedReader(new BufferedReader(new InputStreamReader(openFileInput("SETS.txt"))));
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
System.out.println("File not found");
try {
fileOut.write("".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOE");
// TODO Auto-generated catch block
e.printStackTrace();
}
getSets();
toList();
super.onCreate(savedInstanceState);
}
...
public void newSet(String newSetName){
System.out.println(newSetName);
sets.add(newSetName);
try {
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
fileOut.write(newSetName.getBytes());
fileOut.write("\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
catch (NullPointerException NPE){
System.out.println(fileOut);
NPE.printStackTrace();
}
}
}
public class NewSet extends Activity {
EditText input;
String setName;
MainActivity main;
...
public void submit(View view){
setName=input.getText().toString();
System.out.println("CREATING SET:"+setName);
main.newSet(setName);
finish();
}
}
The full stack trace
03-03 23:08:42.183: W/System.err(8435): java.lang.NullPointerException
03-03 23:08:42.183: W/System.err(8435): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:173)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.MainActivity.newSet(MainActivity.java:112)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.NewSet.submit(NewSet.java:35)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$1.onClick(View.java:3594)
03-03 23:08:42.193: W/System.err(8435): at android.view.View.performClick(View.java:4204)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$PerformClick.run(View.java:17355)
03-03 23:08:42.193: W/System.err(8435): at android.os.Handler.handleCallback(Handler.java:725)
03-03 23:08:42.203: W/System.err(8435): at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 23:08:42.203: W/System.err(8435): at android.os.Looper.loop(Looper.java:137)
03-03 23:08:42.203: W/System.err(8435): at android.app.ActivityThread.main(ActivityThread.java:5226)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-03 23:08:42.203: W/System.err(8435): at dalvik.system.NativeStart.main(Native Method)
Exception is getting thrown in android.content.ContextWrapper class. Method is:
public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException
{
return mBase.openFileOutput(name, mode); // Line number 173
}
Here, the only possibility I see which could result in NullPointerException is data member mBase of type Context is NULL.
Can you check if Context data member is non-null.

Android music player prepare method failed

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.

Somebody please explain the error

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());

Categories