Writing .txt file on android - nothing happens - java

I have an android app which is recording audio and outputting it withe the name audiorecorder to the local storage on the phone.
Now i would like store a .txt file as well in same directory.
I have tried several methods from stack overflow, the app doesn't complain but does not store the .txt as it should. I can't figure out why.
The methods of interest is: CreateTxt and generateNote. These are the ones that doesn't do what they are supposed to.
These methods are used within the startR.setOnClickListener method.
Can anybody see why? Thank you in advance.
package xxxx;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class DataCollectionActivity extends AppCompatActivity {
private MediaPlayer mediaPLayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
public Button GoToUserAcc;
public Button GoToLogin;
public Button GoToTest;
// Permission Variables
private static final String LOG_TAG = "AudioRecordTest";
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private static String mFileName = null;
private boolean permissionToRecordAccepted = false;
private String [] permissions =
{Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET};
private static final int
REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 200;
private boolean permissionToWriteExternalStoragedAccepted =
false;
private static final int REQUEST_INTERNET_PERMISSION = 200;
private boolean permissionToUseInternetAccepted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_collec);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
Button startR = (Button) findViewById(R.id.Bstart);
Button stopR = (Button) findViewById(R.id.Bstop);
Button playRecording = (Button) findViewById(R.id.playBtn);
Button stopPlaying = (Button) findViewById(R.id.stopBtn);
final TextView statusTV;
statusTV = (TextView) findViewById(R.id.tStatus);
OUTPUT_FILE= Environment.getExternalStorageDirectory().
getAbsolutePath()+"/audiorecorder.3gpp";
ActivityCompat.requestPermissions(this, permissions,
REQUEST_RECORD_AUDIO_PERMISSION);
/*------START recording BUTTON------*/
startR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
beginRecording();
stv.setText("Recording");
//CreateTxt();
generateNote("MLdata", "sBody");
stv.setText("Created txt");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
stv.setText("Error");
}
}
});
/*------STOP BUTTON------*/
stopR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
stopRecording();
stv.setText("Stopped");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
Log.d("here","dd",e);
}
}
});
}
private void stopPlayback() throws Exception{
if(mediaPLayer != null)
mediaPLayer.stop();
}
private void playRecording() throws IOException {
ditchMediaPLayer();
mediaPLayer = new MediaPlayer();
mediaPLayer.setDataSource(OUTPUT_FILE);
mediaPLayer.prepare();
mediaPLayer.start();
}
private void ditchMediaPLayer() {
if (mediaPLayer != null) {
try{
mediaPLayer.release();
} catch(Exception e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
if(recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception{
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
//DataCollectionActivity dca = new DataCollectionActivity();
//dca.CreateTxt();
if (outFile.exists()) {
outFile.delete();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.
OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(OUTPUT_FILE);
/*API constraints
Container WAV
Encoding PCM
Rate 16K
Sample Format 16 bit OK
Channels Mono OK
*/
recorder.setAudioSamplingRate(16);
//channel 1 equals mono, 2 eqals stereo
recorder.setAudioChannels(1);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
if(recorder != null)
recorder.release();
}
#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.
if (item.getItemId() == R.id.action_setting){
Toast.makeText(DataCollectionActivity.this, "You have
clicked on setting action menu", Toast.LENGTH_SHORT).show();
}
if (item.getItemId() == R.id.action_about_us){
Toast.makeText(DataCollectionActivity.this, "You have
clicked on about us action menu", Toast.LENGTH_SHORT).show();
goToUserAccount();
}
return super.onOptionsItemSelected(item);
}
// Requesting permission to RECORD_AUDIO
//fra android.com
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull
String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
//---ny permission ---
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION:
permissionToWriteExternalStoragedAccepted =
grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
//---ny permission ---
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_INTERNET_PERMISSION:
permissionToUseInternetAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mMenuInflater = getMenuInflater();
mMenuInflater.inflate(R.menu.menu_main, menu);
return true;
}
/** Opens up new activity */
//Vedrører tollbaren som ligenu ikke bliver brugt /virker ikke.
public void goToUserAccount() {
Intent intent = new Intent(this, UserAccountActivity.class);
EditText editText = (EditText)
findViewById(R.id.action_about_us);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
//Metode som laver en writer.
public void CreateTxt() throws IOException {
//concerning txt file
int id = 0;
String typeId = "S";
EditText db = (EditText) findViewById(R.id.dbNoiseText);
String dbString = db.getText().toString();
EditText numPar = (EditText)
findViewById(R.id.participatorsText);
String npar = numPar.getText().toString();
EditText conversationBool = (EditText)
findViewById(R.id.CoverationText);
String cBool = conversationBool.getText().toString();
File f = new File(Environment.getExternalStorageDirectory().
getAbsolutePath()+"dataForML.txt");
try {
System.out.print("enters try in createtxt");
PrintWriter writer = new PrintWriter(f, "UTF-8");
writer.println(dbString + ", ");
writer.println(npar + ", ");
writer.println(cBool + ", ");
writer.println(typeId + id + ", ");
writer.println(Environment.getExternalStorageDirectory().
getAbsolutePath()+"/dataForML.txt");
//Her skal den skrive binary. Metoden ligger i asrRequest
writer.println("Path to Acceleroeter CSV file ");
writer.println("\n");
writer.println();
writer.close();
id++;
} catch (IOException e) {
e.printStackTrace();
}
}
//OUTPUT_FILE= Environment.getExternalStorageDirectory().
getAbsolutePath()+"/audiorecorder.3gpp";
//generateNoteOnSD("MLdata", "sBody");
public void generateNote(String sFileName, String sBody) {
try {
File root = new
File(Environment.getExternalStorageDirectory().
getAbsolutePath(), "NotesML");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
//Toast.makeText(context, "Saved",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void thirdTry(){
String FILENAME = "hello_file";
String string = "hello world!";
try{
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
layout xml comes here
<?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:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:weightSum="1">
<EditText
android:id="#+id/dbNoiseText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="db noise"
android:inputType="textPersonName"
android:textAlignment="center"
android:textSize="24sp" />
<EditText
android:id="#+id/participatorsText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="# participators"
android:inputType="textPersonName"
android:textAlignment="center"
android:textSize="24sp" />
<EditText
android:id="#+id/CoverationText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Conversation? Y/N"
android:inputType="textPersonName"
android:textAlignment="center" />
<Button
android:id="#+id/Bstart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Start Recording" />
<Button
android:id="#+id/Bstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Stop recording" />
<TextView
android:id="#+id/tStatus"
android:layout_width="354dp"
android:layout_height="42dp"
android:text="status"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>
Manifest comes here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dk.itu.percomp17.jumanji">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category
android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".UserAccountActivity" />
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity"/>
<activity android:name=".DataCollectionActivity"/>
<activity android:name=".CallingjsActivity">
</activity>
</application>
</manifest>

I found out. Following method solved it.
// Once a file has been created, use this method to publicize
//the file as it can be seen !!
// But be sure to add "Context context;" outside of the method.
// Plus, remember to add "context = getApplicationContext ();" in the
//onCreate () method.
public void scanFile(String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}

Related

When I try to open my app in Mobile or Android Studio. It says cannot read app data failed to launch app

I copied code from my previous project into this new one I stumbled upon this error. I tried to rebuild the project. I am not sure it did. I will provide you with any information you want. I tried running in Android Studio and it did give me anything other than this
06/14 22:23:30: Launching 'app' on Copy_of_Pixel 3a API 24 Backup.
App restart successful without requiring a re-install.
$ adb shell am start -n "com.example.turnovernodes/com.example.turnovernodes.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.turnovernodes">
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.TurnOverHosting"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="false"
tools:ignore="IntentFilterExportedReceiver">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-7460030581005035~1600535246" />
</application>
</manifest>
MainActivity.java
package com.example.turnovernodes;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
Button loadad;
Button showad;
TextView point;
TextView status_text;
EditText discord_id;
RewardedAd mRewardedAd;
Integer Ads_Watched = 0;
Integer Credits_Earned = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadad = findViewById(R.id.loadadbutton);
showad = findViewById(R.id.showadbutton);
point = findViewById(R.id.point);
status_text = findViewById(R.id.status_text);
discord_id = findViewById(R.id.discord_id);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Log.i("tag", "Initialization complete");
status_text.setText("Initialization complete. Make sure you put your discord ID above");
}
}, 5000);
}
});
loadad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str_discord_id = discord_id.getText().toString().replaceAll("\\s+", "");
if (str_discord_id.equals("") || str_discord_id.length() != 18) {
status_text.setText("Please enter a valid discord user ID.\nMake sure it is 18 digits long");
return;
}
Log.d("TAG", "Loading ad");
status_text.setText("Loading ad");
AdRequest adRequest = new AdRequest.Builder().build();
RewardedAd.load(com.example.turnovernodes.MainActivity.this, "\n" +
"ca-app-pub-7460030581005035/5128716716",
adRequest, new RewardedAdLoadCallback() {
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error.
Log.d("TAG", loadAdError.getMessage());
mRewardedAd = null;
status_text.setText("Ad load failed");
}
#Override
public void onAdLoaded(#NonNull RewardedAd rewardedAd) {
mRewardedAd = rewardedAd;
Log.d("TAG", "Ad was loaded.");
status_text.setText("Ad loaded and ready to be watched.\nClick SHOW AD to watch");
}
});
}
});
showad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str_discord_id = discord_id.getText().toString().replaceAll("\\s+", "");
if (str_discord_id.equals("") || str_discord_id.length() != 18) {
status_text.setText("Please enter a valid discord user ID.\nMake sure it is 18 digits long");
return;
}
status_text.setText("Trying to show ad");
if (mRewardedAd != null) {
Activity activityContext = MainActivity.this;
mRewardedAd.show(activityContext, new OnUserEarnedRewardListener() {
#Override
public void onUserEarnedReward(#NonNull RewardItem rewardItem) {
// Handle the reward.
Log.d("TAG", "The user earned the reward.");
int rewardAmount = rewardItem.getAmount();
String rewardType = rewardItem.getType();
Ads_Watched++;
Credits_Earned += rewardAmount;
point.setText("Ads Watched: " + Ads_Watched.toString() + "\nCredits Earned: " + Credits_Earned.toString());
try {
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create("{ \"credits\": \"" + rewardAmount + "\" }", JSON);
Request request = new Request.Builder()
.url("https://dash.turnover.ga/api/users/" + discord_id.getText().toString() + "/increment")
//.url("https://ApiRouter.fanisus.repl.co?credits=20")
.header("Authorization", "Bearer " + "E61kOmVMh85gdww5ey194K83eCAU0ICrWJwYh-P0_H0PuE8R")
.patch(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println("Dataaaaaaaaaaa: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
status_text.setText("Ad watched and credits added");
} catch (Exception e) {
e.printStackTrace();
status_text.setText("Error: " + e.toString());
}
mRewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d("TAG", "Ad was shown.");
status_text.setText("Ad was shown");
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.d("TAG", "Ad failed to show.");
status_text.setText("Ad failed to show");
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d("TAG", "Ad was dismissed.");
mRewardedAd = null;
}
});
// status_text.setText("The user earned " + rewardAmount + " " + rewardType);
}
});
} else {
Log.d("TAG", "The ad is not loaded yet");
status_text.setText("The ad is not loaded yet. Please click LOAD AD button if you haven't clicked it.");
}
}
});
}
}
ActivityMain.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"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="TurnOver Nodes"
android:textSize="40sp"
app:layout_constraintBottom_toTopOf="#+id/discord_id"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.653" />
<TextView
android:id="#+id/status_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Please put your discord user id"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/showadbutton"
app:layout_constraintVertical_bias="0.341" />
<TextView
android:id="#+id/point"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Ads Watched: 0\nCoins: 0"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/loadadbutton"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Load Ad"
app:layout_constraintBottom_toTopOf="#+id/showadbutton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/point" />
<Button
android:id="#+id/showadbutton"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Show Ad"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/point" />
<EditText
android:id="#+id/discord_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Put your Discord ID here"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toTopOf="#+id/point"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.785" />
</androidx.constraintlayout.widget.ConstraintLayout>```
I delete this line from Manifest and it didn't show the error
tools:ignore="IntentFilterExportedReceiver">

Can't find nearby WiFi- Direct devices showing "No Device Found!"

I am trying to Discover two devices each other using WifiDirect. Devices are running Android version 8.0 and 9.0 respectively. But not able to succeed.
First time I click on Discover button on both devices both waits for 2-3 seconds and shows No device found Toast.
Second time I try to discover on both within a second both show up the No device found Toast.
MainActivity.java
package com.example.prototypewfp2p;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.security.Permission;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, ConnectoinStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mMangaer;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
// Permissions Related
public String[] PermissionsList = {Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE
, Manifest.permission.CHANGE_NETWORK_STATE, Manifest.permission.ACCESS_FINE_LOCATION};
public int permsRequestCode = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permissions
for (int i = 0; i < PermissionsList.length; i++) {
if (ContextCompat.checkSelfPermission(MainActivity.this, PermissionsList[i]) == PackageManager.PERMISSION_DENIED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(PermissionsList, permsRequestCode);
}
} else {
Toast.makeText(MainActivity.this, "Permissions Granted Already!", Toast.LENGTH_SHORT).show();
}
}
//Calling Functions Declared below
initialWork();
exqListener();
}
//Permission (Override stuff)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (permsRequestCode) {
case 200:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission[1] granted!",Toast.LENGTH_LONG);
}
else{Toast.makeText(this,"Permission[1] Denied!",Toast.LENGTH_LONG);}
if(grantResults.length > 0 && grantResults[2] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 3 granted");}
if(grantResults.length > 0 && grantResults[3] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 4 granted");}
if(grantResults.length > 0 && grantResults[4] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 5 granted");}
if(grantResults.length > 0 && grantResults[5] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 6 granted");}
if(grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 2 granted");}
// boolean first = grantResults[0] == PackageManager.PERMISSION_GRANTED;
// boolean second = grantResults[1] == PackageManager.PERMISSION_GRANTED;
// boolean third = grantResults[2] == PackageManager.PERMISSION_GRANTED;
// boolean fourth = grantResults[3] == PackageManager.PERMISSION_GRANTED;
// boolean fifth = grantResults[4] == PackageManager.PERMISSION_GRANTED;
// boolean sixth = grantResults[5] == PackageManager.PERMISSION_GRANTED;
break;
}
}
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
// Toast.makeText(MainActivity.this,"Wifi is turned OFF",Toast.LENGTH_LONG).show();
} else {
wifiManager.setWifiEnabled(true);
// Toast.makeText(MainActivity.this,"Wifi is turned ON",Toast.LENGTH_LONG).show();
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
return;
}
mMangaer.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
ConnectoinStatus.setText("Discovery Started!");
}
#Override
public void onFailure(int reason) {
ConnectoinStatus.setText("Could not start Discovery");
}
});
}
});
}
private void initialWork() {
btnOnOff = (Button) findViewById(R.id.onOff);
btnDiscover = (Button) findViewById(R.id.discover);
btnSend = (Button) findViewById(R.id.sendButton);
listView = (ListView) findViewById(R.id.peerListView);
read_msg_box = (TextView) findViewById(R.id.readMsg);
ConnectoinStatus = (TextView) findViewById(R.id.connectionStatus);
writeMsg = (EditText) findViewById(R.id.writeMsg);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mMangaer = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mMangaer.initialize(this, getMainLooper(),null);
mReceiver = new WiFiDirectBroadcastReciever(mMangaer,mChannel,this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers) ){
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()]; //Size of deviceNameArray initialized
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()]; //Size of deviceArray initialized
int index = 0;
//assigning device name and device to 'deviceNameArray' and 'deviceArray'
for (WifiP2pDevice device: peerList.getDeviceList()){
deviceNameArray[index] = device.deviceName;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter= new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size()==0){
Toast.makeText(MainActivity.this,"No Device Found!",Toast.LENGTH_LONG).show();
return;
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
}
WiFiDirectBroadcastReciever.java
package com.example.prototypewfp2p;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import static android.media.audiofx.Visualizer.STATE_ENABLED;
public class WiFiDirectBroadcastReciever extends BroadcastReceiver {
private WifiP2pManager mMangaer;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReciever(WifiP2pManager mMangaer, WifiP2pManager.Channel mChannel, MainActivity mActivity) {
this.mMangaer = mMangaer;
this.mActivity = mActivity;
this.mChannel = mChannel;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Toast.makeText(context, "Wifi is On", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Wifi is Off", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
if (mMangaer != null) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(context,"Acces Location (BroadcastRec) Not granted",Toast.LENGTH_SHORT).show();
}
mMangaer.requestPeers(mChannel, mActivity.peerListListener);
}
}
else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
}
else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
}
}
}
activitymain.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/onOff"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="24dp"
android:layout_marginTop="47dp"
android:text="Wifi On/Off"
android:textSize="13dp" />
<Button
android:id="#+id/discover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/onOff"
android:layout_alignBottom="#+id/onOff"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:layout_marginLeft="0dp"
android:text="discover" />
<ListView
android:id="#+id/peerListView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/onOff"
android:layout_marginTop="25dp"
android:background="#android:color/holo_orange_light" />
<TextView
android:id="#+id/readMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/peerListView"
android:layout_marginTop="31dp"
android:text="Message"
android:textAlignment="center"
android:textSize="20sp"
android:textStyle="italic" />
<EditText
android:id="#+id/writeMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:ems="10"
android:inputType="textPersonName"
android:layout_toStartOf="#+id/sendButton" />
<Button
android:id="#+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="Send" />
<TextView
android:id="#+id/connectionStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="Connection Status"
android:textAlignment="center"
android:textColor="#android:color/holo_blue_dark"
android:textSize="18sp"
android:textStyle="italic" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prototypewfp2p">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Prototypewfp2p">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
IDK why But you have to enable gps (Location) on both devices.
I have also tested with android version 8 device and android 10 device gps enabled Both are working perfectly fine.

How to control button click according to the values stored in a variable using android studio?

I have made an android app using android studio were through bluetooth module (hc05) and arduino I'm sending sensor data to the app. I have added a torch application in it and willing to control it's on and off according to the range set for the value that gets stored in amount variable.
I had convert the string value of DATA into integer and stored it in amount variable. For this conversion I used:
amount = Integer.parseInt(DATA);
The torch on and off button is through Image button.
Java code:
package com.example.sugandhabansal.bluetooth_torch;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class bluetooth_torch_Activity extends Activity
{
TextView myLabel,mydata,myvalue;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private Boolean isTorchOn;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d("bluetooth_torch", "onCreate()");
setContentView(R.layout.activity_bluetooth_torch_);
Button openButton = (Button)findViewById(R.id.open);
Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.label);
myvalue = (TextView)findViewById(R.id.value);
mydata = (TextView)findViewById(R.id.data);
//Open Button
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Close button
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
mTorchOnOffButton = (ImageButton) findViewById(R.id.button_on_off);
isTorchOn = false;
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(bluetooth_torch_Activity.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();
}
}
});
}
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("HC-05"))
{
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Connected");
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 35; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String DATA = new String(encodedBytes, "US-ASCII");
Log.d("SKY",DATA);
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
mydata.setText(DATA);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
mTorchOnOffButton.setImageResource(R.drawable.on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
mTorchOnOffButton.setImageResource(R.drawable.off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#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();
}
}
}
Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sugandhabansal.bluetooth_torch">
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.flash" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name="bluetooth_torch_Activity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
layout design xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Connection"
android:layout_below="#+id/open"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="Open"
android:layout_above="#+id/value"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Value: "
android:id="#+id/value"
android:layout_marginTop="86dp"
android:layout_below="#+id/close" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="data"
android:id="#+id/data"
android:layout_alignTop="#+id/value"
android:layout_toEndOf="#+id/value" />
<ImageButton
android:layout_gravity="center"
android:id="#+id/button_on_off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:src="#drawable/off"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="45dp" />
</RelativeLayout>

Android studio E/MediaRecorder﹕ stop called in an invalid state: 4

I am trying to create a simple record and play audio application for android using MediaRecorder and MediaPlayer when i try to stop recording i get in the logcat the following error E/MediaRecorder﹕ stop called in an invalid state: 4 i am testing on a moto g 2013 16 gb memory version 5.1
Main activity
package com.example.sebastin.myapplication;
import android.content.DialogInterface;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.GpsStatus;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterWriter;
import java.io.IOException;
public class MainBina extends AppCompatActivity {
TextView texto;
Button boton ,boton2, boton3, boton4;
MediaPlayer Play;
MediaRecorder Record;
String grabacion;
String filePath;
String grabarState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_bina);
filePath = Environment.getExternalStorageDirectory()+ "/audiorecordtest.3gp";
texto = (TextView) findViewById(R.id.textView);
//boton.setText("Grabar");
boton = (Button) findViewById(R.id.button);
boton2 = (Button) findViewById(R.id.button2);
boton3 = (Button) findViewById(R.id.button3);
texto.setText(boton.getText().toString());
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch ( boton.getText().toString())
{
case "grabar":
try {
startRecord();
} catch (Exception e) {
e.printStackTrace();
}
boton.setText("grabando");
break;
case "grabando":
try {
stopRecord();
} catch (Exception e) {
e.printStackTrace();
}
boton.setText("Grabar");
break;
}
}
});
boton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlay();
}
});
boton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startPlay();
} catch (Exception e) {
e.printStackTrace();
}
}
});}
public void startRecord ()throws Exception{
if (Record!=null)
{
Record.release();
}
File fileOut = new File(filePath);
if (fileOut!=null)
{
fileOut.delete();
}
String fileName = "bina1.3gpp";
FileOutputStream fileOutputStream = openFileOutput(fileName, MODE_PRIVATE);
String filePathh = fileOutputStream.toString();
texto.setText(filePath);
Record = new MediaRecorder();
Record.setAudioSource(MediaRecorder.AudioSource.MIC);
Record.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
Record.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
Record.setOutputFile(filePath);
fileOutputStream.close();
Record.prepare();
Record.start();
}
public void stopRecord () {
Record.stop();
Record.reset();
Record.release();
Record = null;
}
public void startPlay ()throws Exception {
Play = new MediaPlayer();
Play.setDataSource(filePath);
Play.prepare();
Play.start();
Play.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer Play) {
Play.release();
}
});
}
public void stopPlay ()
{
if (Play != null) {
Play.stop();
Play.release();
Play = null;
}
}
#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_main_bina, 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);
}
}
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainBina"
android:id="#+id/linear"
android:orientation="vertical">
<TextView android:text="#string/saludo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Grabar"
android:id="#+id/button"
android:layout_marginTop="35dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Reproducir"
android:id="#+id/button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Parar"
android:id="#+id/button3" />
</LinearLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sebastin.myapplication" >
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.write_external_storage" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainBina"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Are you sure it started correctly? Take a look at your logcat for other errors/exceptions.
Your permission for writing to external storage looks wrong, it should be (with the last part capitalized):
android.permission.WRITE_EXTERNAL_STORAGE

Bluetooth Sending and Receiving Text Data

I'm new to Android developing and I would like to make an app that sends and receive text using bluetooth. I got everything regarding the sending text logically working, but when I try to test it in my phone, I can't see the interface.
Here's the Main Activity Code
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set; import java.util.UUID;
public class MainActivity extends ActionBarActivity {
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
EditText myTextbox;
TextView myLabel;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Button sendButton = (Button) findViewById(R.id.send);
Button openButton = (Button) findViewById(R.id.open);
myTextbox = (EditText) findViewById(R.id.editText);
myLabel = (TextView) findViewById(R.id.textView);
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// This will find a bluetooth device
void findBT() {
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// Salaxy S4 is the name of the bluetooth device
if (device.getName().equals("Galaxy S4")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Tries to open a connection to the bluetooth device
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// After opening a connection to bluetooth device,
// we have to listen and check if a data were sent to be printed.
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here's my Fragment_main
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res/com.example.bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="top"
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.example.bt.MainActivity$PlaceholderFragment" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Text Here" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/send"
android:layout_alignBottom="#+id/send"
android:layout_alignRight="#+id/linearLayout1"
android:text="Open" />
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_marginTop="15dp"
android:layout_toLeftOf="#+id/button1"
android:text="Send" />
<TextView
android:id="#+id/recievedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/send"
android:layout_below="#+id/send"
android:layout_marginTop="20dp"
android:text="Received Text" />
<TextView
android:id="#+id/rtArea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/recievedText"
android:layout_alignParentBottom="true"
android:layout_below="#+id/recievedText"
android:layout_marginTop="20dp"
android:text="Received Text Will be Displayed Here..." />
</RelativeLayout>
my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bt"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<supports-screens android:anyDensity="true" />
<uses-permission android:name="android.permissions.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.bt.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
So I would like to know:
Why can't I see the interface and test my code?
How can I receive text inside the app itself?
Appreciate all your help guys.
One step at a time.
setContentView(R.layout.activity_main);
will set the content of the view and i am assuming its defined in your Fragment_main should be fragment_main as its a XML file. So if you change it to
setContentView(R.layout. fragment_main);
you should be able to see the user Interface.

Categories