Create views dynamically depending on data - java

I have a name, time and experience. I save them in one screen and want to load them on another. I think, creating a view for each would be a good solution. But i'm open to other suggestions. This is the code that I use to save the data.
//Sacando el texto de los editText y guardandolos en sus variables
d_TaskName = etxt_TaskName.getText().toString();
d_TaskTime = etxt_TaskTime.getText().toString();
d_TaskExp = etxt_TaskExp.getText().toString();
// Guardar nombre de la tarea en TaskName.txt
try {
FileOutputStream fou1 = openFileOutput("TaskName.txt", MODE_WORLD_WRITEABLE);
OutputStreamWriter osw1 = new OutputStreamWriter(fou1);
try {
osw1.write(d_TaskName);
osw1.flush();
osw1.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Guardar tiempo que dura la tarea en TaskTime.txt
try {
FileOutputStream fou2 = openFileOutput("TaskTime.txt", MODE_WORLD_WRITEABLE);
OutputStreamWriter osw2 = new OutputStreamWriter(fou2);
try {
osw2.write(d_TaskTime);
osw2.flush();
osw2.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Guardar la experiencia de la tarea en TaskExp.txt
try {
FileOutputStream fou3 = openFileOutput("TaskExp.txt", MODE_WORLD_WRITEABLE);
OutputStreamWriter osw3 = new OutputStreamWriter(fou3);
try {
osw3.write(d_TaskExp);
osw3.flush();
osw3.close();
Toast.makeText(getBaseContext(), "Tarea Guardada", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Why don't you use SharedPreferences?
For store your data:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("TaskName", etxt_TaskName.getText().toString());
editor.apply();
For load your data:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String taskName = sharedPref.getString("TaskName", "");

Related

Can I share a .csv file by whatsapp or email?

I have a problem. When I try share a .csv file generated by my application by whatsapp this app opens and closes immediately no consigo and I can't share the file.
The way to generate the file is as follows:
private void guardarFichero() {
//Date date=new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("ddMMhhmmss");
// Nombre del fichero
fileName="Inventario_"+ dateFormat.format(new Date())+".csv";
// obtenemos los datos a guardar
String inventario=textoEyoyo.getText().toString();
File file =new File (getExternalFilesDir(null),fileName);
try {
OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(file));
osw.write(inventario);
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
method share:
private void compartir(){
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Log.i("Mensaje", "nombre de la path: "+ path);
try {
File file =new File(getExternalFilesDir(null), fileName);
Uri uri = Uri.fromFile(file);
Log.i("Mensaje", "nombre de la URL: " + uri);
Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.setType("*/*");
share.putExtra(Intent.EXTRA_STREAM,uri);
//share.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivity(share);
} catch (Exception e) {
e.printStackTrace();
}
}

Call the saved text from any activitie

public void getData(View view) {
try {
FileInputStream fileInput = openFileInput("user_data.txt");
InputStreamReader reader = new InputStreamReader(fileInput);
BufferedReader buffer = new BufferedReader(reader);
StringBuffer strBuffer = new StringBuffer();
String lines;
while ((lines = buffer.readLine()) != null) {
strBuffer.append(lines); //Вывод имени
}
textView3.setText(strBuffer.toString());
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
public void saveData (View view) {
String user_name = editSave.getText().toString();
try {
FileOutputStream fileOutput = openFileOutput("user_data.txt", MODE_PRIVATE);
fileOutput.write((user_name).getBytes());
fileOutput.close();
textView3.setText(user_name);
Toast.makeText(setting.this, " ", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Hello. I'm just learning. I need user_name to be called from any activity so I can insert it into the code that passes the text, right now I can't do it.
I will now try to explain what I want to get: textView.setText("random text" + user_name + "text random")
I would be very grateful if you could edit my code.

Android SharedPreferences and Encrypted SharedPreferences

I have encrypted my preferences like this
public void setFile(){
String masterKeyAlias = null;
try {
masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
encryptedSharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
this,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and I'm setting and getting values like this
prefEditor.putString(SettingsActivity.KEY_NICKNAME,nickName.getText().toString()).apply();
nickname = encryptedSharedPreferences.getString(SettingsActivity.KEY_NICKNAME, "");
Everything is okay,but it doesn't set up values in preferences when I'm opening settings, because it uses standart SharedPreferences xml file.
So, the main question is : How to set up values from Encrypted SharedPreferences instead of sharedpreferences xml file ?

save server response in sqlite database(offline)

i call below php webservice and get xml response and parse resonse and set it to hashmap.now i want save server response in offline mode .can i save data in offline mode.how plz give me answer.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
if (response.length() > 0) {
int code = Integer.parseInt(XMLManualParser.getTagValue(Constant.TAG_CODE, response));
if (code == 1) {
spinner.clear();
ArrayList<String> eventlist = XMLManualParser.getMultipleTagList(Constant.TAG_LIST, response);
for (int i = 0; i < eventlist.size(); ++i) {
String responseContent = eventlist.get(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
String title = XMLManualParser.getTagValue(Constant.title, responseContent);
hashMap.put("title", title);
hashMap.put("id", XMLManualParser.getTagValue(Constant.id, responseContent));
hashMap.put("url", XMLManualParser.getTagValue(Constant.url, responseContent));
hashMap.put("balanceurl", XMLManualParser.getTagValue(Constant.balanceurl, responseContent));
spinner.add(hashMap);
}
} else {
Toast.makeText(SettingsEditActivity.this, "no data found", Toast.LENGTH_SHORT).show();
}
CustomSpinnerAdapter customSpinnerAdapter = new CustomSpinnerAdapter(SettingsEditActivity.this, spinner);
settingsBinding.splist.setAdapter(customSpinnerAdapter);
settingsBinding.splist.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(), "Android Custom Spinner Example Output..." + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can save your response into a file and get in offline
public static void saveDataSingleItemDetails(Context context,String file, MainListModel data) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = context.openFileOutput(file, MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
return;
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(data);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static MainListModel getSinglItemDetails(Context context,String file) {
MainListModel items = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = context.openFileInput(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return items;
} catch (NullPointerException e) {
return items;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
return items;
}
try {
items = (MainListModel) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return items;
}

IO exception is not handle

I have an issue in my Android app saying "Unhandled IOException: java.io.exception" when I'm trying to getBitmap from URI. below is the code.
I do not want to catch all exception using a catch (exception e) as it's too wide.
private void getBitmapFromURI(Uri uri) {
try {
mSnapShot = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
int PreviewSizeWidth = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewWidth);
int PreviewSizeHeight = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewHeight);
mPreviewBitmap = Bitmap.createScaledBitmap(mSnapShot, PreviewSizeWidth, PreviewSizeHeight, false);
FiltersPreview();
}
catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "File not found");
finish();
}
}
any idea how to catch exception in case getbitmap not working ?
thx
Try...
try {
mSnapShot = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
int PreviewSizeWidth = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewWidth);
int PreviewSizeHeight = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewHeight);
mPreviewBitmap = Bitmap.createScaledBitmap(mSnapShot, PreviewSizeWidth, PreviewSizeHeight, false);
FiltersPreview();
}
catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "File not found");
finish();
}catch(IOException e){
//do something
}
Use the multi catch and make sure to log your exception in logcat. Something like this.
catch (FileNotFoundException | IOException e) {
Log.e(TAG, e.getMessage(), e);
finish();
}
You should also catch the IOException
private void getBitmapFromURI(Uri uri) {
try {
mSnapShot = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
int PreviewSizeWidth = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewWidth);
int PreviewSizeHeight = CameraApplication.Instance().getResources().getInteger(R.integer.FilterPreviewHeight);
mPreviewBitmap = Bitmap.createScaledBitmap(mSnapShot, PreviewSizeWidth, PreviewSizeHeight, false);
FiltersPreview();
}
catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "File not found");
finish();
}
catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "IO error");
finish();
}
}
or you have to change you method signature to
private void getBitmapFromURI(Uri uri) throws IOException
and handle this on an other place.

Categories