I'm trying to generate a code as string in my android application and save it to a text file. When you press a Share button, the code should be read from the text file and be copied to the clipboard.
I guess I'm not understanding something about acivity/context. Of course I read in the documentation about it, but I can't figure out the problem. Hope you guys could help me!
FileSystem.java
package com.niclasjaksch.shoppinglist;
import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class FileSystem extends AppCompatActivity {
static String filename = "shoppinglist_code.txt";
void Create() {
try {
FileOutputStream fOut = openFileOutput(filename, Context.MODE_PRIVATE);
String str = Utility.randomString(10);
fOut.write(str.getBytes());
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String Read() {
String result = "";
try {
FileInputStream fin = openFileInput(filename);
int c;
while( (c = fin.read()) != -1){
result += c;
}
fin.close();
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return result;
}
void Clear() {
try {
File dir = getFilesDir();
File file = new File(dir, filename);
file.delete();
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Share.java
package com.niclasjaksch.shoppinglist;
import android.content.ClipData;
import androidx.appcompat.app.AppCompatActivity;
class Share extends AppCompatActivity {
android.content.ClipboardManager clipboardManager = null;
FileSystem fs = new FileSystem();
void Share() {
String code = fs.Read();
if(code == "" || code == null) {
fs.Create();
code = fs.Read();
}
ClipData clipData = ClipData.newPlainText("Source Text", code);
clipboardManager.setPrimaryClip(clipData);
}
}
MainActivity.java
...
Share share = new Share();
...
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.item_share:
share.Share();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Getting a NullPointerException in this line:
FileOutputStream fOut = openFileOutput(filename, Context.MODE_PRIVATE);