I am using a thread and a handler in android. The app works fine as long as i dont any function from outside the activity. But if i call some funcyion from outside the activity from inside a thread, it gives NullPointerException.
package com.prog;
import com.API.TextBoxCheck;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ProgressBarExample extends Activity {
private Handler handler = new Handler();
int i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
TextView tv=(TextView)findViewById(R.id.textView1);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread thread = new Thread(null, doBackgroundThreadProcessing,
"Background");
thread.start();
}});
Button stopBtn=(Button)findViewById(R.id.button2);
stopBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}});
}
private Runnable doBackgroundThreadProcessing = new Runnable() {
public void run() {
try {
backgroundThreadProcessing();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private void backgroundThreadProcessing() throws InterruptedException {
TextView tv=(TextView)findViewById(R.id.textView1);
i=0;
while(i<100)
{
handler.post(doUpdateGUI);
Thread.sleep(50);
i++;
}
EditText et=(EditText)findViewById(R.id.editText1);
TextBoxCheck tbc = new com.API.TextBoxCheck();
String reply=tbc.TextBoxChecker(et.getText().toString(),10);
Log.d("thread", reply);
}
private Runnable doUpdateGUI = new Runnable() {
public void run() {
updateGUI();
}
private void updateGUI() {
// TODO Auto-generated method stub
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText(i+"%");
}
};
}
I have left out the code of textBoxCheck becoz i think it may be unnecesarry here.
Please help me on this.
PS. : I also tried using AsyncTask but the same problem occurs.
You are not on UI thread. You must be on UI thread to operate on any UI items. Create a handler on the UI thread and call your backgroundThreadProcessing(); from the handler and not from a non-UI thread.
Related
This is a part of an app that I am trying to make. I am trying to make a delay that can be set by the user so after each +1 it delays with 500 milliseconds, but soon I figured that i don't even know how to add a simple build in delay, I tried with delay(1000); it gave me Can not resolve method delay(int) then with sleep(1000); same error, then with TimeUnit.SECONDS.sleep(1); and Thread.sleep(1); nothing worked I am missing something fundamental, maybe I need to import something ? this is the whole program
if (v == swt1){
while (counter<2100000000) {
counter++;
}
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.BLACK);
}
Activity:
package counter.test.my.simplecount;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;
public class MainActivity extends Activity implements OnClickListener {
Button btn1;
Button btn2;
Button btn3;
Switch swt1;
TextView textTitle;
EditText scoreText;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.button);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
swt1 = (Switch)findViewById(R.id.switch1);
scoreText = (EditText)findViewById(R.id.editText);
textTitle = (TextView)findViewById(R.id.textView);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 34);
}
#Override
public void onClick(View v) {
if (v == btn1){
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.CYAN);
}
if (v == btn2){
counter--;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}
if (v == btn3){
counter = 0;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
if (v == swt1){
while (counter<2100000000) {
counter++;
}
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
}
}
}
You can use Handler() for delay like
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Your Aftre delay code
}
},500);
Remember to import this:
import android.os.Handler;
Use the "Handler" with "Runnable" to auto increment a value continuously at some time delay. Here i used "1sec" time dealy.
Find below code snippet for your requirement.
Runnable runnable;
Handler handler;
int delayTimeSec = 1000; //1 Sec
handler = new Handler();
runnable = new Runnable(){
#Override
public void run() {
// Your auto increment logic...
handler.postDelayed(runnable, delayTimeSec);
}
}
handler.postDelayed(runnable, delayTimeSec);
Use thread instead of handler if you have got background tasks.
new Thread(new Runnable() {
#Override
public void run() {
///background calculations
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//main thread task to update user interface
}
});
}
}).start();
I am working on an app that implements a Web Socket server. I am referring this library - https://github.com/TooTallNate/Java-WebSocket
The problem is that the thread holds up the entire UI. Here is the code -
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.nio.ByteBuffer;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.FrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText port, msg;
Button listener, send;
TextView status;
int p;
int count = 0;
boolean connect = false;
boolean listen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText)findViewById(R.id.editText2);
listener = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
SimpleServer server = new SimpleServer();
server.start();
status.setText("Working inside Thread");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class SimpleServer extends WebSocketServer {
public SimpleServer() throws UnknownHostException {
super(new InetSocketAddress(9998));
// TODO Auto-generated constructor stub
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
// TODO Auto-generated method stub
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Working");
}
}
}
You cannot update ui from other threads:
status.setText("Working inside Thread");
use runOnUiThread method of activity
runOnUiThread(new Runnable() {
#Override
public void run() {
status.setText("Working inside Thread");
}
});
By the way youre code cause memory leack and crashes. You cannot start long living operations in activity context. You should run service ,or make this thread in application context, results to ui you can pass by using EventBus.
Hello everyone, I am new to android application development. I have written and code and trying to update the UI from the message obtained from handler. I have tried to debug the code but i couldn't find what the error is. please help me out. Thank you.
package com.threadcommunicationexample;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button Click;
TextView Message;
Handler Mrmessenger;
int Counter = 0;
/*
*Initialisation area....
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Click = (Button) findViewById(R.id.ClickButton);
Message = (Button) findViewById(R.id.TextView);
Click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Operation to be performed after the button click
Runnable myThreadRunner = new Runnable() {
#Override
public void run() {
// Saving the text in bundle and passing it to handler ....
while (Counter < 100) {
try {
Thread.sleep(100);
Message msg = Mrmessenger.obtainMessage();
Bundle myBundle = new Bundle();
myBundle.putString("Communication", "Loading....");
msg.setData(myBundle);
//Sending the bundle to Handler
Mrmessenger.sendMessage(msg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Mrmessenger = new Handler() {
public void handleMessage(final Message msg) {
Mrmessenger.post(new Runnable() {
// Getting the message from the handler and updating it using textview
#Override
public void run() {
Bundle ComBundle = msg.getData();
// TODO Auto-generated method stub
String myMessage = ComBundle
.getString("Communication");
Message.setText(myMessage);
}
});
}
};
Counter++;
}
}
};
Thread myRunner = new Thread(myThreadRunner);
//creating a thread and passing the runnable object.
myRunner.start();
}
}
For one thing, the line
Message msg = Mrmessenger.obtainMessage();
will fail since you don't initialize Mrmessenger until a few lines later.
Would recommend you use AsyncTask for this type of thing; it deals with all of the threading so you don't have to.
Also: per Java conventions, variable names should start with a lowercase letter, class names start with an uppercase letter. This would make your code easier for others to read.
the problem with your code is, that the run method in your handler is called on another thread than the main / ui thread.
To make the code working you can use the following code..
runOnUiThread(new Runnable() {
public void run() {
Message.setText(myMessage);
}
});
..to run the ui update explicitly on the ui thread.
My app seems to start up properly, with the splash screen and stuff. But when it sleeps for 6 secs and when it supposed to get into the main activity the app crashes any help please?
Here is me code (android.intent.action1.MAINACTIVIVTY, the "action" was purposely changed to "action1")
package com.hellhogone.multitools;
import com.hellhogone.multitools.R;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Window;
import android.view.WindowManager;
public class Splash extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
MediaPlayer yo = MediaPlayer.create(Splash.this, R.raw.smusic);
yo.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(6000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent h1 = new Intent("android.intent.action1.MAINACTIVITY");
startActivity(h1);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
You cannot start an activity from another thread than the UI thread. To avoid this problem you can use runOnUiThread() :
}finally{
runOnUiThread(new Runnable() {
public void run() {
Intent h1 = new Intent("android.intent.action1.MAINACTIVITY");
startActivity(h1);
}
});
}
i have a little bit of a problem here when calling a new thread.
I am making a audio recording app and i call the recording/playback in separate threads.
There is a button to start the recording. I am trying to update the button with new text via a handler.post object and method.
The problem is it takes too long to update. The text doesnt update till after the thread(s) run +5 secs longer.
can someone help me? please?
package com.EJH.Industries.microkr;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.media.MediaSyncEvent;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
//CLASS VARIABLES
//CHAR SEQUENCE
CharSequence easyChar = "PLAYING";
public Handler textViewHandler = new Handler();
//CREATE THE RECORDING OBJECT
int audioSrc = MediaRecorder.AudioSource.MIC;
int sampleRate = 44100;
int chanConfig = AudioFormat.CHANNEL_IN_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int getMinBuffSize = 200*AudioRecord.getMinBufferSize(sampleRate, chanConfig, audioFormat);
int minBuffSize = (int) getMinBuffSize;
short audioBuff[] = new short[minBuffSize];
public AudioRecord micRecorder = new AudioRecord(audioSrc, 22050, chanConfig, audioFormat, minBuffSize);
//CREATE THE PLAYBACK OBJECT
int streamType = AudioManager.STREAM_MUSIC;
int playMode = AudioTrack.MODE_STREAM;
int playChanConfig = AudioFormat. CHANNEL_OUT_MONO;
public AudioTrack speakerPlay = new AudioTrack(streamType, sampleRate, playChanConfig, audioFormat, 8192, playMode);
public void startRec(){
micRecorder.startRecording();
micRecorder.read(audioBuff, 0, minBuffSize);
micRecorder.stop();
micRecorder.release();
}
public void startPlayback(){
speakerPlay.play();
speakerPlay.write(audioBuff, 0, minBuffSize);
speakerPlay.stop();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button startBtn = (Button) findViewById(R.id.startButton);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Thread recThread = new Thread( new Runnable(){
public void run() {
// TODO Auto-generated method stub
textViewHandler.post(new Runnable () {
public void run(){
startBtn.setText("Recording!");
}
});
startRec();
}
});
// RUN RECORDING FUNCTION
recThread.run();
try {
recThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread playThread = new Thread( new Runnable(){
public void run() {
// TODO Auto-generated method stub
startPlayback();
}
});
playThread.run();
try {
playThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
///////END onCreate//////////
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I think so it is because you are calling startRec() first and then running the recThread..try to modify your code as below..that is remove your startRec() function from above recThread.run() line and add it after try catch..hope it helped you..
Thread recThread = new Thread( new Runnable(){
public void run() {
// TODO Auto-generated method stub
textViewHandler.post(new Runnable () {
public void run(){
startBtn.setText("Recording!");
}
});
//remove it from here..
// startRec();
}
});
// RUN RECORDING FUNCTION
recThread.run();
try {
recThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//add here..
startRec();