I am using chat application. Upto Android 28sdk its worked fine but after i refract to androidx am facing this problem please check my code below and error screenshot.
Error Code Image 1
Error Code Image 2
private void compressAndUpload(final Context context, final String child, final File file) {
compressionTask = new AsyncTask<File, Void, String>() {
#Override
protected String doInBackground(File... files) {
String filePathCompressed = null;
Uri originalFileUri = Uri.fromFile(files[0]);
File tempFile = new File(context.getCacheDir(), originalFileUri.getLastPathSegment());
//tempFile = File.createTempFile(originalFileUri.getLastPathSegment(), null, context.getCacheDir());
if (child.equals("images")) {
filePathCompressed = SiliCompressor.with(context).compress(originalFileUri.toString(), tempFile);
} else {
try {
filePathCompressed = SiliCompressor.with(context).compressVideo(files[0].getPath(), context.getCacheDir().getPath());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
if (filePathCompressed == null)
filePathCompressed = "";
return filePathCompressed;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
File compressed = new File(s);
fileUri = Uri.fromFile(compressed.length() > 0 ? compressed : file);
FirebaseStorage storage = FirebaseStorage.getInstance();
if (uploadRef == null)
uploadRef = storage.getReference().child(child).child(fileUri.getLastPathSegment());
if (replace) {
upload();
} else {
checkIfExists();
}
}
};
compressionTask.execute(file);
}
Related
I have been compressing Images without any problems. Recently my app required video compress functionality to be added. Again, Silicompressor does the job but for some reason there is no audio in output file.
I am using code inside Runnable
private void compressVideo() {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
new CompressVideo().execute("false",uri.toString(),file.getPath());
// Uri muri = Uri.parse(uri.toString());
}
#SuppressLint("StaticFieldLeak")
private class CompressVideo extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... strings) {
String videoPath = null;
try {
Uri mUri = Uri.parse(strings[1]);
videoPath = SiliCompressor.with(PostReelActivity.this).compressVideo(mUri,strings[2]);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return videoPath;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
File file = new File(s);
Uri videoUri = Uri.fromFile(file);
uploadVideo(videoUri);
}
}
I'm trying to download multiple pictures using picasso. here's my code:
for(int i=1; i <=20; i++){
String url = img_url + i + "/profile.jpg";
String img_dir = img_dir + i;
Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));
}
Url of the site looks like this:
site.com/img/equipment/1/profile.jpg,
site.com/img/equipment/2/profile.jpg,
site.com/img/equipment/3/profile.jpg
and so on ...
i tried
Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));
without the for loop and it is working. images are not download when i place it inside the loop.
here's my Target
private Target picassoImageTarget(Context context, final String imageDir, final String imageName) {
Log.d("picassoImageTarget", " picassoImageTarget");
ContextWrapper cw = new ContextWrapper(context);
final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
return new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
final File myImageFile = new File(directory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath());
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {}
}
};
}
please help. thanks.
Targets are held in WeakReferences.
You need to hold a reference to the Targets you want to keep to prevent them from being garbage collected.
Maybe your code would look something like:
final class MyLoader {
final ArrayList<Target> targets = new ArrayList<>(20);
void load(...) {
for(...) {
Target target = picassoImageTarget(...);
targets.add(target);
picasso.load(...).into(target); // TODO: Maybe remove from list when complete.
}
}
}
I am using google drive api for android to access files in google drive. When a new file is uploaded it takes anywhere from 3 to 15 minutes for the file to be accessible by my app. I tried to add requestSync to occasionally force a sync but every time I run it I get "sync request limit exceeded". Is there something that can be causing me to hit the limit already, or is there a different issue?
RequestSync portion of code:
Drive.DriveApi.requestSync(getGoogleApiClient()).setResultCallback(syncCallback);
final private ResultCallback<com.google.android.gms.common.api.Status> syncCallback = new ResultCallback<com.google.android.gms.common.api.Status>() {
#Override
public void onResult(Status status) {
if (!status.getStatus().isSuccess()) {
showMessage(status.toString());
} else {
showMessage("updated");
}
}
};
Full class:
public class SD_UAV_TEST_RESULTS extends SD_UAV_TEST_MAIN {
TextView numberOfCows_text,picsProcessed_text;
public static int previousCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sd__uav__test__results);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
numberOfCows_text = (TextView) findViewById(R.id.numberOfCows);
picsProcessed_text = (TextView) findViewById(R.id.picsProcessed);
}
public void refreshResults(View view)
{
getContnets();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
String temp = data.getStringExtra("parse");
String[] lines = temp.split(":");
int cow_count = 0;
for(int i=0;i<lines.length;i++)
{
cow_count += Integer.parseInt(lines[i].split(",")[1]);
}
numberOfCows_text.setText(Integer.toString(cow_count));
picsProcessed_text.setText(Integer.toString(lines.length));
}
if (requestCode == 8) {
}
}
public void getContnets(){
if(file_id != null) {
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), file_id)
.setResultCallback(idCallback);
}
}
public void parseFileRead(String temp)
{
String[] lines = temp.split(":");
int cow_count = 0;
for(int i=0;i<lines.length;i++)
{
cow_count += Integer.parseInt(lines[i].split(",")[1]);
}
if(lines.length == previousCount)
{
fnfCount = fnfCount + 1;
}
if(fnfCount >= 5)
{
Drive.DriveApi.requestSync(getGoogleApiClient()).setResultCallback(syncCallback);
fnfCount = 0;
}
numberOfCows_text.setText(Integer.toString(cow_count));
picsProcessed_text.setText(Integer.toString(lines.length));
previousCount = lines.length;
}
final private ResultCallback<com.google.android.gms.common.api.Status> syncCallback = new ResultCallback<com.google.android.gms.common.api.Status>() {
#Override
public void onResult(Status status) {
if (!status.getStatus().isSuccess()) {
showMessage(status.toString());
} else {
showMessage("updated");
}
}
};
//----------------------------------------------------------------------------------------------
final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
#Override
public void onResult(DriveApi.DriveIdResult result) {
DriveId temp = result.getDriveId();
new RetrieveDriveFileContentsAsyncTask(
SD_UAV_TEST_RESULTS.this).execute(temp);
}
};
final private class RetrieveDriveFileContentsAsyncTask
extends ApiClientAsyncTask<DriveId, Boolean, String> {
public RetrieveDriveFileContentsAsyncTask(Context context) {
super(context);
}
#Override
protected String doInBackgroundConnected(DriveId... params) {
String contents = null;
DriveFile file = params[0].asDriveFile();
DriveApi.DriveContentsResult driveContentsResult =
file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return null;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
BufferedReader reader = new BufferedReader(
new InputStreamReader(driveContents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
contents = builder.toString();
} catch (IOException e) {
}
driveContents.discard(getGoogleApiClient());
return contents;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result == null) {
showMessage("Error while reading from the file");
return;
}
parseFileRead(result);
}
}
}
The operation failed because the application attempted the operation too often. As per official DriveApi docs,
In order to avoid excessive load on the device and the server, sync
requests are rate limited. In this case, the operation will fail with
DRIVE_RATE_LIMIT_EXCEEDED status, which indicates that a sync already
happened quite recently so there is no need for another sync. The
operation will succeed when reattempted after a sufficient backoff
duration.
I wanted to download images via Dropbox API so i followed the sample code # Android Dropbox API file download but i do not understand how to integrate it into my current code. I tried changing api.getFileStream("dropbox", dbPath, null); to dropbox.getFileStream("dropbox", dbPath, null); resulting in the error:
'getFileStream(java.lang.String, java.lang.String)' in 'com.dropbox.client2.DropboxAPI' cannot be applied to '(java.lang.String, java.lang.String, null)'
Updated 1 : Changed to `dropbox.getFileStream(FILE_DIR,null)
Main Code
public class Dropbox extends AppCompatActivity implements View.OnClickListener {
private DropboxAPI<AndroidAuthSession> dropbox;
private final static String FILE_DIR = "/DropboxSample/";
private final static String DROPBOX_NAME = "dropbox_prefs";
private final static String ACCESS_KEY = "Insert Key here";
private final static String ACCESS_SECRET = "Insert Key here";
private boolean isLoggedIn;
private Button logIn;
private Button uploadFile;
private Button downloadFile;
private Button listFiles;
private LinearLayout container;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dropbox);
logIn = (Button) findViewById(R.id.dropbox_login);
logIn.setOnClickListener(this);
uploadFile = (Button) findViewById(R.id.upload_file);
uploadFile.setOnClickListener(this);
downloadFile = (Button) findViewById(download_file);
downloadFile.setOnClickListener(this);
listFiles = (Button) findViewById(R.id.list_files);
listFiles.setOnClickListener(this);
container = (LinearLayout) findViewById(R.id.container_files);
loggedIn(false);
AndroidAuthSession session;
AppKeyPair pair = new AppKeyPair(ACCESS_KEY, ACCESS_SECRET);
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
String key = prefs.getString(ACCESS_KEY, null);
String secret = prefs.getString(ACCESS_SECRET, null);
if (key != null && secret != null) {
AccessTokenPair token = new AccessTokenPair(key, secret);
session = new AndroidAuthSession(pair ,token);
} else {
session = new AndroidAuthSession(pair );
}
dropbox = new DropboxAPI<>(session);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = dropbox.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
SharedPreferences prefs = getSharedPreferences(DROPBOX_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(ACCESS_KEY, tokens.key);
editor.putString(ACCESS_SECRET, tokens.secret);
editor.commit();
loggedIn(true);
} catch (IllegalStateException e) {
Toast.makeText(this, "Error during Dropbox authentication",
Toast.LENGTH_SHORT).show();
}
}
}
public void loggedIn(boolean isLogged) {
isLoggedIn = isLogged;
uploadFile.setEnabled(isLogged);
downloadFile.setEnabled(isLogged);
listFiles.setEnabled(isLogged);
logIn.setText(isLogged ? "Log out" : "Log in");
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
ArrayList<String> result = msg.getData().getStringArrayList("data");
for (String fileName : result) {
Log.i("ListFiles", fileName);
TextView tv = new TextView(Dropbox.this);
tv.setText(fileName);
container.addView(tv);
}
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dropbox_login:
if (isLoggedIn) {
dropbox.getSession().unlink();
loggedIn(false);
} else {
dropbox.getSession().startAuthentication(Dropbox.this);
}
break;
case R.id.list_files:
ListDropboxFiles list = new ListDropboxFiles(dropbox, FILE_DIR,
handler);
list.execute();
break;
case R.id.upload_file:
UploadFileToDropbox upload = new UploadFileToDropbox(dropbox, FILE_DIR);
upload.execute();
break;
case R.id.download_file:
try {
downloadDropboxFile(FILE_DIR,(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"CapturyGallery")));
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
public class UploadFileToDropbox extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> dropbox;
private String mPath;
private Context mContext;
private final ProgressDialog mDialog;
private DropboxAPI.UploadRequest mRequest;
private String mErrorMsg;
private File[] listFile;
private int mFilesUploaded;
private int mCurrentFileIndex;;
public UploadFileToDropbox(DropboxAPI<?> dropbox, String path) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
listFile = file.listFiles();
mContext = Dropbox.this;
this.dropbox = dropbox;
this.mPath = path;
mFilesUploaded = 0 ;
mCurrentFileIndex = 0 ;
mDialog = new ProgressDialog(mContext);
mDialog.setMax(100);
mDialog.setMessage("Uploading file 1 /" +listFile.length);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
try {
mRequest.abort();
} catch (Exception e) {
}
}
});
mDialog.show();
mDialog.setCanceledOnTouchOutside(false);
}
#Override
protected Boolean doInBackground(Void... params) {
try {
for (int y = 0; y < listFile.length; y++) {
mCurrentFileIndex = y;
File file = listFile[y];
// By creating a request, we get a handle to the putFile operation,
// so we can cancel it later if we want to
FileInputStream fis = new FileInputStream(file);
String path = mPath + file.getName();
mRequest = dropbox.putFileOverwriteRequest(path, fis, file.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 5;
}
#Override
public void onProgress(long bytes, long total) {
if (isCancelled()) {
mRequest.abort();
} else {
publishProgress(bytes);
}
}
});
mRequest.upload();
if(!isCancelled()){
mFilesUploaded++;
}else{
return false;
}
}
return true;
}
catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
long totalBytes = 0;
long bytesUploaded = 0;
for (int i = 0; i < listFile.length; i++) {
Long bytes = listFile[i].length();
totalBytes += bytes;
if (i < mCurrentFileIndex) {
bytesUploaded += bytes;
}
bytesUploaded += progress[0];
int percent = 100;
int percent1 = (int) (percent * (bytesUploaded/totalBytes));
mDialog.setMessage("Uploading file " + (mCurrentFileIndex + 1) + " / " + listFile.length);
mDialog.setProgress(percent1);
}
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(Dropbox.this, msg, Toast.LENGTH_LONG);
error.show();
}
}
public class ListDropboxFiles extends AsyncTask<Void, Void, ArrayList<String>> {
private DropboxAPI<?> dropbox;
private String path;
private Handler handler;
public ListDropboxFiles(DropboxAPI<?> dropbox, String path, Handler handler) {
this.dropbox = dropbox;
this.path = path;
this.handler = handler;
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> files = new ArrayList<String>();
try {
DropboxAPI.Entry directory = dropbox.metadata(path, 1000, null, true, null);
for (DropboxAPI.Entry entry : directory.contents) {
files.add(entry.fileName());
}
} catch (DropboxException e) {
e.printStackTrace();
}
return files;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putStringArrayList("data", result);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
Added from Sample code
private boolean downloadDropboxFile(String dbPath, File localFile) throws IOException {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
FileDownload fd = dropbox.getFileStream("dropbox", dbPath, null);
br = new BufferedInputStream(fd.is);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} finally {
//in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
}
>
The error message is indicating that the method definition is:
getFileStream(java.lang.String, java.lang.String)
This is also what the documentation for the getFileStream method in the Dropbox Android Core SDK shows.
However, you're attempting to use three parameters:
(java.lang.String, java.lang.String, null)
So, to properly call the method, you should remove that last parameter (null).
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;
}