I found some code in the Internet and changed it. I try to send a short string via Bluetooth. I use the HC-05 Bluetooth module.
I can connect my android device with the module but I can't send a string to my Arduino.
I have:
1 EditText to enter my string.
2 Buttons:
-1 to send
-2 to connect
Could you look over my code? Thank you:)
Android Code...
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
String command;//string variable that will store value to be transmitted to the bluetooth module
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button BtSend = findViewById(R.id.BtSend);
Button BtVerbinden = findViewById(R.id.BtVerbinden);
final EditText EtEingabe = findViewById(R.id.EtEingabe);
BtSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
command = EtEingabe.getText().toString();
try {
outputStream.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
});
//Button that connects the device to the bluetooth module when pressed
BtVerbinden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (BTinit()) {
BTconnect();
}
}
});
}
public boolean BTinit() {
boolean found = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) //Checks if the device supports bluetooth
{
Toast.makeText(getApplicationContext(), "Device doesn't support bluetooth", Toast.LENGTH_SHORT).show();
}
if (!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(), "Please pair the device first", Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iterator : bondedDevices) {
if (iterator.getAddress().equals(DEVICE_ADDRESS)) {
device = iterator;
found = true;
break;
}
}
}
return found;
}
public boolean BTconnect() {
boolean connected = true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID); //Creates a socket to handle the outgoing connection
socket.connect();
Toast.makeText(getApplicationContext(),
"Connection to bluetooth device successful", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
if (connected) {
try {
outputStream = socket.getOutputStream(); //gets the output stream of the socket
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream == null) {
try {
outputStream = socket.getOutputStream();
} catch (IOException e) {
}
}
return connected;
}
#Override
protected void onStart() {
super.onStart();
}
}
Android XML...
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.swini.gimbalarduino.MainActivity">
<Button
android:id="#+id/BtSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="184dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/EtEingabe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="220dp"
android:ems="10"
android:hint="Hoi"
android:inputType="textPersonName"
android:text="Text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/BtVerbinden"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Connect"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Try to use this code but this code run in Fragment so carefully change the Code according to your activity.
package com.example.rishabhrawat.tablayoutapp;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
/**
* Created by Rishabh Rawat on 6/18/2017.
*/
public class OfflineVideo extends android.support.v4.app.Fragment {
Button f,r,l,b,s,dis;
ListView listView;
ImageView mic;
BluetoothAdapter adapter;
private Set<BluetoothDevice> paireddevices;
private String address;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
private ProgressDialog progress;
private final int REQ_CODE_SPEECH_INPUT = 100;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.offlinevideo,container,false);
f=(Button)view.findViewById(R.id.forward);
r=(Button)view.findViewById(R.id.right);
l=(Button)view.findViewById(R.id.left);
b=(Button)view.findViewById(R.id.backward);
s=(Button)view.findViewById(R.id.stop);
dis=(Button)view.findViewById(R.id.discover);
mic=(ImageView)view.findViewById(R.id.mic);
listView=(ListView)view.findViewById(R.id.listview);
f.setEnabled(false);
r.setEnabled(false);
l.setEnabled(false);
b.setEnabled(false);
s.setEnabled(false);
mic.setEnabled(false);
adapter=BluetoothAdapter.getDefaultAdapter();
dis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowPairedDevices();
}
});
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forward();
}
});
r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
right();
}
});
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
left();
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backward();
}
});
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stop();
}
});
mic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VoiceInput();
}
});
return view;
}
public void ShowPairedDevices()
{
paireddevices=adapter.getBondedDevices();
ArrayList list = new ArrayList();
if (paireddevices.size()>0)
{
for(BluetoothDevice bt : paireddevices)
{
list.add(bt.getName() + "\n" + bt.getAddress());
}
}
else
{
Toast.makeText(getContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter=new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(myclicklistner);
}
private AdapterView.OnItemClickListener myclicklistner= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
new connectbt().execute();
}
};
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(getActivity(), "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)
{
adapter = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = adapter.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
}
}
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)
{
Toast.makeText(getActivity().getApplicationContext(),"Connection Failed Please Try again later",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Successfully Connected ", Toast.LENGTH_SHORT).show();
f.setEnabled(true);
r.setEnabled(true);
l.setEnabled(true);
b.setEnabled(true);
s.setEnabled(true);
mic.setEnabled(true);
isBtConnected = true;
}
progress.dismiss();
}
}
public void toast(String message)
{
Toast.makeText(getActivity().getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void forward()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("F".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void left()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("L".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void right()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("R".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void backward()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("B".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void stop()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("S".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
public void VoiceInput()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speak Command for Robot");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQ_CODE_SPEECH_INPUT)
{
if(resultCode==RESULT_OK)
{
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(result.get(0).equals("forward"))
{
forward();
}
else if(result.get(0).equals("backward"))
{
backward();
}
else if(result.get(0).equals("stop"))
{
stop();
}
else if(result.get(0).equals("left"))
{
left();
}
else if(result.get(0).equals("right"))
{
right();
}
else
{
Toast.makeText(getActivity(), result.get(0), Toast.LENGTH_SHORT).show();
}
}
}
}
}
Layout File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/forward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forward"
android:background="#00bfff"
android:textColor="#fff"
android:layout_above="#+id/stop"
android:layout_alignStart="#+id/stop"
android:layout_marginBottom="27dp" />
<Button
android:id="#+id/backward"
android:background="#00bfff"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/forward"
android:layout_centerVertical="true"
android:text="Backward"
/>
<Button
android:id="#+id/left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginEnd="14dp"
android:text="Left"
android:background="#00bfff"
android:textColor="#fff"
android:layout_above="#+id/backward"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="#00bfff"
android:textColor="#fff"
android:layout_alignTop="#+id/left"
android:layout_marginStart="17dp"
android:text="Right" />
<Button
android:id="#+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:background="#d22d2d"
android:textColor="#fff"
android:layout_alignBaseline="#+id/right"
android:layout_alignBottom="#+id/right"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/backward"
android:divider="#52f202"
android:dividerHeight="1dp"
android:id="#+id/listview"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<Button
android:id="#+id/discover"
android:background="#80ff00"
android:textSize="25dp"
android:textColor="#000099"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:fontFamily="sans-serif-smallcaps"
android:text="Discovery"
android:textAppearance="#style/TextAppearance.AppCompat.Light.Widget.PopupMenu.Large" />
<ImageView
android:id="#+id/mic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/discover"
app:srcCompat="#drawable/microphone" />
</RelativeLayout>
Arduino Code
char myserial;
void setup()
{
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
pinMode(9,OUTPUT);
pinMode(8,OUTPUT);
Serial.begin(9600);
}
void loop()
{
myserial=Serial.read();
switch(myserial)
{
case 'S':
digitalWrite(11,LOW);
digitalWrite(10,LOW);
digitalWrite(9,LOW);
digitalWrite(8,LOW);
break;
case 'B':
digitalWrite(11,HIGH);
digitalWrite(10,LOW);
digitalWrite(9,HIGH);
digitalWrite(8,LOW);
break;
case 'F':
digitalWrite(11,LOW);
digitalWrite(10,HIGH);
digitalWrite(9,LOW);
digitalWrite(8,HIGH);
break;
case 'L':
digitalWrite(11,HIGH);
digitalWrite(10,LOW);
digitalWrite(9,LOW);
digitalWrite(8,HIGH);
break;
case 'R':
digitalWrite(11,LOW);
digitalWrite(10,HIGH);
digitalWrite(9,HIGH);
digitalWrite(8,LOW);
break;
}
}
btSocket.getOutputStream().write(sendText.getText().toString().getBytes());
.
Related
I'm trying to incorporate somehow into Android audio player, functionality of marking of the fragment of the song in the player that it is supposed to play. I see this like clipping of the fragment as in Audacity. I'm trying to get it with a range seekbar (two blue dots on a line that can be adjust) on which user mark the beginning and the end to play and when replay mode is enabled the player will play that marked section over and over again.
This player looks like this
The application is written in the Java language.
Below are the related code.
Dependency
implementation 'com.yahoo.mobile.client.android.util.rangeseekbar:rangeseekbar-
library:0.1.0'
PlayerActivity.java
package com.example.marcin.playerexperiment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import com.yahoo.mobile.client.android.util.rangeseekbar.RangeSeekBar;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class PlayerActivity extends AppCompatActivity {
RangeSeekBar<Integer> mRangeSeekBar;
MediaPlayer mMediaPlayer;
Button playButton, openButton, replayButton;
int max;
SeekBar mSeekBar;
public static final int PICK_FILE =99;
ScheduledExecutorService timer;
TextView title, elapse, mEndTextView;
String duration;
Boolean isRepeat = false;
Runnable mRunnable;
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
//otwórz
openButton = findViewById(R.id.open);
//powtórz
replayButton = findViewById(R.id.replayButton);
//range seekbar
mRangeSeekBar = findViewById(R.id.rangeSeekBar);
//seekbar - linia dzwięku
mSeekBar = findViewById(R.id.seekBar);
//mRangeSeekBar.setNotifyWhileDragging(true);
title = (TextView) findViewById(R.id.title);
elapse = (TextView) findViewById(R.id.elapse);
playButton = findViewById(R.id.play);
// mEndTextView = findViewById(R.id.end_duration);
mHandler = new Handler();
//Odtwórz |>
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mMediaPlayer != null){
if(mMediaPlayer.isPlaying()){
mMediaPlayer.pause();
playButton.setText("ODTWÓRZ");
timer.shutdown();
}else{
mMediaPlayer.start();
playButton.setText("PAUZA");
timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
// playProgress ();
if (mMediaPlayer != null) {
if (!mSeekBar.isPressed()) {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
}
}
}
},10,10, TimeUnit.MILLISECONDS);
}
}
}
});
//otwieranie pliku dzwiękowego
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("audio/*");
startActivityForResult(intent, PICK_FILE);
}
});
mRangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
mMediaPlayer.seekTo(minValue);
max = maxValue;
String infoMax = String.valueOf(max);
Log.i("MAX", infoMax);
}
});
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (mMediaPlayer != null){
int millis = mMediaPlayer.getCurrentPosition();
long total_secs = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
elapse.setText(mins + ":" + secs + " / " + duration);
//Log.i("Duration:", duration);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(seekBar.getProgress());
}
}
});
//Loop
replayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//repeat = false
if(isRepeat){
isRepeat = false;
mMediaPlayer.setLooping(false);
replayButton.setText("Powtórka wyłączona");
Toast.makeText(PlayerActivity.this, "Tryb powtórki jest wyłączony", Toast.LENGTH_SHORT).show();
}else{
isRepeat = true;
mMediaPlayer.setLooping(true);
replayButton.setText("Powtórka włączona");
Toast.makeText(PlayerActivity.this, "Tryb powtórki jest włączony", Toast.LENGTH_SHORT).show();
}
//mediaPlayer.setLooping(true);
// Toast.makeText(PlayerActivity.this, "Repeat if ON", Toast.LENGTH_SHORT).show();
}
});
playButton.setEnabled(false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE && resultCode == RESULT_OK){
if (data != null){
Uri uri = data.getData();
createMediaPlayer(uri);
}
}
}
public void createMediaPlayer(Uri uri){
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mMediaPlayer.setDataSource(getApplicationContext(), uri);
mMediaPlayer.prepare();
title.setText(getNameFromUri(uri));
playButton.setEnabled(true);
mRangeSeekBar.setNotifyWhileDragging(true);
mRangeSeekBar.setRangeValues(0, mMediaPlayer.getDuration());
max = mMediaPlayer.getDuration();
mSeekBar.setMax(max);
mSeekBar.setProgress(0);
long total_secs = TimeUnit.SECONDS.convert(max, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
duration = mins + ":" + secs;
elapse.setText("00:00 / " + duration);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
} catch (IOException e){
title.setText(e.toString());
}
}
#SuppressLint("Range")
public String getNameFromUri(Uri uri){
String fileName = "";
Cursor cursor = null;
cursor = getContentResolver().query(uri, new String[]{
MediaStore.Images.ImageColumns.DISPLAY_NAME
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
}
if (cursor != null) {
cursor.close();
}
return fileName;
}
private void playProgress () {
if (mMediaPlayer.getCurrentPosition() == max) {
mMediaPlayer.stop();
}
if (mMediaPlayer.isPlaying()) {
mRunnable = new Runnable() {
#Override
public void run() {
playProgress();
}
};
mHandler.postDelayed(mRunnable, 0);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
public void releaseMediaPlayer(){
if (timer != null) {
timer.shutdown();
}
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
playButton.setEnabled(false);
elapse.setText("TYTUL");
elapse.setText("00:00 / 00:00");
mSeekBar.setMax(100);
mSeekBar.setProgress(0);
}
}
Activity_player.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".PlayerActivity">
<Button
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="37dp"
android:layout_marginStart="150dp"
android:layout_marginEnd="173dp"
android:text="Play"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/seekBar" />
<com.yahoo.mobile.client.android.util.rangeseekbar.RangeSeekBar
android:id="#+id/rangeSeekBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="357dp"
android:layout_marginBottom="20dp"
app:layout_constraintBottom_toTopOf="#+id/seekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/elapse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="287dp"
android:layout_marginBottom="51dp"
android:text="00-00"
app:layout_constraintBottom_toTopOf="#+id/rangeSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.461"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rangeSeekBar" />
<androidx.constraintlayout.widget.Barrier
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="top"
tools:layout_editor_absoluteX="92dp"
tools:layout_editor_absoluteY="357dp" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="154dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="140dp"
android:backgroundTint="#color/teal_200"
android:text="Open file"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/play" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="173dp"
android:layout_marginEnd="202dp"
app:layout_constraintBottom_toTopOf="#+id/elapse"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.824" />
<Button
android:id="#+id/replayButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginEnd="142dp"
android:backgroundTint="#color/purple_500"
android:text="Replay"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/open" />
</androidx.constraintlayout.widget.ConstraintLayout>
I got a little problem with my android app. It is an app to determine the steadiness of hand using accelerometer.I have two activities, Vert.java and Calcu.java. In Vert.java there is an animation function comprising of 25 png files. It also has the functions to retrieve the acceleromter values of x,y and z axes. A combined value is transferred to Calcu.java, where scores are given for specific range of values using if loop.But, while running the "Calcu" activity is reappearing. I am new to android. Please help.
These are my codes..
Vert.java
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
public class Vert extends Activity implements SensorEventListener{
Sensor accelerometer1;
SensorManager sm1;
float x1=0,y1=0,z1=0,tx1=0,ty1=0,tz1=0,oldx1=0,oldy1=0,oldz1=0,totalx1=0,totaly1=0,totalz1=0;
Intent m1;
int z;
ImageView img;
Timer timer;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.slide_in,R.anim.slide_out);
setContentView(R.layout.vert);
sm1=(SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer1=sm1.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm1.registerListener(this, accelerometer1,SensorManager.SENSOR_DELAY_NORMAL);
img=(ImageView)findViewById(R.id.ivAnim);
AnimationDrawable animation=new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.a),200);
animation.addFrame(getResources().getDrawable(R.drawable.b),200);
animation.addFrame(getResources().getDrawable(R.drawable.c),200);
animation.addFrame(getResources().getDrawable(R.drawable.d),200);
animation.addFrame(getResources().getDrawable(R.drawable.e),200);
animation.addFrame(getResources().getDrawable(R.drawable.f),200);
animation.addFrame(getResources().getDrawable(R.drawable.g),200);
animation.addFrame(getResources().getDrawable(R.drawable.h),200);
animation.addFrame(getResources().getDrawable(R.drawable.i),200);
animation.addFrame(getResources().getDrawable(R.drawable.j),200);
animation.addFrame(getResources().getDrawable(R.drawable.k),200);
animation.addFrame(getResources().getDrawable(R.drawable.l),200);
animation.addFrame(getResources().getDrawable(R.drawable.m),200);
animation.addFrame(getResources().getDrawable(R.drawable.n),200);
animation.addFrame(getResources().getDrawable(R.drawable.o),200);
animation.addFrame(getResources().getDrawable(R.drawable.p),200);
animation.addFrame(getResources().getDrawable(R.drawable.q),200);
animation.addFrame(getResources().getDrawable(R.drawable.r),200);
animation.addFrame(getResources().getDrawable(R.drawable.s),200);
animation.addFrame(getResources().getDrawable(R.drawable.t),200);
animation.addFrame(getResources().getDrawable(R.drawable.u),200);
animation.addFrame(getResources().getDrawable(R.drawable.v),200);
animation.addFrame(getResources().getDrawable(R.drawable.w),200);
animation.addFrame(getResources().getDrawable(R.drawable.x),200);
animation.addFrame(getResources().getDrawable(R.drawable.y),200);
animation.setOneShot(false);
img.setImageDrawable(animation);
animation.start();
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
x1=event.values[0];
y1=event.values[1];
z1=event.values[2];
timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
oldx1=x1;
oldy1=y1;
oldz1=z1;
}
}, 200, 200);
String str=String.valueOf(tx1);
m1=new Intent(Vert.this,Calcu.class);
m1.putExtra("score", str);
if(oldx1>x1){
totalx1=oldx1-x1;
}
else if(x1>oldx1){
totalx1=x1-oldx1;
}
if(oldy1>y1){
totaly1=oldy1-y1;
}
else if(y1>oldy1){
totaly1=y1-oldy1;
}
if(oldz1>z1){
totalz1=oldz1-z1;
}
else if(z1>oldz1){
totalz1=z1-oldz1;
}
tx1=tx1+(totalx1+totaly1+totalz1);
handler=new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
startActivity(Vert.this.m1);
m1.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
finish();
}
},5000);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
this.sm1.unregisterListener(this);
timer.cancel();
}
}
Vert.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/vertpageplain"
android:padding="20dp"
android:orientation="vertical" >
<TextView
android:id="#+id/tvVertHead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="30dp"
android:textColor="#138808"
android:text="KEEP YOUR HANDS STEADY TILL THE BOTTLE GETS EMPTY..." />
<ImageView
android:id="#+id/ivAnim"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:src="#drawable/a" />
</LinearLayout>
Calcu.java
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
public class Calcu extends Activity{
float krip1;
double score1;
String sScore;
TextView finalScore1;
ImageButton bB1,bS1,bE1;
Bitmap b;
Intent intent,chooser;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.slide_in,R.anim.slide_out);
setContentView(R.layout.result);
String pky1 = getIntent().getStringExtra("score");
krip1=Float.valueOf(pky1);
finalScore1=(TextView)findViewById(R.id.tvScore1);
bB1=(ImageButton)findViewById(R.id.bMain1);
bS1=(ImageButton)findViewById(R.id.bShare1);
bE1=(ImageButton)findViewById(R.id.bExit1);
bB1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent n=new Intent(Calcu.this,Play.class);
n.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
n.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(n);
}
});
bS1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(score1==10){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorea);
}
else if(score1==9.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreb);
}
else if(score1==9){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorec);
}
else if(score1==8.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scored);
}
else if(score1==8){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoree);
}
else if(score1==7.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoref);
}
else if(score1==7){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreg);
}
else if(score1==6.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreg);
}
else if(score1==6){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorei);
}
else if(score1==5.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorej);
}
else if(score1==5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorek);
}
else if(score1==4.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorel);
}
else if(score1==4){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorem);
}
else if(score1==3.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoren);
}
else if(score1==3){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreo);
}
else if(score1==2.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorep);
}
else if(score1==2){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreq);
}
else if(score1==1.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorer);
}
else if(score1==1){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scores);
}
else if(score1==0.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoret);
}
else if(score1==0){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreu);
}
intent=new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
ByteArrayOutputStream bytes=new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bytes);
String path=MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
imageUri=Uri.parse(path);
intent.putExtra(Intent.EXTRA_TITLE, "SOBER SCORE CHALLENGE");
intent.putExtra(Intent.EXTRA_SUBJECT, "Sober score : "+score1+"What's your's?");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.putExtra(Intent.EXTRA_TEXT, "This is beta version. The final version will soon be available in play store.");
chooser=Intent.createChooser(intent, "Share your Sober Score...");
startActivity(chooser);
}
});
bE1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent exit=new Intent(getApplicationContext(),MainActivity.class);
exit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
exit.putExtra("EXIT", true);
startActivity(exit);
}
});
if(krip1<90){
score1=10;
}
else if(90<krip1 && krip1<100){
score1=9.5;
}
else if(100<krip1 && krip1<110){
score1=9;
}
else if(110<krip1 && krip1<135){
score1=8.5;
}
else if(135<krip1 && krip1<150){
score1=8;
}
else if(150<krip1 && krip1<160){
score1=7.5;
}
else if(160<krip1 && krip1<175){
score1=7;
}
else if(175<krip1 && krip1<185){
score1=6.5;
}
else if(185<krip1 && krip1<195){
score1=6;
}
else if(195<krip1 && krip1<210){
score1=5.5;
}
else if(210<krip1 && krip1<215){
score1=5;
}
else if(215<krip1 && krip1<225){
score1=4.5;
}
else if(225<krip1 && krip1<245){
score1=4;
}
else if(245<krip1 && krip1<265){
score1=3.5;
}
else if(265<krip1 && krip1<285){
score1=3;
}
else if(285<krip1 && krip1<305){
score1=2.5;
}
else if(305<krip1 && krip1<335){
score1=2;
}
else if(335<krip1 && krip1<365){
score1=1.5;
}
else if(365<krip1 && krip1<395){
score1=1;
}
else if(395<krip1 && krip1<425){
score1=0.5;
}
else if(krip1>425){
score1=0;
}
finalScore1.setText(""+score1+"");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent back=new Intent(Calcu.this,MainActivity.class);
back.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
back.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(back);
Calcu.this.finish();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
}
Result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/resultpageplain"
android:orientation="vertical"
>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:src="#drawable/sobercent" />
<TextView
android:id="#+id/tvScore1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="70dp"
android:textColor="#138808"
android:text="X" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageButton
android:id="#+id/bMain1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:src="#drawable/bplayagain" />
<ImageButton
android:id="#+id/bShare1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="50dp"
android:src="#drawable/bshare" />
</LinearLayout>
<ImageButton
android:id="#+id/bExit1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0dp"
android:layout_gravity="center"
android:gravity="center"
android:src="#drawable/bexit" />
</LinearLayout>
Replace the below code snip it should work
#Override
public void run() {
// TODO Auto-generated method stub
startActivity(Vert.this.m1);
m1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
finish();
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Hello I would like to ask for help on how to get the if else statements found below inside a onreceive from a broadcastreceiver . Im trying to change the button background depending on the value received. like when I receive the value 1 the button image will change to onn . Because it does not work when I place if else statements, but if I place the btn.setBackgroundResource(R.drawable.onn); before the if else statements it works fine however it defeats the purpose of having the app show which button is at on state. I'm trying to create an app that will update 6 switches depending on the text message. Like if I receive 111000 the first three switches will change image to on. TIA
Main activity
package com.example.asd;
import java.lang.reflect.Array;
import java.text.BreakIterator;
import android.R.array;
import android.R.layout;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.widget.TextView;
public class MainActivity extends Activity {
String[] bin={"0","0","0","0","0","0"};
String[] bin1={"0","0","0","0","0","0"};
Button zero,one,two,three,four,five,update,refresh;
IntentFilter intentFilter;
TextView tv1;
private final BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//---display the SMS received in the TextView---
init();
zero=(Button)findViewById(R.id.one);
bin[0]=intent.getStringExtra("zero");
if (bin[0]!=null && bin[0].equalsIgnoreCase("1")) {
zero.setBackgroundResource(R.drawable.onn);
}
else {
zero.setBackgroundResource(R.drawable.off);
}
one=(Button)findViewById(R.id.two);
bin[1]=intent.getStringExtra("one");
if (bin[1]!=null && bin[1].equalsIgnoreCase("1")) {
one.setBackgroundResource(R.drawable.onn);
}
else {
one.setBackgroundResource(R.drawable.off);
}
two=(Button)findViewById(R.id.three);
bin[2]=intent.getStringExtra("two");
if (bin[2]!=null && bin[2].equalsIgnoreCase("1")) {
two.setBackgroundResource(R.drawable.onn);
}
else {
two.setBackgroundResource(R.drawable.off);
}
three=(Button)findViewById(R.id.four);
bin[3]=intent.getStringExtra("three");
if (bin[3]!=null && bin[3].equalsIgnoreCase("1")) {
three.setBackgroundResource(R.drawable.onn);
}
else {
three.setBackgroundResource(R.drawable.off);
}
four=(Button)findViewById(R.id.five);
bin[4]=intent.getStringExtra("four");
if (bin[4]!=null && bin[4].equalsIgnoreCase("1")) {
four.setBackgroundResource(R.drawable.onn);
}
else {
four.setBackgroundResource(R.drawable.off);
}
five=(Button)findViewById(R.id.six);
bin[5]=intent.getStringExtra("five");
if (bin[5]!=null && bin[5].equalsIgnoreCase("1")) {
five.setBackgroundResource(R.drawable.onn);
}
else {
five.setBackgroundResource(R.drawable.off);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---intent to filter for SMS messages received---
intentFilter = new IntentFilter();
zero=(Button)findViewById(R.id.one);
one=(Button)findViewById(R.id.two);
two=(Button)findViewById(R.id.three);
three=(Button)findViewById(R.id.four);
four=(Button)findViewById(R.id.five);
five=(Button)findViewById(R.id.six);
refresh=(Button)findViewById(R.id.refresh);
update=(Button)findViewById(R.id.update);
intentFilter.addAction("SMS_RECEIVED_ACTION");
zero.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[0]=="1") {
bin[0]="0";
updateBtn();
}
else {
bin[0]="1";
updateBtn();
}
}
});
one.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[1].equals("1")) {
bin[1]="0";
updateBtn();
}
else {
bin[1]="1";
updateBtn();
}
}
});
two.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[2].equals("1")) {
bin[2]="0";
updateBtn();
}
else {
bin[2]="1";
updateBtn();
}
}
});
three.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[3].equals("1")) {
bin[3]="0";
updateBtn();
}
else {
bin[3]="1";
updateBtn();
}
}
});
four.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[4].equals("1")) {
bin[4]="0";
updateBtn();
}
else {
bin[4]="1";
updateBtn();
}
}
});
five.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[5].equals("1")) {
bin[5]="0";
updateBtn();
}
else {
bin[5]="1";
updateBtn();
}
}
});
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
updateBtn();
String s="";
for (int i = 0; i < 6; i++) {
s+= bin[i];
}
String upToNCharacters = s.substring(0, Math.min(s.length(), 6));
Toast.makeText(getBaseContext(),upToNCharacters+"00", Toast.LENGTH_LONG).show();
s="";
}
});
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateBtn();
//Toast.makeText(getBaseContext(),s0+s1+s2+s3+s4+s5+"00", Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(),bin[0]+bin[1]+bin[2]+bin[3]+bin[4]+bin[5]+"00", Toast.LENGTH_LONG).show();
}
});
}
private void updateBtn() {
for (int i = 0; i < 6; i++) {
if (bin[i]==null) {
bin[i]="0";
}
else
{
bin[i]=bin[i];
}
}
if (bin[0]=="1") {
zero.setBackgroundResource(R.drawable.onn);
}
else if(bin[0]=="0"){
zero.setBackgroundResource(R.drawable.off);
}
if (bin[1]=="1") {
one.setBackgroundResource(R.drawable.onn);
}
else if(bin[1]=="0"){
one.setBackgroundResource(R.drawable.off);
}
if (bin[2]=="1") {
two.setBackgroundResource(R.drawable.onn);
}
else if(bin[2]=="0"){
two.setBackgroundResource(R.drawable.off);
}
if (bin[3]=="1") {
three.setBackgroundResource(R.drawable.onn);
}
else if(bin[3]=="0"){
three.setBackgroundResource(R.drawable.off);
}
if (bin[4]=="1") {
four.setBackgroundResource(R.drawable.onn);
}
else if(bin[4]=="0"){
four.setBackgroundResource(R.drawable.off);
}
if (bin[5]=="1") {
five.setBackgroundResource(R.drawable.onn);
}
else if(bin[5]=="0"){
five.setBackgroundResource(R.drawable.off);
}
}
private void init() {
// TODO Auto-generated method stub
for (int i = 0; i < 6; i++) {
bin[i]="0";
}
}
#Override
protected void onResume() {
//---register the receiver---
registerReceiver(intentReceiver, intentFilter);
super.onResume();
}
#Override
protected void onPause() {
//---unregister the receiver---
unregisterReceiver(intentReceiver);
super.onPause();
}
}
activity xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/back"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="#+id/one"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/two"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/one"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/three"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/two"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/four"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/three"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/five"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/four"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/six"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/five"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/refresh"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="19dp"
android:layout_marginLeft="31dp"
android:background="#drawable/button" />
<Button
android:id="#+id/update"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="69dp"
android:layout_marginLeft="31dp"
android:background="#drawable/button" />
</RelativeLayout>
Smsreceiver
package com.example.asd;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver
{
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String[] bin=new String[6];
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += msgs[i].getMessageBody().toString();
bin[i]=msgs[i].getMessageBody().toString();
}
//---send a broadcast intent to update the SMS received in the activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("zero", bin[0]);
broadcastIntent.putExtra("one", bin[1]);
broadcastIntent.putExtra("two", bin[2]);
broadcastIntent.putExtra("three", bin[3]);
broadcastIntent.putExtra("four", bin[4]);
broadcastIntent.putExtra("five", bin[5]);
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
}
You have to use
if (bin[0].equals("1")) {
zero.setBackgroundResource(R.drawable.onn);
}
else {
zero.setBackgroundResource(R.drawable.off);
}
because Strings will be compared with equals() method, not with ==
Also, You have to be sure that this String is not null if You get it from an intent. Like:
bin[0]=intent.getStringExtra("zero");
if(bin[0]!=null){
//Your if/else statements
}
Don't use == to compare String. You have to use equals or equalsIgnoreCase for compare String see developer doc for String and code looks like
if (bin[0]!=null && bin[0].equalsIgnoreCase("1")) {
zero.setBackgroundResource(R.drawable.onn);
}
else {
zero.setBackgroundResource(R.drawable.off);
}
I am creating an app having login activity and used parse.com as the network service. I used the default loginactivity.java file in android studio. Inside my class UserLoginTask, I used the parse login methods. But I am not sure what is wrong. The app takes the email id and password. The progress bar works for a flip second and then the app shuts down.Then I get and error after sometime.
This is the loginactivty.java.
package com.redux.kumardivyarajat.attendance;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
/**
* A login screen that offers login via email/password.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class LoginActivity extends ActionBarActivity implements LoaderCallbacks<Cursor> {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
Button mSignUpButton = (Button)findViewById(R.id.SignUpButtonInsideLogin);
mSignUpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
//mSignUpTextView = (TextView) findViewById(R.id.SignupText);
}
private void populateAutoComplete() {
if (VERSION.SDK_INT >= 14) {
// Use ContactsContract.Profile (API 14+)
getLoaderManager().initLoader(0, null, this);
} else if (VERSION.SDK_INT >= 8) {
// Use AccountManager (API 8+)
new SetupEmailAutoCompleteTask().execute(null, null);
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
email = email.trim();
password = password.trim();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute();
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Use an AsyncTask to fetch the user's email addresses on a background thread, and update
* the email text field with results on the main UI thread.
*/
class SetupEmailAutoCompleteTask extends AsyncTask<Void, Void, List<String>> {
#Override
protected List<String> doInBackground(Void... voids) {
ArrayList<String> emailAddressCollection = new ArrayList<String>();
// Get all emails from the user's contacts and copy them to a list.
ContentResolver cr = getContentResolver();
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
null, null, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract
.CommonDataKinds.Email.DATA));
emailAddressCollection.add(email);
}
emailCur.close();
return emailAddressCollection;
}
#Override
protected void onPostExecute(List<String> emailAddressCollection) {
addEmailsToAutoComplete(emailAddressCollection);
}
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
/*try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;*/
ParseUser.logInInBackground(mEmail,mPassword, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null)
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle(R.string.loginup_error_title);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
And this is the error I get after a while. I think this error is because of the fact that the app closes down but the background task of fetching data from parse is still in progress. I am not sure.
com.redux.kumardivyarajat.attendance E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.redux.kumardivyarajat.attendance, PID: 22430
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#43010550 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:559)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.redux.kumardivyarajat.attendance.LoginActivity$UserLoginTask$1.done(LoginActivity.java:362)
at com.redux.kumardivyarajat.attendance.LoginActivity$UserLoginTask$1.done(LoginActivity.java:345)
at com.parse.Parse$6$1.run(Parse.java:945)
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:5047)
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:806)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
at dalvik.system.NativeStart.main(Native Method)
Please suggest what chages should I make in the UserLoginTask(asynctask) to make it work.
Edit: Adding the mainactivity.java and the activity_login2.xml.
activity_login2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.redux.kumardivyarajat.attendance.LoginActivity"
android:weightSum="1"
android:id="#+id/activity_login2">
<!-- Login progress -->
<ProgressBar android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:touchscreenBlocksFocus="false">
<AutoCompleteTextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true"
android:layout_weight="10.63">
<requestFocus/>
</AutoCompleteTextView>
<EditText android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"
android:textSize="20dp"/>
<Button android:id="#+id/email_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/action_sign_in_short"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id ="#+id/SignupText"
android:text="#string/sign_up_from_login"
android:textColor="#ffff0500"
android:layout_marginTop="50dp"
android:layout_weight="0.18" />
<Button
style="?android:textAppearanceSmall"
android:id="#+id/SignUpButtonInsideLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Sign Up"
android:textStyle="bold"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Now the on create method of mainactivity.java.
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
setContentView(R.layout.activity_main);
}
ParseAnalytics.trackAppOpened(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null) {
navigateToLogin();
} else {
Log.i(TAG,currentUser.getUsername());
}
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
According to your scenario, BadToken error may occurs when you try to show the particular view or a dialog once you finish the current activity. Whatever happens, your doinBackground return true, but when it get execute, you may have finish the activity. So i suggest you to proceed within the onpostExecute.
Try this,
Update your Async task as follows and return the status values from doInBackground. Then perform whatever the task based on return value with on onPostExecute.
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
private boolean status = false;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
ParseUser.logInInBackground(mEmail,mPassword, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null)
{
status = true;
} else {
status = false;
}
}
});
return status;
}
#Override
protected void onPostExecute(final Boolean success) {
if (success) {
// success code
} else {
// failure code
}
}
I Want To Add A Switch Camera Button To My Code.
Here is The Code.
I am not getting how do i do it.
Please Suggest Some Methods.
Thank you in Advance.
CameraDemo.java
public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick,switchCam;
int which=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
switchCam=(Button)findViewById(R.id.switchcam);
preview = new Preview(this);
((RelativeLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CameraDemo.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm");
// Setting Dialog Message
alertDialog.setMessage("Are You Done ?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.doneimg);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CameraDemo.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Student");
// Setting Dialog Message
alertDialog.setMessage("Are you a Student?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.student);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Intent i = new Intent(getApplicationContext(),
ScanId.class);
startActivity(i);
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "Sorry, Only Students Allowed", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "Sorry, Only Students Allowed", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
long time = 0;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
time = System.currentTimeMillis();
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",time));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
NExxt Java File >> Preview.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";
SurfaceHolder mHolder;
public Camera camera;
int which=0;
Preview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
camera.stopPreview();
camera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
// parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p= new Paint(Color.RED);
Log.d(TAG,"draw");
canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2, p );
}
}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/layout">
<RelativeLayout android:id="#+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/switchcam"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp" />
</RelativeLayout>
<Button android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/buttonClick"
android:text=""
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/circlebutton"
/>
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/gallery"
android:background="#drawable/grid"
android:layout_marginBottom="50dp"
android:layout_marginLeft="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Just reopen camera with open(int cameraId) method.
//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);