I am facing a problem, I have implemented a code, it is showing me message in Logs correctly but it doesn't update the TextView's text. Here i have tried this version. How i can update it? I tried it using threads as well but in vain.
I have seen many solution over this StackOverflow platform but i could not find my any solution for my problem.
package com.example.yousafmoh.seizuredetection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class ledControl extends AppCompatActivity {
// Button btnOn, btnOff, btnDis;
ImageButton On, Off, Discnt, Abt;
TextView txtMessage;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgets
On = (ImageButton)findViewById(R.id.on);
Off = (ImageButton)findViewById(R.id.off);
Discnt = (ImageButton)findViewById(R.id.discnt);
Abt = (ImageButton)findViewById(R.id.abt);
txtMessage = (TextView) findViewById(R.id.txtMessage);
new ConnectBT().execute(); //Call the class to connect
//myBluetoothThread();
//commands to be sent to bluetooth
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
Discnt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void myBluetoothThread() {
while(true)
{
if (btSocket!=null)
{
try
{
if(isBtConnected) {
InputStream inputStream = btSocket.getInputStream();
for (int i = 0; i <= inputStream.available(); i++) {
//Log.d("data", inputStream.read() + " "+"ok");
int val = inputStream.read();
if (val == 49) // seizure detected
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Log.d("Message", " Detected");
}
});
Log.d("Message", " Detected");
} else if (val == 48) // no detection
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
Log.d("Message", "not Detected");
}
});
Log.d("Message", "not Detected");
//, Toast.LENGTH_SHORT).show();
}
}
}
}
catch (IOException e)
{
msg("Error");
}
}
}
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
for(int i = 0 ; i <= inputStream.available();i++)
{
Log.d("data",inputStream.read()+" ");
}
Log.d("Bytes available off",String.valueOf(inputStream.available()));
Log.d("Message off",String.valueOf(inputStream.read()));
//btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
Log.d("Bytes available on",String.valueOf(inputStream.available()));
Log.d("Message on",String.valueOf(inputStream.read()));
Log.d("Message on",inputStream.toString());
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
public void about(View v)
{
if(v.getId() == R.id.abt)
{
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_led_control, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
progress.dismiss();
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
if(progress!=null)
progress.dismiss();
if(isBtConnected)
{
myBluetoothThread();
}
}
}
}
Try using this if its a fragment class
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
and this is its an activity
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
Another solution u can try is.
You can use handler
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
});
I have read some article somewhere that you should not update your textview directly inside the Runnable Thread. So what I did is i created a function that updates the textview then the Runnable run method calls that function. So It look like this.
public class SampleActivity extends AppCompatActivity {
TextView sample;
int counter = 0;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
sample = findViewById(R.id.sample);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
counter++;
updateTextView("Counter: " + counter);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
public void updateTextView(String message) {
sample.setText(message);
}
But I tried it calling the sample.setText("Counter: "+counter) inside the Runnable Thread, it still works though.
Btw here is my sample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="SAWSAW"
android:textColor="#000"
android:textSize="32dp" />
</LinearLayout>
Related
I am very new to android. Following is my code and I am getting these errors.
Cannot resolve symbol params.
Variable "blinkDelay" never assigned.
When i hover the mouse over "Parameters". it says "android.hardware.Camera.Parameters Alt+Enter".
In the following code:
blinkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = "0101010101";
long blinkDelay 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Here is my full MainActivity.java
package com.fusion.flashlight;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private ImageButton firstButton;
private Button blinkButton;
private Boolean isTorchOn;
private MediaPlayer media;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("MainActivity", "onCreate()");
setContentView(R.layout.activity_main);
mTorchOnOffButton = (ImageButton) findViewById(R.id.btnSwitch);
firstButton = (ImageButton) findViewById(R.id.btn1Switch);
blinkButton = (Button) findViewById(R.id.blinking);
isTorchOn = false;
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
blinkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = "0101010101";
long blinkDelay 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.btn_on);
firstButton.setImageResource(R.drawable.btn11_on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.btn_off);
firstButton.setImageResource(R.drawable.btn11_off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void playOnOffSound(){
media = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
media.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//TODO Auto-generated method stub
mp.release();
}
});
media.start();
}
#Override
protected void onStop() {
super.onStop();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onPause() {
super.onPause();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onResume() {
super.onResume();
if(isTorchOn){
turnOnFlashLight();
}
}
}
For blinkDelay, you are missing an equal symbol when assigning,
For params, I cant see where do you create that variable.
And the other, alt+Enter is for autoImporting the Parameters class by Android Studio.
Cannot resolve symbol params. params not define
Variable "blinkDelay" never assigned. blinkDelay having no initial value
long blinkDelay =50;
When i hover the mouse over "Parameters". it says
"android.hardware.Camera.Parameters Alt+Enter". Alt+Enter for import
I am using the audiodispatcher from the TarsosDSPlibrary.
The pitchdetection is used to detect sounds from the mic. Once detected, it switches to the next activity (which is a Maths quiz). After completing the quiz on the next activity, it returns to this activity and starts the process all over again.
What is bugging me is that my APP is working 90% of the time when using the pitchdetection function. However, sometimes it doesn't work and throws an error as follows:
E/AudioRecord: start() status -38
and the app no longers switches to the next activity.
package com.humanfactorsandappliedcognitionlab.research.mathsapp;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.RunnableFuture;
import be.tarsos.dsp.AudioDispatcher;
import be.tarsos.dsp.AudioEvent;
import be.tarsos.dsp.io.android.AudioDispatcherFactory;
import be.tarsos.dsp.pitch.PitchDetectionHandler;
import be.tarsos.dsp.pitch.PitchDetectionResult;
import be.tarsos.dsp.pitch.PitchProcessor;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
MediaPlayer notifySound;
MediaPlayer endSound;
AudioDispatcher dispatcherMAIN;
PitchProcessor pitchProcessorMAIN;
public boolean isListening = false;
TextToSpeech tts;
private int sensitivity = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notifySound = MediaPlayer.create(this, R.raw.samsung);
endSound = MediaPlayer.create(this, R.raw.ding);
OPTION = dbHandler.getOPTION();
tts = new TextToSpeech(this, this);
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
}
});
}
#Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
startListenToTalk();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
}
private void speakOut() {
Log.e("TTS", "SPEAKING...");
String text = "Please Say Continue to Proceed ";
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
tts.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
private void startListenToTalk() {
dispatcherMAIN = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0);
pitchProcessorMAIN = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult pitchDetectionResult,
AudioEvent audioEvent) {
final float pitchInHz = pitchDetectionResult.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageButton buttonOK = (ImageButton) findViewById(R.id.buttonOK);
TextView textINPUT = (TextView)findViewById(R.id.textINPUT);
if (pitchInHz > sensitivity) {
Log.e("pitch : ", pitchInHz + "");
if (isListening) {
try {
dispatcherMAIN.stop();
Intent gotoMaths = new Intent(MainActivity.this, MathsActivity.class);
startActivity(gotoMaths);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
});
dispatcherMAIN.addAudioProcessor(pitchProcessorMAIN);
new Thread(dispatcherMAIN, "Audio Dispatcher").start();
isListening = true;
}
#Override
protected void onPause() {
super.onPause();
if (notifySound != null) {
notifySound.release();
}
if (endSound != null) {
endSound.release();
}
if (isListening) {
try {
dispatcherMAIN.stop();
} catch (Exception e) {
e.printStackTrace();
}
isListening = false;
}
finish();
}
#Override
public void onStop(){
super.onStop();
if (tts != null) {
tts.shutdown();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
if(OPTION == "3") {
speakOut();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
As part of my learning Android Threading, I have done the below code.
package simple.learning.com.samplethread;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
MyThread myThread;
Button button;
private static class MyThread extends Thread {
public Handler mHandler;
public void run () {
Log.d ("TESTME", " iNSIDE RUN..");
Looper.prepare();
mHandler = new Handler () {
public void HandleMessage (Message msg) {
Log.d("TESTME", "iNSIDE HandleMessage");
if ( msg.what == 0) {
someWork();
}
}
};
Looper.loop();
}
public void someWork()
{
while (true) {
Log.d("TESTME", "Inside someWork ");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myThread = new MyThread();
myThread.start();
Button btn = (Button) findViewById(R.id.button1);
assert btn != null;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myThread.mHandler != null) {
Log.d("TESTME", " bUTTON pRESSED..");
Message msg = myThread.mHandler.obtainMessage(0);
myThread.mHandler.sendMessage(msg);
}
}
});
}
}
When I Click the button, I expect the msg to be posted into the message queue. But, I don't see any output displayed. Any help would be appreciated.
You made a small mistake in overriding the handleMessage, instead of overriding the real one you added some method. Below is the working solution:
private static class MyThread extends Thread {
public Handler mHandler;
public void run() {
Log.d("TESTME", " iNSIDE RUN..");
Looper.prepare();
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.d("TESTME", "iNSIDE HandleMessage");
if (msg.what == 0) {
someWork();
}
}
};
Looper.loop();
}
public void someWork() {
while (true) {
Log.d("TESTME", "Inside someWork ");
}
}
}
This method works fine.
public void onClick(View view) {
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
EditText login = (EditText) findViewById(R.id.loginfld);
EditText passw = (EditText) findViewById(R.id.passfld);
String logincmd = "CheckLogin*" + login.getText() + "*" + passw.getText() + "*";
ss.senddata(logincmd, 1);
}
In this method java.lang.NullPointerException appears (on btn.setVisibility(View.VISIBLE);
public void geturdata(String answer) {
if (answer != null)
{
System.out.println("true");
btn.setVisibility(View.VISIBLE);
}
else
{
System.out.println("false");
}
}
Please tell me how can I call button in this method? Also I can't use StartActivity(intent) in this method.(same error). Both metods placed in one activity.
Here is full code
This is activity
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class Login extends Activity {
SocketServer ss = new SocketServer();
Button btn;
ProgressBar progr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
try {
ss.setserver();
} catch (Exception ex) {
System.out.println("------- " + ex);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add("menu1");
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view) {
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
EditText login = (EditText) findViewById(R.id.loginfld);
EditText passw = (EditText) findViewById(R.id.passfld);
String logincmd = "CheckLogin*" + login.getText() + "*" + passw.getText() + "*";
ss.senddata(logincmd, 1);
}
public void geturdata(String answer) {
if (answer != null)
{
System.out.println("true");
btn.setVisibility(View.VISIBLE);
}
else
{
System.out.println("false");
}
}
}
And this is class that call >geturdata
import android.os.Looper;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketServer {
private Socket socket;
private static final int SERVERPORT = 11000;
private static String SERVER_IP = "192.168.2.222";
String answer;
private static String cmdtext;
private static int caller;
class ClientThread implements Runnable
{
public void run() {
if (cmdtext.equals("setserver"))
{
try
{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
}
catch (Exception ex)
{System.out.println(ex);}
}
else {
try {
String str = cmdtext;
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
byte[] data = new byte[256];
InputStream inp = socket.getInputStream();
inp.read(data);
answer = new String(data, "UTF-8");
Looper.prepare();
handledata(answer);
Looper.loop();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
////////////////////////////////////////
public void setserver ()
{
new Thread(new ClientThread()).start();
cmdtext = "setserver";
}
private void handledata(String answer)
{
switch (caller) {
case 1:
{
Login lgn = new Login();
lgn.geturdata(answer);
}
}
}
public void senddata(String cmd, int callerid)
{
this.cmdtext = cmd;
this.caller = callerid;
new Thread(new ClientThread()).start();
}
}
btn is null when you call geturdata(). You should call btn = (Button) findViewById(R.id.trytogetin); directly after setContentView(R.layout.activity_main); in public void onCreate(Bundle b)
private Button btn;
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.trytogetin);
...
}
EDIT:
But, seeing your code now, thats not the problem. There are two problems here
Login lgn = new Login();
lgn.geturdata(answer);
You try to instantiate an Activity. You should start activities through intents, so that they are instanciated in the normal Activity lifecycle: through onCreate.
But there's more: You try to set the Button from another Thread than the one which created the Button (the UI-thread)
You can try to get a handle from the context in the thread, and call context.runOnUiThread(Runnable). That way you can update the UI from other Threads.
So the NPE is caused by the fact that you instantiate Login (which has to be done by Android), and call a method, but theres no ContentView inflated, so the Button is not found anyway, findViewById returns null
You are getting id of button inside click method. So to solve the problem , get your button id in oncreate() method. So you can access button anywhere. But declare button globaly
Declare this in OnCreate()
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
public void onClick(View view) {
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
}
String logincmd = "CheckLogin*" + login.getText().toString() + "*" + passw.getText().toString() + "*";
So reference to this method geturdata where you used object of Button btn returns null, since you used inside onClick button.
public void geturdata(String answer) {
I'm working on an android app and I have a problem that i wish you could help me solve it.
So i have an activity1 called MainActivity and activity2 called myown. In myown i have a public class that i want to call in an onItemClick() in MainActivity . Here's the code of both activities below :
MainActivity.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ActionBarActivity {
class Active extends myown {
}
private BluetoothAdapter btadapter;
private Set<BluetoothDevice> pairedDevices;
private SeekBar redcontrol = null;
private SeekBar greencontrol = null;
private SeekBar bluecontrol = null;
private TextView redv;
private TextView greenv;
private TextView bluev;
private ListView lv;
LinearLayout linearLayout;
Button on, off, button;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert bluetooth devices MAC address
private static String address = "00:14:02:13:08:21";
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
finish();
System.exit(10);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btadapter = (BluetoothAdapter.getDefaultAdapter());
button = (Button)findViewById(R.id.button);
lv = (ListView)findViewById(R.id.listView1);
btadapter = BluetoothAdapter.getDefaultAdapter();
button = (Button) findViewById(R.id.button);
redv = (TextView) findViewById(R.id.redv);
greenv = (TextView) findViewById(R.id.greenv);
bluev = (TextView) findViewById(R.id.bluev);
redcontrol = (SeekBar) findViewById(R.id.seekBar);
greencontrol = (SeekBar) findViewById(R.id.seekBar2);
bluecontrol = (SeekBar) findViewById(R.id.seekBar3);
redcontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
redv.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
//Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
// Toast.LENGTH_SHORT).show();
}
});
greencontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
greenv.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
//Toast.LENGTH_SHORT).show();
}
});
bluecontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
bluev.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
//Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
// Toast.LENGTH_SHORT).show();
}
});
linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
on = (Button) findViewById(R.id.on);
off = (Button) findViewById(R.id.off);
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
on.setBackgroundColor(Color.parseColor("#57D3E8"));
off.setBackgroundColor(Color.parseColor("#EAEAEA"));
if (!btadapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Bluetooth Turning On"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Already On",
Toast.LENGTH_SHORT).show();
}
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
off.setBackgroundColor(Color.parseColor("#57D3E8"));
on.setBackgroundColor(Color.parseColor("#EAEAEA"));
if (btadapter.isEnabled()) {
btadapter.disable();
Toast.makeText(getApplicationContext(), "Bluetooth Off"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Already Off",
Toast.LENGTH_SHORT).show();
}
}
});
}
public void list(View view) {
pairedDevices = btadapter.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName() +"\n" + bt.getAddress() );
Toast.makeText(getApplicationContext(),"Showing Paired Devices",
Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter
(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
for (BluetoothDevice device : pairedDevices) {
if ("bluetooth".equals(device.getName())) {
Intent launchActivity2 = new Intent(MainActivity.this, myown.class);
MainActivity.this.startActivity(launchActivity2);
break;
}
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(true)) {
Toast.makeText(getBaseContext(), "Connected",Toast.LENGTH_SHORT).show();
//do nothing
}else {
Toast.makeText(getBaseContext(), "Unable to connect Light",Toast.LENGTH_SHORT).show();
}
view.setEnabled(false);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
myown.java
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import java.io.IOException;
import java.util.UUID;
public class myown {
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;
public BluetoothSocket scSocket;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
connectBT = new ConnectToBluetooth(discoveredDevice);
new Thread(connectBT).start();
}
class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
} catch (IOException createSocketException) {
}
}
#Override
public void run() {
try {
mySocket.connect();
scSocket = mySocket;
} catch (IOException connectException) {
try {
mySocket.close(); //try to close the socket
} catch (IOException closeException) {
}
return;
}
}
// Will allow you to get the socket from this class
public BluetoothSocket getSocket() {
return mySocket;
}
/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
} catch (IOException e) {
}
}
}
}
}
add this to your activity
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
//add this
Intent launchActivity2 = new Intent(MainActivity.this, myown.class);
MainActivity.this.startActivity(launchActivity2);
//
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
for (BluetoothDevice device : pairedDevices) {
if ("bluetooth".equals(device.getName())) {
Intent launchActivity2 = new Intent(MainActivity.this, myown.class);
MainActivity.this.startActivity(launchActivity2);
break;
}
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(true)) {
Toast.makeText(getBaseContext(), "Connected",Toast.LENGTH_SHORT).show();
//do nothing
}else {
Toast.makeText(getBaseContext(), "Unable to connect Light",Toast.LENGTH_SHORT).show();
}
view.setEnabled(false);
}
}
});