Filelist filelist request.execute() does not work - android

I want to list all the files that my google accouunts have with my app, i tried the follow piece of code which is actually from the website, but , there's error in the line " FileList fileList = request.execute(); ", it says the method execute() is undefined for the type Drive.Files.List ,i don't know how to fix it.
private void getDriveContents()
{
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
com.google.api.services.drive.Drive.Files f1 = mService.files();
Files.List request = null;
do
{
try
{
request = service.files().list().setQ("trashed=false");
FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
request.setPageToken(fileList.getNextPageToken());
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
if (request != null)
{
request.setPageToken(null);
}
}
} while (request.getPageToken() !=null && request.getPageToken().length() > 0);
populateListView();
}
});
t.start();
}

I believe your 'request' is of incorrect type. it is supposed to be FileList, not File.List

I wasn't arguing about what you've seen. I was only trying to help since I have similar code running and tested. Here's a snippet from my "class ListDownFromGOODrive extends AsyncTask..."
import com.google.api.services.drive.model.FileList;
...
.... a lot of code here
...
GoogleAccountCredential _crd;
Drive _svc;
FileList _gooLst;
Intent _it;
String _rqst;
...
... a lot of code here
...
#Override protected Integer doInBackground(Void... nothing) {
try {
if (_crd == null)
_crd = GoogleAccountCredential.usingOAuth2(_ctx,Arrays.asList(DriveScopes.DRIVE_FILE));
if (_svc == null)
_svc = new Drive.Builder
(AndroidHttp.newCompatibleTransport(), new GsonFactory(), _crd).build();
if (_crd.getSelectedAccountName() == null) {
_it = _crd.newChooseAccountIntent();
return REQ_EMAIL;
}
_gooLst = _svc.files().list().setMaxResults(MAX_DOWN).setQ(_rqst)
.setFields("items(id,title,description,downloadUrl,thumbnailLink)").execute();
}
catch (UserRecoverableAuthIOException e){ //Log.d("atn", "LD URAIO Except->REQ_AUTH");
try { _it = e.getIntent(); } catch (Exception e1) {return ERROR;}
return REQ_AUTH;
}
catch (IOException e) { return ERROR; }
catch (Exception e) { return ERROR; }
return GOOD;
}
it returns GOOD, ERROR, REQ_AUTH(orization), or REQ_EMAIL(account)

Related

Change album art using jaudiotagger

I'm trying to change the album art of an audio file using jaudiotagger but it is not working. There are a lot of question regarding this topic but none of them fulfilled my requirements. Other fields such as artist,audio name, album etc are updated successfully but the album artwork remains the same.
The code I'm using to change the artwork:
public void changeAlbumArt(Uri data) {
Artwork cover = null;
try {
AudioFile f = null;
try {
f = AudioFileIO.read(new File(storageUtil.loadAudio().get(storageUtil.loadAudioIndex()).getData()));
} catch (CannotReadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TagException e) {
e.printStackTrace();
} catch (ReadOnlyFileException e) {
e.printStackTrace();
} catch (InvalidAudioFrameException e) {
e.printStackTrace();
}
Tag tag = null;
if (f != null) {
tag = f.getTag();
}
try {
if(tag!=null) {
cover = ArtworkFactory.createArtworkFromFile(new File(data.getPath()));
tag.deleteArtworkField();
tag.setField(cover);
}
} catch (FieldDataInvalidException e) {
e.printStackTrace();
}
try {
if (f != null) {
f.commit();
}
} catch (CannotWriteException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(storageUtil.loadAudio().get(storageUtil.loadAudioIndex()).getData());
Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);
}
I had this working at one point but have reverted back to jid3 as jaudiotagger required some io files which were not available in android.
In addition, for android Gingerbread+ to write to external storage requires the SAF framework. I have managed to modify the jid3 library so it works but only for mp3.
for mp3 files:
public String setMp3AlbumArt(File SourceFile, byte[] bytes)
throws Exception {
String error = null;
try {
MP3File musicFile = (MP3File) AudioFileIO.read(SourceFile);
AbstractID3v2Tag tag = musicFile.getID3v2Tag();
if (tag != null) {
Artwork artwork = null;
try {
artwork = ArtworkFactory.createArtworkFromFile(SourceFile);
} catch (IOException e) {
e.printStackTrace();
error = e.getMessage();
}
if (artwork != null) {
artwork.setBinaryData(bytes);
tag.deleteArtworkField();
tag.setField(artwork);
musicFile.setTag(tag);
musicFile.commit();
} else {
artwork.setBinaryData(bytes);
tag.addField(artwork);
tag.setField(artwork);
musicFile.setTag(tag);
musicFile.commit();
}
}
} catch (CannotReadException | IOException | TagException
| ReadOnlyFileException | InvalidAudioFrameException e) {
error = e.getMessage();
}
return error;
}

Override/Extend the default http protocol Handler on Android

I've used protocol handlers in the past overriding the default http handler and creating my own custom handlers and I was thinking the approach still works on Android. I am trying to override any http or https URL requested by my Android app and pass it to a custom handler under certain situations. However I still would like to access web resources in other cases. How do I retrieve the default http/https protocol handlers? I'm trying something like the following to load the default handler before putting my override in place:
static URLStreamHandler handler;
static {
Class<?> handlerClass;
try {
handlerClass = Class.forName("net.www.protocol.http.Handler");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Error loading clas for default http handler.", e);
}
Object handlerInstance;
try {
handlerInstance = handlerClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Error instantiating default http handler.", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Error accessing default http handler.", e);
}
if (! (handlerInstance instanceof URLStreamHandler)) {
throw new RuntimeException("Wrong class type, " + handlerInstance.getClass().getName());
} else {
handler = (URLStreamHandler) handlerInstance;
}
}
My override logic works as follows:
URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
public URLStreamHandler createURLStreamHandler(String protocol) {
URLStreamHandler urlStreamHandler = new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
return new URLConnection(url) {
public void connect() throws IOException {
Log.i(getClass().getName(), "Global URL override!!! URL load requested " + url);
}
};
}
};
return shouldHandleURL(url) ? urlStreamHandler : handler;
}
});
The override works but I cannot load the default in cases where I want normal URL connection behavior. Trying to clear my StreamHandlerFactory as follows:
URL.setURLStreamHandlerFactory(null);
Throws an error:
java.lang.Error: Factory already set
at java.net.URL.setURLStreamHandlerFactory(URL.java:112)
The only way I've been able to resolve my issue is by setting the streamHandler and StramHandler factory to null using reflection through the private fields. It's yucky but it works. This is my temporary solution (I was hoping for something less yucky):
private static class APIURLStreamHandlerFactory implements URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
return new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
if (! shouldHandle(url)) {
Field streamHandlerMapField = getURLPrivateField("streamHandlers");
try { Map handlerMap = (Map) streamHandlerMapField.get(url); handlerMap.clear(); }
catch (IllegalAccessException e) { throw new Error("Could not access private field streamHandler",e); }
unregisterSelf();
invokeInstancePrivateMethod(url, "setupStreamHandler");
URLStreamHandler originalHandler = getPrivateUrlStreamHandler(url);
Method openConnectionMethod = getPrivateMethod(originalHandler, "openConnection", URL.class);
openConnectionMethod.setAccessible(true);
try { return (URLConnection) openConnectionMethod.invoke(originalHandler, url); }
catch (IllegalAccessException e) { throw new Error("Could not access openConnection on URL", e); }
catch (InvocationTargetException e) { throw new RuntimeException("Exception while invoking openConnection on URL", e); }
finally { registerSelf(); }
}
return new APIURLConnection(url, registeredServiceRouter);
}
};
}
private static Method getPrivateMethod(Object object, String methodName, Class... parameterTypes) {
try { return object.getClass().getDeclaredMethod(methodName, parameterTypes); }
catch (NoSuchMethodException e) { throw new Error("Could not find method " + methodName, e); }
}
private static boolean shouldHandle(URL url) {
//Logic to decide which requests to handle
}
private static URLStreamHandler getPrivateUrlStreamHandler(URL url) {
URLStreamHandler originalHandler;
try { originalHandler = (URLStreamHandler) getURLPrivateField("streamHandler").get(url); }
catch (IllegalAccessException e) { throw new Error("Could not access streamHandler field on URL",e); }
return originalHandler;
}
private static Object invokeInstancePrivateMethod(Object objectInstance, String methodName) {
try {
Method urlPrivateMethod = getURLPrivateMethod(methodName);
urlPrivateMethod.setAccessible(true);
return urlPrivateMethod.invoke(objectInstance);
}
catch (IllegalAccessException e) { throw new Error("Cannot access metehod " + methodName + " on instance type " + objectInstance.getClass().getName(), e); }
catch (InvocationTargetException e) { throw new RuntimeException("Exception while invoking method " + methodName + " on type " + objectInstance.getClass().getName(),e); }
}
private static Method getURLPrivateMethod(String methodName) {
try { return URL.class.getDeclaredMethod(methodName); }
catch (NoSuchMethodException e) { throw new Error("Method " + methodName + " not found on class URL"); }
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private static void resetStreamHandlerFactory() {
try { getURLPrivateField("streamHandlerFactory").set(null, null); }
catch (IllegalAccessException e) { throw new Error("Could not access factory field on URL class: {}", e); }
}
#NonNull
private static Field getURLPrivateField(String field) {
final Field privateField;
try { privateField = URL.class.getDeclaredField(field); }
catch (NoSuchFieldException e) { throw new Error("No such field " + field + " in class URL"); }
privateField.setAccessible(true);
return privateField;
}
}
I found this in java.net.URL
else if (protocol.equals("http")) {
try {
String name = "com.android.okhttp.HttpHandler";
streamHandler = (URLStreamHandler) Class.forName(name).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
}
It would appear com.android.okhttp.HttpHandler would be the stream handler you would want to return for default behaviour
Here are the other defaults:
if (protocol.equals("file")) {
streamHandler = new FileHandler();
} else if (protocol.equals("ftp")) {
streamHandler = new FtpHandler();
} else if (protocol.equals("http")) {
try {
String name = "com.android.okhttp.HttpHandler";
streamHandler = (URLStreamHandler) Class.forName(name).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
} else if (protocol.equals("https")) {
try {
String name = "com.android.okhttp.HttpsHandler";
streamHandler = (URLStreamHandler) Class.forName(name).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
} else if (protocol.equals("jar")) {
streamHandler = new JarHandler();
}
if (streamHandler != null) {
streamHandlers.put(protocol, streamHandler);
}
PS: I've been trying to solve this for the past couple hours and your post was the only one I could find wanting to do a similar thing. Hopefully this helps.

Google drive return empty files

I am making a app which access files from google drive. I am using this link to acess the files from google drive. The methodFiles.List request = service.files().list(); return {} for me all the time. i am posting my all code here.
private Drive getDriveService() {
try {
GoogleAccountCredential credential = GoogleAccountCredential
.usingOAuth2(MainActivity.this, DriveScopes.DRIVE_FILE);
credential.setSelectedAccountName("Sachinkamboj1989#gmail.com");
drive = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
drive.children();
drive.files();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
retrieveAllFiles1(drive);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
return drive;
}
private static List<File> retrieveAllFiles1(Drive service)
throws IOException {
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
System.out.println(files);
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
// System.out.println(result);
return result;
}
Method to access file is

Error on ruOnUiThread inside asychtask

I am trying to parse some data from server and compare the data with the data in the database...
Everything seems working fine... except I am getting only same value even the comparing data change... I'll explain it with the code...
In the below code, there is textviews tv3 and tv4... even the comparing data ie, shopid changed, it shows the value from the first array of the json...
when i tried to debug, i found the the run() inside the runOnUithread is calling after 2-3 loops... i donno whats happening here... Please somone help ,e to sort out the issue...
Edit: while debugging when i skip to each line it not showing any error...
But when i try to skip to the breakpoints using F9 it shows the error...
Edit: 2: Since the code is litle bit long, i juz deleted som unwanted part...
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private class GetJsondata extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
ObjectOutput out = new ObjectOutputStream(new FileOutputStream
(new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
out.writeObject(jsonObj.toString());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream
(new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
jsonObj = new JSONObject((String) in.readObject());
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
if (jsonObj != null) {
try {
ofrList = new ArrayList<ArrayList<String>>();
// Getting JSON Array node
jsonArray = jsonObj.getJSONArray("offers");
shoplistarray = new ArrayList<ArrayList<String>>();
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
url1 = c.getString("url");
if (userPrefs.getString("locale", null) == null || userPrefs.getString("locale", null).equals("en")) {
desc = c.getString("desc");
} else {
desc = c.getString("desc_ar");
}
expdate = c.getString("expdate");
ofrdate = c.getString("date");
shopsarray = c.getJSONArray("shops");
for (int n = 0; n < shopsarray.length(); n++) {
JSONObject jobj = shopsarray.getJSONObject(n);
shopid = jobj.getString("shopid");
if (shopid.equals(id) && tv3.getText().toString().equals("") ) {
downloadBitmap(url1);
finalI = i;
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate);
}
});
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.urnotconnected), Toast.LENGTH_LONG).show();
}
});
}
return desc;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
}
}
private Bitmap getFileOutOfCache(String fileName) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiskCacheFilePath = new File(cachePath);
File myCachedFile = new File(myDiskCacheFilePath
+ File.separator + fileName);
if (myCachedFile.exists()) {
bitmap = BitmapFactory.decodeFile(myCachedFile.toString());
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachedfilenotexist), Toast.LENGTH_LONG).show();
}
return bitmap;
}
public void saveFileInCache(String aFileName, Bitmap myImage) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiscCacheFilePath;
myDiscCacheFilePath = new File(cachePath);
File myDiscCacheFile = new File(myDiscCacheFilePath + File.separator + aFileName);
try {
FileOutputStream out = new FileOutputStream(myDiscCacheFile);
myImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachefailed), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private class GetJsondata extends AsyncTask<Void, Void, String> {
boolean isIfCondition=false;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
ObjectOutput out = new ObjectOutputStream(new FileOutputStream
(new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
out.writeObject(jsonObj.toString());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream
(new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
jsonObj = new JSONObject((String) in.readObject());
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
if (jsonObj != null) {
try {
ofrList = new ArrayList<ArrayList<String>>();
// Getting JSON Array node
jsonArray = jsonObj.getJSONArray("offers");
shoplistarray = new ArrayList<ArrayList<String>>();
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
url1 = c.getString("url");
if (userPrefs.getString("locale", null) == null || userPrefs.getString("locale", null).equals("en")) {
desc = c.getString("desc");
} else {
desc = c.getString("desc_ar");
}
expdate = c.getString("expdate");
ofrdate = c.getString("date");
shopsarray = c.getJSONArray("shops");
for (int n = 0; n < shopsarray.length(); n++) {
JSONObject jobj = shopsarray.getJSONObject(n);
shopid = jobj.getString("shopid");
if (shopid.equals(id) && tv3.getText().toString().equals("") ) {
downloadBitmap(url1);
finalI = i;
//no need to use runonuithread since post execute methods already runs on main ui thread ..rather set isIfCondition=true and do this job on postexecute method
isIfCondition=true;
desc1=desc;
expdate1=expdate;
/*getActivity().runOnUiThread(new Runnable() {
public void run() {
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate);
}
});*/
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
//no need to use runonuithread since post execute methods already runs on main ui thread
/*getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.urnotconnected), Toast.LENGTH_LONG).show();
}
});*/
}
return desc;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
if(isIfCondition=true)
{
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc1);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate1);
}
}
}
private Bitmap getFileOutOfCache(String fileName) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiskCacheFilePath = new File(cachePath);
File myCachedFile = new File(myDiskCacheFilePath
+ File.separator + fileName);
if (myCachedFile.exists()) {
bitmap = BitmapFactory.decodeFile(myCachedFile.toString());
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachedfilenotexist), Toast.LENGTH_LONG).show();
}
return bitmap;
}
public void saveFileInCache(String aFileName, Bitmap myImage) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiscCacheFilePath;
myDiscCacheFilePath = new File(cachePath);
File myDiscCacheFile = new File(myDiscCacheFilePath + File.separator + aFileName);
try {
FileOutputStream out = new FileOutputStream(myDiscCacheFile);
myImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachefailed), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
there is not need to use runonuithread or any other thread...because asynctask is already do this for you..doinbackground work run on bgthread and onpostexecute work on mainuithread..
Just check the code...i haven't check..but it will work for sure....
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
new GetJsondata().execute()
}else{
//show toast
}
Write the above code in the place where you are calling the asynctask.Remove it from the asynctask itself.

What is wrong with this Asynchronus task?

the method onPostExecute simply was not executed, I have seen 36 at LogCat but I can not see 13 in LogCAT. I tried to debug it, it seemed that it goes to the first line of the class (package line) after return statement.
private class Client extends AsyncTask<Integer, Void, Integer> {
protected Integer doInBackground(Integer... params) {
Log.e(TAG,10+"");
try {
socket = new Socket(target, port);
//socket.setSoTimeout(3000);
Log.e(TAG,31+"");
oos = new ObjectOutputStream(socket.getOutputStream());
Log.e(TAG,34+"");
ois = new ObjectInputStream(socket.getInputStream());
Log.e(TAG,35+"");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG,36+"");
return 1;
}
protected void onPostExecute(Integer result) {
Log.e(TAG,13+"");
try {
Log.e(TAG,12+"");
oos.writeUTF(key);
Log.e(TAG,16+"");
if (ois.readInt() == OKAY) {
isConnected = true;
Log.e(TAG,14+"");
}else{
Log.e(TAG,15+"");
isConnected = false;
}
} catch (IOException e) {
e.printStackTrace();
isClosed = true;
}
Log.e(TAG,19+"");
}
}
Number seen in logCat:
10
31
34
35
36
Nothing after that.

Categories

Resources