I would like to save/create a file in the directory of my Emulator but i cant do that and i dont understand what is wrong with my code. So everytime i try to run the code it says that android cant create the file in such directory.
Can someone please explain to me how i make it. Here is the code of my Application:
public class MainActivity extends AppCompatActivity {
private int STORAGE_PERMISSION_CODE = 1;
private File csvFile;
SimpleDateFormat TIME;
private static final String CSV_DIRECTORY = "NameOfTheDirectory";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if((ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)){
Toast.makeText(MainActivity.this, "You have already granted this permission",
Toast.LENGTH_SHORT).show();
}else {
requestStoragePermission();
}
}
public void makeFile(View view) {
File csvDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY);
if(!csvDirectory.exists()) {
try{
csvDirectory.mkdir();
Log.d("StateMakeFile","Directory created");
} catch(Exception e) {
e.printStackTrace();
Log.d("StateMakeFile","Directory not created");
}
}
File categoryDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY + File.separator + "NameOfTheCategory");
if(!categoryDirectory.exists()){
try{
categoryDirectory.mkdir();
Log.d("StateMakeFile","CategoryDirectory created");
}catch (Exception e){
e.printStackTrace();
Log.d("StateMakeFile","CategoryDirectory not created");
}
}
TIME = new SimpleDateFormat("yyyyMMdd-hh:mm:ss:SSS", Locale.getDefault());
String uniqueFileName = TIME.format(new Date());
csvFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY + File.separator + "NameOfTheCategory" +
File.separator + uniqueFileName + ".csv");
if(!csvFile.exists()){
try{
csvFile.createNewFile();
Log.d("StateMakeFile","File created");
}catch (IOException e){
e.printStackTrace();
Log.d("StateMakeFile","File not created");
}
if(csvFile.exists()) {
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(csvFile, true)));
out.write("Something" + "\n");
out.flush();
out.close();
Log.d("StateMakeFile","File was writed with success");
}catch (IOException e){
e.printStackTrace();
Log.d("StateMakeFile","File wasnt writed with success");
}
}
}
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed to save and load files into ssd")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
}
I don‘t know if it is in your manifest, but your are working here with
READ_EXTERNAL_STORAGE
Try it with the permission
WRITE_EXTERNAL_STORAGE
Hope this helps you
Related
I have an app that allows you to pick an audio file and then load / playback etc.
For some reason certain files do not load, even though they are selectable, and are not unusual file types, for example, I am currently trying an MP3 audio file (6.5mb).
This is the process once selected;
// load audio to SoundController
public void initSound(String audioPath) {
File audioFile = new File(audioPath);
if (audioFile.exists()) {
String s = audioFile.getName();
mFileName = s.substring(0, s.length() - 4);
showProcessDialog();
try {
mSoundController.loadAudio(audioFile.getAbsolutePath());
mSoundController.loadVisualizer(visualizerView, false);
mSoundController.loadVisualizer(visualizerReverseView, true);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot load audio file", Toast.LENGTH_SHORT).show();
closeProcessDiaglog();
}
} else {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
}
}
The showProcessDialog;
void showProcessDialog() {
isLoadedAudio = false;
prcDialog = new ProgressDialog(this);
prcDialog.setMessage("Please Wait - Loading Audio - if this dialogue appears for more than 15 seconds, your file is not compatible so please try loading a different audio file.");
prcDialog.setCancelable(true);
prcDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel & Try A Different Audio File",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
} );
prcDialog.show();
}
// Close Process dialog
void closeProcessDiaglog() {
if (prcDialog.isShowing()) {
prcDialog.dismiss();
}
checkAudioLoaded();
}
public void checkAudioLoaded() {
sbSongProcess.setEnabled(mSoundController.isPlaying());
if (mSoundController.isLoadedAudio()) {
playAudio.setEnabled(true);
playAudio.setChecked(mSoundController.isPlaying());
} else {
playAudio.setEnabled(false);
playAudio.setChecked(false);
}
}
Of course also onActivityResult;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AppicationContants.OPEN_FILE_REQUEST && resultCode == RESULT_OK) {
mPath = data.getStringExtra("Path");
isLoadingFile = true;
}
}
This particular mp3 file, the dialogue shows, however does not ever dismiss and the file does not load, but other files will fire the 'File not found' Toast message found in my initSound method.
I am struggling to understand why, these are audio files that are downloaded onto my device.
The ManagerAudioActivity.java file handles the choosing of the file / opening.
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AppicationContants.AUDIO_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
try {
Uri uri = data.getData();
String arr1 = uri.toString().substring(0, uri.toString().lastIndexOf("/"));
String id = DocumentsContract.getDocumentId(uri);
String path = FilePath.getPath(this, uri);
File t = null;
// Alternatively, use FileUtils.getFile(Context, Uri)
if (path != null && FileUtils.isLocal(path)) {
t = new File(path);
}
mPath = path;
Toast.makeText(getApplicationContext(), mPath, Toast.LENGTH_LONG).show();
if(checkIfAudio(mPath)) {
if(t.exists()) {
String description = "Tempo:100 Pitch:+0 Key:+0";
Song newSong = new Song(t.getName().substring(0, t.getName().length() -4), description, t.getAbsolutePath());
if(!checkIfExisted(newSong.getName())) {
currentCategory.getSongs().add(newSong);
}
SongAdapter songAdapter = new SongAdapter(ManagerAudioActivity.this, currentCategory.getSongs());
lvListSong.setAdapter(songAdapter);
((CustomAdapter) lvListCategory.getAdapter()).updateItemList(categories);
saveData();
} else {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "File in wrong format", Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
}
}
}
public boolean checkIfAudio(String path)
{
boolean result = false;
try {
SoundStreamAudioPlayer audioPlayer = new SoundStreamAudioPlayer(10, path, 1.0f, 0.0f);
result = true;
audioPlayer = null;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error="+e.getMessage(), Toast.LENGTH_SHORT).show();
}
return result;
}
public boolean checkIfExisted(String name)
{
if(currentCategory!= null && currentCategory.getSongs().size()>0)
{
for(int i =0 ; i< currentCategory.getSongs().size() ; i++)
{
if(currentCategory.getSongs().get(i).getName().equals(name))
{
return true;
}
}
}
return false;
}
When I open the activity, I request for the directory permission. Once the permission is allowed, I write the name and content of the file and then I press the save button. There is a confirmation dialog before saving the file. I choose YES there and then the following error appears.
2019-07-17 04:29:31.063 17879-17879/com.halimlab.catatanharian E/WindowManager: android.view.WindowLeaked: Activity com.halimlab.catatanharian.InsertAndViewActivity has leaked window DecorView#56fdc15[InsertAndViewActivity] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:538)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:329)
at androidx.appcompat.app.AlertDialog$Builder.show(AlertDialog.java:1007)
at com.halimlab.catatanharian.InsertAndViewActivity.konfirmasiSave(InsertAndViewActivity.java:191)
at com.halimlab.catatanharian.InsertAndViewActivity.onBackPressed(InsertAndViewActivity.java:197)
at com.halimlab.catatanharian.InsertAndViewActivity.buatDanUbah(InsertAndViewActivity.java:177)
at com.halimlab.catatanharian.InsertAndViewActivity$1.onClick(InsertAndViewActivity.java:188)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6739)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:859)
Here is my code.
public class InsertAndViewActivity extends AppCompatActivity implements View.OnClickListener {
public static final int REQUEST_CODE_STORAGE = 100;
int eventID = 0;
EditText edtFileName, edtContent;
Button btnSimpan;
boolean isEditable = false;
String fileName = "";
String tempCatatan = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_and_view);
// button back
ActionBar menu = getSupportActionBar();
menu.setDisplayShowHomeEnabled(true);
menu.setDisplayHomeAsUpEnabled(true);
// input
edtFileName = findViewById(R.id.editFilename);
edtContent = findViewById(R.id.editContent);
// button
btnSimpan = findViewById(R.id.btnSimpan);
btnSimpan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
fileName = extras.getString("filename");
edtFileName.setText(fileName);
getSupportActionBar().setTitle("Ubah Catatan");
} else {
getSupportActionBar().setTitle("Tambah Catatan");
}
eventID = 1;
if (Build.VERSION.SDK_INT >= 23) {
if (periksaIzin()) {
bacaFile();
}
} else {
bacaFile();
}
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSimpan :
eventID = 2;
if (!tempCatatan.equals(edtContent.getText().toString())) {
if (Build.VERSION.SDK_INT >= 23) {
konfirmasiSave();
}
} else {
konfirmasiSave();
}
break;
}
}
public boolean periksaIzin() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == getPackageManager().PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE);
return false;
}
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_STORAGE :
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (eventID == 1) {
bacaFile();
} else {
konfirmasiSave();
}
}
break;
}
}
void bacaFile() {
String path = Environment.getExternalStorageDirectory().toString() + "/halimlab.catatan";
File file = new File(path, edtFileName.getText().toString());
if (file.exists()) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while (line != null) {
text.append(line);
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("ERROR" + e.getMessage());
}
tempCatatan = text.toString();
edtContent.setText(text.toString());
}
}
void buatDanUbah() {
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
return;
}
String path = Environment.getExternalStorageDirectory().toString() + "/halimlab.catatan";
File parent = new File(path);
if (parent.exists()) {
File file = new File(path, edtFileName.getText().toString());
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file);
OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream);
streamWriter.append(edtContent.getText());
streamWriter.flush();
streamWriter.close();
streamWriter.flush();
streamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
parent.mkdir();
File file = new File(path, edtFileName.getText().toString());
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file, false);
outputStream.write(edtContent.getText().toString().getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
onBackPressed();
}
void konfirmasiSave () {
new AlertDialog.Builder(this)
.setTitle("Simpan Catatan")
.setMessage("Apakah anda akan menyimpan catatan ini ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
buatDanUbah();
}
})
.setNegativeButton(android.R.string.no, null).show();
}
#Override
public void onBackPressed() {
if (!tempCatatan.equals(edtContent.getText().toString())) {
konfirmasiSave();
}
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
I have the necessary permissions in my AndroidManifest.xml.
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/>
You need to modify the onBackPressed function like the following.
#Override
public void onBackPressed() {
if (!tempCatatan.equals(edtContent.getText().toString()))
konfirmasiSave();
else super.onBackPressed(); // Do that in the else part.
}
Because in the konfirmasiSave function you are opening a dialog which is not being closed or any action is being taken upon it and hence you are calling the super.onBackPressed which is trying to return back to the previous activity and hence causing the window leak error.
And handle the value of the tempCatatan variable before exiting so that your onBackPressed function performs as expected.
First, Thank you very much for looking at this!
I've been handed an app someone wrote before Marshmallow. I've fixed the Theme and SSL issues that came with Nougat but I'm having a heck of a time with Write to External Storage Permission or something associated. Debug is lacking or I'm not using it properly. This app creates a file onto the device and adds the ssl cert and login info in a folder called My Documents.
When I open the app it say network timeout right away. That message is from LoginActivity.java . I click ok then I get the Android pop up asking to allow permissions. I allow it. After that I put in the username and password and click login. It instantly gives the network timeout message from LoginActivity.java. LoginActivity.java is the Main Activity. If I click ok it's back to the login screen. All permissions are in the Android Manifest as well.
Maybe it's not from permissions but it works fine in version 22. I've worked on this 12 hours today and thought if you guys could help that'd be great. I'm a network engineer dabbling in Java so please excuse my question if it's "ugly".
I tried to find a line by line debug like I've done with phonegap but wasn't successful.
My Apps Main Activity LoginActivity.java and associated activity is LoginScreen.java and shown below.
LoginActivity.java
public class LoginActivity extends Activity {
private String userName = "";
private static final int PERMS_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blackactivity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
new SSLHandler().execute();
if(Variables.testing)
{
}
if (hasPermissions()){
// our app has permissions.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
//our app doesn't have permissions, So i m requesting permissions.
requestPerms();
}
}
//Begin Permission Methods
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
//End Permission Methods
private void attemptLogin() throws IOException {
String filepath = Variables.fileFolder + "/login.txt";
File tempFile = new File(filepath);
if (!tempFile.exists()) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
BufferedReader reader = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
} catch (Exception e) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
fileExists = true;
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean success = false;
Boolean timedOut = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
AlertDialog.Builder builder = new AlertDialog.Builder(
LoginActivity.this);
builder.setMessage("Network Timed Out").setTitle("Notice");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
if (result) {
Variables.storeTechName(userName, LoginActivity.this);
Variables.assignTechName();
startActivity(new Intent(LoginActivity.this,
MainActivity.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginActivity.this,
"Loading...", "Logging you in...");
mProgressDialog.getWindow().setGravity(Gravity.BOTTOM);
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
System.out.println(e.toString());
timedOut = true;
}
return success;
}
}
#Override
protected void onPause() {
super.onPause();
}
}
LoginScreen.java
public class LoginScreen extends Activity {
private String userName;
private static final int PERMS_REQUEST_CODE = 123;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (!SSLHandler.loaded) {
new SSLHandler().execute();
}
// Creates login and name files and attempts to log in
Button createButton = (Button) findViewById(R.id.createbutton);
createButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((EditText) findViewById(R.id.usernamefield)).getText()
.toString().isEmpty()
|| ((EditText) findViewById(R.id.passwordfield))
.getText().toString().isEmpty()) {
GUI.oneOptionDialog(LoginScreen.this,
"Missing field entries", "OK", false);
} else {
createLoginFile();
((EditText) findViewById(R.id.usernamefield)).setText("");
((EditText) findViewById(R.id.passwordfield)).setText("");
attemptLogin();
}
}
});
}
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
createFiles();
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
private void createFiles() {
}
private void attemptLogin() {
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
try {
String filepath = Variables.fileFolder + "/login.txt";
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
fileExists = true;
}
catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this,
"Login file does not exist. Please enter login info.",
"OK", false);
}
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean timedOut = false;
Boolean success = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
GUI.oneOptionDialog(LoginScreen.this, "Network Timed Out",
"OK", false);
} else {
if (result) {
Variables.storeTechName(userName, LoginScreen.this);
Variables.assignTechName();
startActivity(new Intent(LoginScreen.this,
MainActivity.class));
finish();
} else {
GUI.oneOptionDialog(LoginScreen.this,
"Login Failed. Please try again.", "OK", false);
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginScreen.this,
"Loading...", "Logging you in...");
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
jc.setConnectTimeout(Variables.timeoutTimeLimit);
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
timedOut = true;
}
return success;
}
}
private void createLoginFile() {
try {
File dir = new File(Variables.fileFolder);
if (!dir.isDirectory()) {
dir.mkdirs();
}
String filepath = Variables.fileFolder + "/Login.txt";
String username = ((EditText) findViewById(R.id.usernamefield))
.getText().toString();
String password = ((EditText) findViewById(R.id.passwordfield))
.getText().toString();
String salt = new RandomString(20).nextString();
String passwordHash = Variables.sha256(password + salt);
PrintWriter writer = new PrintWriter(filepath, "UTF-8");
writer.println(username);
writer.println(passwordHash);
writer.println(salt);
writer.close();
} catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this, e.toString(), "OK", false);
}
}
#Override
protected void onPause() {
super.onPause();
}
}
I'm having trouble connecting my smartphone to my EV3 over bluetooth using an app.
My situation:
I'm developing an App to send simple Strings to the EV3 which runs with leJOS 0.9.1-aplu11.
My Problem is, I'm not really familiar with Bluetooth, so my app or my receiver-software doesn't work as well.
My goal:
My goal is to create a Listener on the EV3 which is permanant listening for Strings from the app and an App that sends the strings when I press a button.
I hope you can help me.
I'm from germany so don't wonder about my beautifull writing skills!
Here is my Code:
App:
public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
private BluetoothAdapter mBluetoothAdapter;
private static BluetoothDevice mDevice;
private Button mSendBN;
private final static String MY_UUID = "00001101-0000-1000-8000-00805f9b34fb";
private static BluetoothSocket mSocket = null;
private static String mMessage = "Stop";
private static PrintStream sender;
private void findBrick() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("EV3"))
this.mDevice = device;
}
}
private void initBluetooth() {
Log.d(TAG, "Checking Bluetooth...");
if (mBluetoothAdapter == null) {
Log.d(TAG, "Device does not support Bluetooth");
mSendBN.setClickable(false);
} else {
Log.d(TAG, "Bluetooth supported");
}
if (!mBluetoothAdapter.isEnabled()) {
mSendBN.setClickable(false);
Log.d(TAG, "Bluetooth not enabled");
} else {
Log.d(TAG, "Bluetooth enabled");
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "SpeechRecognizer gestartet", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main);
mSendBN = (Button) findViewById(R.id.button);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
initBluetooth();
findBrick();
if (mDevice == null) {
mSendBN.setClickable(false);
Toast.makeText(this, "No Devices found or BT disabled", Toast.LENGTH_SHORT).show();
Log.d("onC", "Connected to " + mDevice);
}
try {
createSocket();
} catch (IOException e) {
e.printStackTrace();
}
startService();
}
private void startService() {
if (PermissionHandler.checkPermission(this, PermissionHandler.RECORD_AUDIO)) {
Intent i = new Intent(this, BackgroundRecognizerService.class);
startService(i);
}
}
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PermissionHandler.RECORD_AUDIO && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startService();
}
}
}
public static void onSend(View view) throws IOException {
try {
OutputStream os = mSocket.getOutputStream();
sender = new PrintStream(os);
Log.d("onSend", "Message = " + mMessage);
sender.println(mMessage);
sender.flush();
Log.d("onSend", "Message sent");
mSocket.close();
Log.d("onSend", "Socket closed");
} catch (IllegalStateException | NullPointerException e) {
e.printStackTrace();
}
}
public void createSocket() throws IOException {
try {
UUID uuid = UUID.fromString(MY_UUID);
mSocket = mDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("createSocket", "Adapter");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mSocket.connect();
OutputStream os = mSocket.getOutputStream();
sender = new PrintStream(os);
Log.d("createSocket", "Fertig, " + "Socket: " + mSocket + " Sender: " + sender + " OutputStream: " + os + " mDevice: " + mDevice.getName());
}
protected void onDestroy() {
super.onDestroy();
Log.d("onDestroy", "App beendet");
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("onDestroy", "App vollständig beendet");
}
}
EV3:
public class BTJ {
public static void main(String[] args) {
BTConnector connector = new BTConnector();
System.out.println("0. Auf Signal warten");
NXTConnection conn = connector.waitForConnection(0, NXTConnection.RAW);
InputStream is = conn.openInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String message = "";
while (true){
System.out.println("1. Schleife gestartet");
message = "";
try {
message = br.readLine();
System.out.println("2. Message: " + message);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
}
}
I have the answer..!
public class BTJ {
public static void main(String[] args) {
BTConnector connector = new BTConnector();
System.out.println("0. Auf Signal warten");
NXTConnection conn = connector.waitForConnection(0, NXTConnection.RAW);
InputStream is = conn.openInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is), 1);
String message = "";
while (true){
System.out.println("1. Schleife gestartet");
message = "";
try {
message = br.readLine();
System.out.println("2. Message: " + message);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
}
I have the following code:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/tc/strip.tcl");
try {
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
else {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in try", Toast.LENGTH_SHORT).show();
}
finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}
else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
What I am looking to do is:
When the button is clicked:
1) Check to make the data is not null or empty (Working fine):
if (showLog != null && showLog.getText().toString().length() > 0) {
2) Check to make sure the folder exists, if not create the folder (Working fine):
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
3) Before writing the data to the file, ensure it doesn't already exist. If it does exist, prompt the user to see if it can be overwritten. If the user chooses YES then overwrite the file but if the user chooses NO then add a "1" at the end of the filename and save it. (NOT WORKING and need help)
I am getting an error for the following line:
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Error:
Unhandled exception type FileNotFoundException
--> (Surround with try/catch)
1)
File tcDir = new File(Environment.getExternalStorageDirectory(),"tc");
tcDir.mkdirs();
File file = new File(tcdir, "strip.tcl");
The first line creates a file object called tc in the external storage directoy. The second line creates it on disk, with any missing parents. The third line creates a file object inside that directory
2)You seem to be doing that- you create a file output stream and write to it like you're doing.
3)Before writing the file, cal file.exists(). If it exists, you need to pop up a AlertDialog. If they hit the yes button of the dialog you write a file. If they choose the no button, you do nothing. It would be best to put all of the writing code into a separate function so it can be called in both the dialog click code and in the !exists code here.
In answer to part 3), I've edited your code to work properly for you. Most of the code you had was correctly written there was just a couple of issues. I also moved the code to write a new file into a new method writeFile() in order to avoid replicating code and to make it easier to keep track of what's going on:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/TollCulator");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/TollCulator/strip.tcl");
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the existing file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeFile(file);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
} else {
writeFile(file);
}
} else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
// ...
private void writeFile(File file){
try {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}