I want to save a string from a TextArea to the device and then reload it after reopening the app. I have tried following the examples (link) but cant get it to work. Main problem arises when i try to read the file and use a StringInputConverter.
private void saveAndLoad(TextArea textArea){
File textFile = new File(ROOT_DIR,"text_file");
String text2 = textArea.getText();
String loadedFile = "none";
if (textFile.exists()){
FileClient fileClient = FileClient.create(textFile);
loadedFile = DataProvider.retrieveObject(fileClient.createObjectDataReader(
new StringInputConverter()));
}
try(FileWriter writer = new FileWriter(textFile)){
writer.write(textArea.getText());
} catch (IOException e) {
e.printStackTrace();
}
textArea.setText(text2);
}
Edit: inserted code which i tried to start reading file with and image of the error i am getting
If you check the DataProvider::retrieveObject documentation:
Retrieves an object using the specified ObjectDataReader. A GluonObservableObject is returned, that will contain the object when the read operation completed successfully.
It returns GluonObservableObject<String>, which is an observable wrapper of the string, not the string itself.
You need to get first the observable, and when the operation ends successfully you can retrieve the string:
if (textFile.exists()) {
FileClient fileClient = FileClient.create(textFile);
GluonObservableObject<String> retrieveObject = DataProvider
.retrieveObject(fileClient.createObjectDataReader(new StringInputConverter()));
retrieveObject.stateProperty().addListener((obs, ov, nv) -> {
if (ConnectState.SUCCEEDED.equals(nv)) {
loadedFile = retrieveObject.get();
}
});
}
This is a quick implementation of this functionality:
public class BasicView extends View {
private static final File ROOT_DIR;
static {
ROOT_DIR = Services.get(StorageService.class)
.flatMap(StorageService::getPrivateStorage)
.orElseThrow(() -> new RuntimeException("Error"));
}
private final File textFile;
private final TextField textField;
private String loadedFile = "none";
public BasicView(String name) {
super(name);
textFile = new File(ROOT_DIR, "text_file");
textField = new TextField();
VBox controls = new VBox(15.0, textField);
controls.setAlignment(Pos.CENTER);
controls.setPadding(new Insets(30));
setCenter(controls);
}
#Override
protected void updateAppBar(AppBar appBar) {
appBar.setNavIcon(MaterialDesignIcon.MENU.button(e -> System.out.println("Menu")));
appBar.setTitleText("Basic View");
appBar.getActionItems().add(MaterialDesignIcon.SAVE.button(e -> save()));
appBar.getActionItems().add(MaterialDesignIcon.RESTORE_PAGE.button(e -> restore()));
}
private void save() {
try (FileWriter writer = new FileWriter(textFile)) {
writer.write(textField.getText());
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void restore() {
if (textFile.exists()) {
FileClient fileClient = FileClient.create(textFile);
GluonObservableObject<String> retrieveObject = DataProvider
.retrieveObject(fileClient.createObjectDataReader(new StringInputConverter()));
retrieveObject.stateProperty().addListener((obs, ov, nv) -> {
if (ConnectState.SUCCEEDED.equals(nv)) {
loadedFile = retrieveObject.get();
textField.setText(loadedFile);
}
});
}
}
}
Related
I am trying to get my Xamarin Forms App to read the appsettings.json config file for setting up RestSharp. I am targeting Android. The appsettings.json file is set to Copy Always in the root of my Android forms project in Visual Studio. I am trying to read in a Factory pattern.
internal class ConfigFactory
{
public ConfigFactory()
{
try
{
SetupSimpleConfiguration();
ReadSimpleConfiguration();
}
catch (Exception e)
{
Log.Logger.Error(e, "Exception Constructing Config Factory");
throw;
}
}
public RestClient QueryClient { get; private set; }
public RestClient CommandClient { get; private set; }
private IConfigurationRoot Config { get; set; }
private void ReadSimpleConfiguration()
{
string val1 = Config["QueryURL"];
string val2 = Config["CommandURL"];
QueryClient = new RestClient(val1);
CommandClient = new RestClient(val2);
}
private void SetupSimpleConfiguration()
{
var currentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
Log.Logger.Debug("Enter Simple {#Directory}", currentDirectory);
Config = new ConfigurationBuilder()
.SetBasePath(currentDirectory)
.AddJsonFile("appsettings.json")
.Build();
Log.Logger.Debug("Leave Simple {#Config}", Config);
}
}
The Exception I keep running into is:
The configuration file 'appsettings.json' was not found and is not
optional. The physical path is
'/data/user/0/com.companyname.SerilogSample/files/appsettings.json'
No matter what I set currentDirectory to.
I am busy with trying to get an array which i get from MSSQL to display in a table view form in my application. I have tried to google it but i cant seem to find an example of this. I have tried it but i am running into one small error.
I get the following error Cannot resolve constructor:Simpletabledata adapter[package.mainactivity, package.itemarray]
Here is my mainactivy.java class:
public class MainActivity extends AppCompatActivity {
static String[] spaceProbeHeaders={"Name"};
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
final TableView<String[]> tableView = (TableView<String[]>) findViewById(R.id.tableView);
private boolean success = false; // boolean
Connection conn; // Connection Class Initialization
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableView.setHeaderBackgroundColor(Color.parseColor("#777777"));
tableView.setHeaderAdapter(new SimpleTableHeaderAdapter(this,spaceProbeHeaders));
tableView.setColumnCount(4);
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String>
{
String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(MainActivity.this, "Synchronising",
"Tableview Loading! Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try
{
ConnectionClass conStr=new ConnectionClass();
conn =conStr.connectionclass();
//Connection Object
if (conn == null)
{
success = false;
}
else {
// Change below query according to your own database.
String query = "SELECT customer_first_name FROM cc_customer";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next())
{
try {
itemArrayList.add(new ClassListItems(rs.getString("customer_first_name")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(MainActivity.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false)
{
}
else {
try {
//myAppAdapter = new MyAppAdapter(itemArrayList, MainActivity.this);
tableView.setDataAdapter(new SimpleTableDataAdapter(MainActivity.this,itemArrayList ));
} catch (Exception ex)
{
}
}
}
}
and here is my classlist.java file:
public class ClassListItems
{
public String name; //Name
public ClassListItems(String name)
{
this.name = name;
}
public String getName() {
return name;
}
Update
N.B: OP is using SortableTableView Library.
You need to import the following to solve Cannot resolve constructor:SimpleTableDataAdapter-
import de.codecrafters.tableview.toolkit.SimpleTableDataAdapter;
Original
Do you have SimpleTableDataAdapter class in your project? It seems it can't find the class so it is not in the same package. If it is in different package, you need to import it.
And on a different note, your .java file names should match the class name
And on another different note, have you tested that itemArrayList is actually populating? For Android-MSSQL, here is a tutorial pointer -
https://parallelcodes.com/connect-android-to-ms-sql-database-2/
There are many tutorials if you google it.
Situation: I have an android application. In this android application I have an internal file containing a "User" class (see code below) this user class has an array-list comprised of spendings, of the "Spending" class, comprised of several different basic attributes.
Problem: When I get this user from the internal file, add a "Spending" Object to the array-list of the User, then re-save this user (delete file and recreate) it doubles in size the Spendings array-list.
I even observed it by looking at the files themselves and can see clearly that the entire array-list is doubled every time a spending is added. the user does not seem to be duplicated.
I tried the same process only without adding the spending and it saves just fine without duplication.
the User class:
public class User implements Serializable {
private int id_utilisateur;
private String mail;
private String motDePasse;
private ArrayList<Spending> mySpendings;
public Utilisateur(int id_utilisateur, String mail, String motDePasse) {
this.id_utilisateur = id_utilisateur;
this.mail = mail;
this.motDePasse = motDePasse;
this.mySpendings= new ArrayList<>();
}
//Getters and Setters of all attributes here//
public void addSpending(Spending mySpending) {
mySpendings.add(mySpending);
}
}
My Spending class :
public class Spendingimplements Serializable {
private Integer idSpending;
private Date dateSpending;
private double montant;
private String pieceJoint;
private Magasin magasin;
private String domaine;
private Date garantieDebut;
private Date garantieFin;
private User user;
public Spending(Integer idSpending, Date dateSpending, double montant, User user, String domaine, Magasin magasin, String pieceJoint, Date garantieDebut, Date garantieFin) {
this.idSpending= idSpending;
this.dateSpending= dateSpending;
this.montant = montant;
this.user= user;
this.domaine = domaine;
this.magasin = magasin;
this.pieceJoint = pieceJoint;
this.garantieDebut = garantieDebut;
this.garantieFin = garantieFin;
}
public Spending(Integer idSpending, Date dateSpending, double montant, User user, String domaine, Magasin magasin, String pieceJoint) {
this.idSpending= idSpending;
this.dateSpending= dateSpending;
this.montant = montant;
this.user= user;
this.domaine = domaine;
this.magasin = magasin;
this.pieceJoint = pieceJoint;
this.garantieDebut = null;
this.garantieFin = null;
}
//geters and setters here//
}
My class StorageHelper:
public final class StorageHelper {
public StorageHelper() {}
public static void storeObject(Context context, Object object) {
try {
File dir = context.getFilesDir();
File file = new File(dir, "UserData.data");
file.delete();
FileOutputStream fos = context.openFileOutput("UserData.data", Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(object);
os.close();
fos.close();
} catch (Exception e) {
Log.e("userFile", "Error: Failed to save User into internal storage - \n" + e.toString());
}
}
public static User getUser(Context context) {
User mainUser = null;
try {
FileInputStream fis = context.openFileInput("UserData.data");
ObjectInputStream is = new ObjectInputStream(fis);
mainUser = (User) is.readObject();
is.close();
fis.close();
} catch (Exception e) {
Log.e("userFile", "Error: loading from the internal storage failed - \n" + e.toString());
} finally {
return mainUser;
}
}
}
MainActivity :
StorageHelper storageHelper;
User mainUser = storageHelper.getUser(this.getBaseContext());
mainUser.addSpending(mySpending);
storageHelper.storeObject(this.getBaseContext(), mainUser);
I am browsing an xml file from external usb storage (using otg cable, connected in the tablet/android phone) to be parsed.
Steps:
Browse for the file from external usb storage
Parse the xml file
Save the file in a text file
For the time being, I am now able to browse and parse the xml file then display the parsed file wherein it shows the needed information in a listview. Now, I want to save the displayed information as a text file and save it to the external sd card of the tablet. Here's the code:
Model.java :
public class Model {
String _model;
String _part;
String _sw;
String _desc;
// constructor
public Model() {
}
// constructor with parameters
public Model(String model, String part, String sw, String desc) {
this._model = model;
this._part = part;
this._sw = sw;
this._desc = desc;
}
// Set all methods
public void setModel(String model) {
this._model = model;
}
public void setPart(String part) {
this._part = part;
}
public void setSw(String sw) {
this._sw = sw;
}
public void setDesc(String desc) {
this._desc = desc;
}
// Get all methods
public String getModel() {
return this._model;
}
public String getPart() {
return this._part;
}
public String getSw() {
return this._sw;
}
public String getDesc() {
return this._desc;
}
//
#Override
public String toString() {
return "\n" + "Device" + "\n" + "\n"
+ "Model ID : " + _model + "\n"
+ "Part Number : " + _part + "\n"
+ "Software Version: " + _sw + "\n"
+ "Description : " + _desc ;
}
}
ModelParser.java :
public class ModelParser extends DefaultHandler{
static final String ERROR = "Errors";
static final String ID = "ID";
static final String PART = "PartNumber";
static final String SW = "SoftwareVersion";
static final String DESC = "Description";
private boolean done = false;
private String currentTag = null;
private Model current = null;
private ArrayList<Model> model = new ArrayList<Model>();
public ArrayList<Model> getItemsList() {
return model;
}
public ArrayList<Model> parse(Context context) {
try {
String file = ReadSystemActivity.getFilename();
file.toString();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
FileInputStream fis = new FileInputStream(file);
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT && !done) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
model = new ArrayList<Model>();
break;
case XmlPullParser.START_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR)) {
current = new Model();
}
else if (current != null) {
if (currentTag.equalsIgnoreCase(ID)) {
current.setModel(parser.nextText());
} else if (currentTag.equalsIgnoreCase(PART)) {
current.setPart(parser.nextText());
} else if (currentTag.equalsIgnoreCase(SW)) {
current.setSw(parser.nextText());
}else if (currentTag.equalsIgnoreCase(DESC)) {
current.setDesc(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR) && current != null) {
model.add(current);
} else if (currentTag.equalsIgnoreCase(ERROR)) {
done = true;
}
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return model;
}
}
And ReadActivity.java :
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
String modd = modId.getModel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
#Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
ModelParser parser = new ModelParser();
model = parser.parse(getBaseContext());
return model;
}
#Override
protected void onPostExecute(List<Model> models) {
ArrayAdapter<Model> adapter = new ArrayAdapter<Model>(getBaseContext(), android.R.layout.simple_list_item_1, models);
setListAdapter(adapter);
}
}
public boolean isSDCardWritable() {
String status = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(status))
{
return true;
}
return false;
} //isSDCardWritable
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Problem is, I want to save the Id but I am getting a null value in the SystemInfo.txt when I click the save button.
You're storing model inside another object and trying to retrieve it from a new object.
This is where you're storing your model object inside ModelParser
current = new GarminModel()
whereas you're trying to retrieve it from a new object inside ReadActivity
GarminModel modId = new GarminModel();
String modd = modId.getModel();
Get reference to your Model arraylist by calling ModelParser's getItemsList() inside ReadActivity and from it try to get your model objects
Check position of below two lines in the code below
ModelParser parser = new ModelParser();
ArrayList<Model> modelList = parser.getItemsList();
Model modd = modelList.get(0);
Note that you need to remove ModelParser parser = new ModelParser(); from LoadSystemTask
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
ModelParser parser = new ModelParser();
//-----------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
ArrayList<Model> modelList = parser.getItemsList();
//-----
Model modd = modelList.get(0);
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
#Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
model = parser.parse(getBaseContext());
return model;
}
I'm trying to make my program save it's current state on internal memory so i can retrieve it when it loads up next time.
But it seems like i can't get it to work, my app keeps crashing on boot.
private File statoContatori = new File(getFilesDir(), "statoContatori");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inizializeCounters();
}
private void inizializeCounters() {
Scanner in = null;
try {
in = new Scanner(statoContatori);
while (in.hasNext())
{
String idContatore = in.next();
String nomeContatore = in.next();
String valore = in.next();
if (idContatore.equals("contatore_1"))
{
initializeContatore(R.id.contatore_1_label, R.id.contatore_1, nomeContatore, valore);
}
else if (idContatore.equals("contatore_2"))
{
initializeContatore(R.id.contatore_2_label, R.id.contatore_2, nomeContatore, valore);
//There are a couple more IFs in here...
}
} catch (FileNotFoundException e) {
creaFileStatoContatori();
}
finally {
in.close();
}
}
private void creaFileStatoContatori() {
PrintWriter out = null;
try {
out = new PrintWriter(statoContatori);
out.println("contatore_1\tcontatore_1\t0");
out.println("contatore_2\tcontatore_2\t0");
out.println("contatore_3\tcontatore_3\t0");
out.println("contatore_4\tcontatore_4\t0");
out.println("contatore_5\tcontatore_5\t0");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
out.close();
}
inizializeCounters();
}
So basically what i'm trying to do is:
If the file is present -> load the file
If the file is not present -> create the file with standard configs -> load the file
What am i doing wrong?