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.
Related
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)
I have implemented a JSON Parser on a background thread and then am trying to write the data to a series of TableRows on the UI Thread using some embedded code which includes a handler to put me back on the normal UI Thread. The code continually comes back with this stack trace
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6123
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:244)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
04-21 14:58:08.506 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
04-21 14:58:11.316 6199-6215/webmd.mmu.ac.uk.wmfinal3 D/dalvikvm﹕ GC_FOR_ALLOC freed 209K, 10% free 3129K/3460K, paused 2ms, total 2ms
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/AndroidRuntime﹕ Shutting down VM
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0cb3b20)
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6199
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:245)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
I tried moving all the code into the AsyncTask but it then demands to be on the UI Thread.
Here is my code. Any help would be much appreciated.
protected Boolean doInBackground(final String... args) {
final TableLayout tl = (TableLayout) findViewById(R.id.table);
final TableRow v1 = new TableRow(MainActivity.this);
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
int [] test = new int [10];
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
//testing(vbn,va1,va2,va3,vpost,vratestar);
//TableLayout tl = (TableLayout) findViewById(R.id.table);
isRunning = true;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
// Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
tl.addView(v1);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
isRunning = false;
//jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
UPDATE: Now shows v1 initialization
Looking at your while (isRunning) loop I suppose you are trying to add the same v1 TableRow view to the TableLayout on each iteration (however, it is just a guess, because you didn't post v1 declaration). Of course, at the second time it will give you an error as it is already has parent, you should create new TableRow object each time. Going deeper, you don't need Handler which is connected to UI thread, because you are using AsyncTask, you can take advantage of the fact, that onPostExecute method is executed on the main thread. Considering it, you can write the following AsyncTask implementation:
class MyAsyncTask extends AsyncTask<Void, Void, JSONArray>{
#Override
protected JSONArray doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
return json;
}
#Override
protected void onPostExecute(JSONArray json) {
TableLayout tl = (TableLayout) findViewById(R.id.table);
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
TableRow tableRow = new TableRow(context);
//configuring row, setting layout params
tl.addView(tableRow);
} catch (JSONException ex){
//error handling
}
}
}
}
I am getting a NullPointerException when my code tries to access the value in a key/value pair created by onSaveInstanceState method of Activity class.
I set break points and I know for fact my Bundle is not null and it contains references to my key/values. I dont understand why I am getting this runtime error. Here are my codes for onSaveInstanceState
#Override
protected void onSaveInstanceState(Bundle outState) {
int mPoints = winCount;
int hPoints = loseCount;
String reTextView = resultsTextView.getText().toString();
String pTextView = pointsTextView.getText().toString();
String roTextView = rollTextView.getText().toString();
outState.putInt("MY_POINTS", mPoints);
outState.putInt("HOUSE_POINTS", hPoints);
outState.putString("RESULTS", reTextView);
outState.putString("POINTS", pTextView);
outState.putString("ROLL", roTextView);
super.onSaveInstanceState(outState);
}
and here is my code to restore the state on the onCreate method
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(String.valueOf(savedInstanceState.getString("RESULTS")));
pointsTextView.setText(String.valueOf(savedInstanceState.getString("POINTS")));
rollTextView.setText(String.valueOf(savedInstanceState.getString("ROLL")));
}
I get the runtime error on line that starts with resultsTextView.setText... and here is contents of the savedInstanceState Bundle retrieved from break points in debug mode
Bundle[{RESULTS=Roll Again, MY_POINTS=2, POINTS=Your Point is 8,
HOUSE_POINTS=2,
android:viewHierarchyState=Bundle[{android:Panels=android.util.SparseArray#421c5560,
android:views=android.util.SparseArray#421c5358,
android:ActionBar=android.util.SparseArray#421c57f8}], ROLL=You Rolled
Easy Four}]
as you can see all my strings have a value, the interesting thing is that I dont get the NullPointerException runtime error on int variables (winCount and loseCount) but I am getting it at string values. I appreciate any help.
Update: here is the whole error log from log cat, I have resultsTextView.setText... at line 68 (within the else block on onCreat())
W/dalvikvm(27797): threadid=1: thread exiting with uncaught exception (group=0x418b6700)
E/AndroidRuntime(27797): FATAL EXCEPTION: main
E/AndroidRuntime(27797): java.lang.RuntimeException: Unable to start activity ComponentInfo{…}: java.lang.NullPointerException
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3740)
E/AndroidRuntime(27797): at android.app.ActivityThread.access$700(ActivityThread.java:141)
E/AndroidRuntime(27797): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
E/AndroidRuntime(27797): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(27797): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(27797): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(27797): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27797): Caused by: java.lang.NullPointerException
E/AndroidRuntime(27797): at app.package.onCreate(AppName.java:68)
E/AndroidRuntime(27797): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime(27797): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
E/AndroidRuntime(27797): ... 12 more
here is my whole onCreate method, since many commentators requested to see the whole method. Hope it helps!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
dealButton.setOnClickListener(dealButtonListener);
resetButton.setOnClickListener(resetButtonLinstener);
//on shake event
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector(new OnShakeListener() {
#Override
public void onShake() {
game(rollDice());
}
});
resultsTextView.setTextColor(Color.BLACK);
myPointsTextView.setText(String.format("%s", winCount));
housePointsTextView.setText(String.format("%s", loseCount));
}
You should initialize your TextViews before calling setText method. So onCreate should be like this:
setContentView(R.layout.activity);
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
...
Hi I learned how to grab data from a SQL and display onto TextView. But I'm having little trouble displaying images.
The images are stored in the SQL database as URL but I can't display as an image onto the view.
I've done some research and found on "How to display image with given URL", but I'm just having a little difficulty understanding the concept of grabbing the URL and display .. Please kindly help me. Thank you!
This is the errorLog i'm getting.
Update
Line 159 : photoMe.setImageDrawable(drawable);
11-15 14:53:21.450: W/LoadImageFromWebOperations(28444): java.net.MalformedURLException: Protocol not found: photo
11-15 14:53:21.480: D/AndroidRuntime(28444): Shutting down VM
11-15 14:53:21.480: W/dalvikvm(28444): threadid=1: thread exiting with uncaught exception (group=0x40c55a68)
11-15 14:53:21.500: E/AndroidRuntime(28444): FATAL EXCEPTION: main
11-15 14:53:21.500: E/AndroidRuntime(28444): java.lang.NullPointerException
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.app.android.DirectoryDetailMeActivity$GetDirectoryDetails$1.run(DirectoryDetailMeActivity.java:159)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Handler.handleCallback(Handler.java:605)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Looper.loop(Looper.java:137)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.app.ActivityThread.main(ActivityThread.java:4517)
11-15 14:53:21.500: E/AndroidRuntime(28444): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 14:53:21.500: E/AndroidRuntime(28444): at java.lang.reflect.Method.invoke(Method.java:511)
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-15 14:53:21.500: E/AndroidRuntime(28444): at dalvik.system.NativeStart.main(Native Method)
public class DirectoryDetailMeActivity extends Activity {
ImageView photoMe;
TextView txtName;
String uid;
String photo = "";
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_veiw_directory = "directory_detail_me.php";
private static final String TAG_ID = "uid";
private static final String TAG_IMG = "photo";
private static final String TAG_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directory_detail_me);
uid = i.getStringExtra(TAG_ID);
new GetDirectoryDetails().execute();
}
class GetDirectoryDetails extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", uid));
JSONObject json = jsonParser.makeHttpRequest(url_veiw_directory, "GET", params);
Log.d("my profile", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray directoryObj = json.getJSONArray(TAG_DIRECTORY);
JSONObject directory = directoryObj.getJSONObject(0);
txtName.setText(directory.getString(TAG_NAME));
Drawable drawable = LoadImageURL(TAG_IMG);
photoMe.setImageDrawable(drawable);
txtName = (TextView) findViewById(R.id.name);
photoMe = (ImageView) findViewById(R.id.photo);
}else{
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private Drawable LoadImageURL(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "photo");
return d;
}
catch (Exception e)
{
Log.w("LoadImageURL",e.toString());
return null;
}
}
});
return null;
}
}
}
You don't seem to understand an AsyncTask. The point is that it does not run on the UI thread, making it possible to do long term IO like HTTP connections. Wrapping the entire doInBackground in a runOnUIThread is completely counter to that. Its not your only problem, but its on the list.
The rest is too hard to read due to formatting, but look on line 159. Some variable you're using there is null.
I saw most of the related questions, but I couldn't find any that fixed my problem.
This is my code, and I have no idea what I'm doing wrong.
static class NamedFile {
public File f;
public String name;
public String ext;
public String path;
public BitmapDrawable icon;
public NamedFile (File file) {
f = file;
name = f.getName();
if (f.isFile()) {
if (name.indexOf('.') != -1) {
ext = name.substring(name.lastIndexOf('.') + 1).trim().toLowerCase();
} else {
ext = "unknown";
}
}
path = f.getAbsolutePath();
if (ext == null) {
icon = mFolderIcon;
} else {
BitmapDrawable i = icons.get(ext);
if (i == null) {
try {
int rid = R.drawable.class.getField(ext).getInt(R.drawable.class);
icons.put(ext, new BitmapDrawable(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(res, rid, mOpts), iconSize, iconSize, false)));
icon = icons.get(ext);
} catch (Exception e1) {}
} else {
icon = i;
}
}/* else if (ext.equals("jpeg") || ext.equals("jpg") || ext.equals("bmp") || ext.equals("gif") || ext.equals("png")) {
Bitmap b = BitmapFactory.decodeFile(path, mOpts);
if (b != null) {
icon = new BitmapDrawable(Bitmap.createScaledBitmap(b, iconSize, iconSize, false));
}
}*/
if (ext != null && (ext.equals("jpeg") || ext.equals("jpg") || ext.equals("bmp") || ext.equals("gif") || ext.equals("png"))) {
/*
Bitmap b = BitmapFactory.decodeFile(path, mOpts);
if (b != null) {
icon = new BitmapDrawable(Bitmap.createScaledBitmap(b, iconSize, iconSize, false));
}
*/
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
HashMap<String, Object> m = ((HashMap<String, Object>)message.obj);
sendThumbnail ((String)m.get("path"), (byte[])m.get("data"));
}
};
Thread thread = new Thread() {
public void writeInt (byte[] buff, int pos, int value) {
buff[pos] = (byte)(value >>> 24);
buff[pos + 1] = (byte)(value >>> 16);
buff[pos + 2] = (byte)(value >>> 8);
buff[pos + 3] = (byte)value;
}
#Override
public void run() {
try {
Bitmap b = BitmapFactory.decodeFile(path, mOpts);
if (b.getHeight() > 256 || b.getWidth() > 256) {
float r;
if (b.getHeight() > b.getWidth()) {
r = 128f / b.getHeight();
} else {
r = 128f / b.getWidth();
}
b = Bitmap.createScaledBitmap(b, (int)(r * b.getWidth()), (int)(r * b.getHeight()), false);
byte[] buffer = new byte[b.getWidth() * b.getHeight() * 4 + 8];
writeInt (buffer, 0, b.getWidth());
writeInt (buffer, 4, b.getHeight());
int i = 8;
for (int y = 0; y < b.getHeight(); y ++) {
for (int x = 0; x < b.getWidth(); x ++) {
writeInt (buffer, i, b.getPixel(x, y));
i += 4;
}
}
HashMap<String, Object> msg = new HashMap<String, Object>();
msg.put("path", path);
msg.put("data", buffer);
Message message = handler.obtainMessage(1, msg);
handler.sendMessage(message);
}
} catch (Exception e) {
sendLog (e.toString());
}
}
};
thread.start();
}
if (icon == null) {
icon = mFileIcon;
}
}
public NamedFile () {
}
public NamedFile simpleClone () {
final NamedFile nf = new NamedFile();
nf.name = name;
nf.ext = ext;
nf.path = path;
return nf;
}
}
This is nested inside an if statement that is in a static class' constructor function and the static class is in a public class that extends ListActivity. I'm new to Java.
Error:
05-01 20:21:58.810: E/AndroidRuntime(584): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
05-01 20:21:58.830: E/AndroidRuntime(584): java.lang.RuntimeException: An error occured while executing doInBackground()
05-01 20:21:58.830: E/AndroidRuntime(584): at android.os.AsyncTask$3.done(AsyncTask.java:200)
05-01 20:21:58.830: E/AndroidRuntime(584): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-01 20:21:58.830: E/AndroidRuntime(584): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-01 20:21:58.830: E/AndroidRuntime(584): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-01 20:21:58.830: E/AndroidRuntime(584): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-01 20:21:58.830: E/AndroidRuntime(584): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
05-01 20:21:58.830: E/AndroidRuntime(584): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
05-01 20:21:58.830: E/AndroidRuntime(584): at java.lang.Thread.run(Thread.java:1096)
05-01 20:21:58.830: E/AndroidRuntime(584): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-01 20:21:58.830: E/AndroidRuntime(584): at android.os.Handler.<init>(Handler.java:121)
05-01 20:21:58.830: E/AndroidRuntime(584): at greg.projects.FileTransfer.FileTransferActivity$NamedFile$1.<init>(FileTransferActivity.java:588)
05-01 20:21:58.830: E/AndroidRuntime(584): at greg.projects.FileTransfer.FileTransferActivity$NamedFile.<init>(FileTransferActivity.java:588)
05-01 20:21:58.830: E/AndroidRuntime(584): at greg.projects.FileTransfer.FileTransferActivity$GesturesLoadTask.doInBackground(FileTransferActivity.java:489)
05-01 20:21:58.830: E/AndroidRuntime(584): at greg.projects.FileTransfer.FileTransferActivity$GesturesLoadTask.doInBackground(FileTransferActivity.java:1)
05-01 20:21:58.830: E/AndroidRuntime(584): at android.os.AsyncTask$2.call(AsyncTask.java:185)
05-01 20:21:58.830: E/AndroidRuntime(584): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-01 20:21:58.830: E/AndroidRuntime(584): ... 4 more
(FileTransferActivity.java:588 is final Handler handler = new Handler() {)
A Handler is basically a callback class that Android uses to asynchronously run code when you send it messages of some form. In order for a Handler to receive and handle messages in a separate thread from the UI thread, it must keep the thread open. That is where the Looper class comes in. Like in the example of the page, call Looper.prepare() at the top of the run() method, then call Looper.loop() at the bottom. The thread will stay open until you explicitly destroy it. In order to destroy a Looper thread, you must have a method in your Thread class that calls Looper.getMyLooper().quit().
An example thread class would be something like this:
class LooperThread extends Thread {
public Handler mHandler;
private volatile Looper mMyLooper;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
mMyLooper = Looper.getMyLooper();
Looper.loop();
}
public void killMe(){
mMyLooper.quit();
}
}
Run the thread normally by creating a new object of it.
LooperThread myLooperThread = new LooperThread();
Hold a reference to it. Then call:
myLooperThread.killMe();
Whenever you want the thread to die. This is usually in the onPause(), onStop(), or onDestroy() methods of the Activity.
Please note that a thread of this nature will stay open when the activity is closed so you must kill it before the user quits.
Runs the specified action on the UI thread
ActivityName.runOnUiThread(new Runnable() {
public void run()
{
//put your logic here
}
});
I recommend using HandlerThread as it prepares the looper for you.
http://developer.android.com/reference/android/os/HandlerThread.html