Android pass a single string from a Fragment to Asynctask - android

I would like to pass a String from an Editext inside a Fragment into an asynctask, how I can do that? I have read here similar posts but I'm doing something wrong.
Fragment
EditText txt=(EditText) view.findViewById(R.id.textSearch);
EditText date=(EditText) view.findViewById(R.id.textDate);
// Get Editext string and pass it to the Asynctask
txtSearch = txt.getEditableText().toString();
Log.d(TAG, "variabile text " + txtSearch);
new TessAsyncEngine().execute(txtSearch);
Asynctask (go to //detect words)
public class TessAsyncEngine extends AsyncTask<Object, Void, String> {
static final String TAG = "DBG_" + TessAsyncEngine.class.getName();
private Bitmap bmp;
private Activity context;
#Override
protected String doInBackground(Object... params) {
try {
if(params.length < 2) {
Log.e(TAG, "Error passing parameter to execute - missing params");
return null;
}
if(!(params[0] instanceof Activity) || !(params[1] instanceof Bitmap)) {
Log.e(TAG, "Error passing parameter to execute(context, bitmap)");
//Log.e(TAG, "Error passing parameter " + params[0].toString() + params[1].toString());
return null;
}
context = (Activity)params[0];
bmp = (Bitmap)params[1];
if(context == null || bmp == null) {
Log.e(TAG, "Error passed null parameter to execute(context, bitmap)");
return null;
}
int rotate = 0;
if(params.length == 3 && params[2]!= null && params[2] instanceof Integer){
rotate = (Integer) params[2];
}
if(rotate >= -180 && rotate <= 180 && rotate != 0)
{
bmp = Tools.preRotateBitmap(bmp, rotate);
Log.d(TAG, "Rotated OCR bitmap " + rotate + " degrees");
}
TessEngine tessEngine = TessEngine.Generate(context);
bmp = bmp.copy(Bitmap.Config.ARGB_8888, true);
String result = tessEngine.detectText(bmp);
//detect words
String textSearch = new ScanFragment().txtSearch;
if (result.equalsIgnoreCase(textSearch)) {
String result1 = ("Warning!: ") + result.concat(" found");
return result1;
} else {
String result2 = ("I have found: ") + result.concat(" check it");
return result2;
}
//Log.d(TAG, result);
//return result;
} catch (Exception ex) {
Log.d(TAG, "Error: " + ex + "\n" + ex.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(s == null || bmp == null || context == null)
return;
ImageDialog.New()
.addBitmap(bmp)
.addTitle(s)
.show(context.getFragmentManager(), TAG);
super.onPostExecute(s);
}
}
EDIT: I forgot to add the trace
08-25 10:41:25.210 6311-7176/com.fastnetserv.app D/DBG_com.fastnetserv.app.TessAsyncEngine: Error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
EDIT2 AsyncTask after Ashish suggestions
public class TessAsyncEngine extends AsyncTask<Void, Void, Void> {
static final String TAG = "DBG_" + TessAsyncEngine.class.getName();
private Bitmap bmp;
private Activity context;
String search;
TessAsyncEngine(String search){
this.search=search;
}
#Override
//protected String doInBackground(Object... params) {
protected Void doInBackground(Void... params){
try {
if(params.length < 2) {
Log.e(TAG, "Error passing parameter to execute - missing params");
return null;
}
if(!(params[0] instanceof Activity) || !(params[1] instanceof Bitmap)) {
Log.e(TAG, "Error passing parameter to execute(context, bitmap)");
//Log.e(TAG, "Error passing parameter " + params[0].toString() + params[1].toString());
return null;
}
context = (Activity)params[0];
bmp = (Bitmap)params[1];
if(context == null || bmp == null) {
Log.e(TAG, "Error passed null parameter to execute(context, bitmap)");
return null;
}
int rotate = 0;
if(params.length == 3 && params[2]!= null && params[2] instanceof Integer){
rotate = (Integer) params[2];
}
if(rotate >= -180 && rotate <= 180 && rotate != 0)
{
bmp = Tools.preRotateBitmap(bmp, rotate);
Log.d(TAG, "Rotated OCR bitmap " + rotate + " degrees");
}
TessEngine tessEngine = TessEngine.Generate(context);
bmp = bmp.copy(Bitmap.Config.ARGB_8888, true);
String result = tessEngine.detectText(bmp);
//detect words
//Bundle bundle = context.getIntent().getExtras();
//String txtSearch = bundle.getString("TextSearch");
String textSearch = new ScanFragment().txtSearch;
if (result.equalsIgnoreCase(textSearch)) {
String result1 = ("WARNING! : ") + result.concat(" found");
return result1;
} else {
String result2 = ("detected this word: ") + result.concat(" please check it");
return result2;
}
//Log.d(TAG, result);
//return result;
} catch (Exception ex) {
Log.d(TAG, "Error: " + ex + "\n" + ex.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(s == null || bmp == null || context == null)
return;
ImageDialog.New()
.addBitmap(bmp)
.addTitle(s)
.show(context.getFragmentManager(), TAG);
super.onPostExecute(s);
}
}
CameraFragmnet
public class CameraFragment extends Fragment implements SurfaceHolder.Callback, View.OnClickListener,
Camera.PictureCallback, Camera.ShutterCallback {
static final String TAG = "DBG_" + MainActivity.class.getName();
Button shutterButton;
Button focusButton;
FocusBoxView focusBox;
SurfaceView cameraFrame;
CameraEngine cameraEngine;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CameraFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CameraFragment.
*/
// TODO: Rename and change types and number of parameters
public static CameraFragment newInstance(String param1, String param2) {
CameraFragment fragment = new CameraFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_camera, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
// Camera Code
public String detectText(Bitmap bitmap) {
TessDataManager.initTessTrainedData(getActivity());
TessBaseAPI tessBaseAPI = new TessBaseAPI();
//String path = "/mnt/sdcard/com.fastnetserv.app/tessdata/eng.traineddata";
String path = Environment.getExternalStorageDirectory().getPath()+"/com.fastnetserv.app/files/tesseract/tessdata/eng.traineddata";
Log.d(TAG, "Check data path: " + path);
tessBaseAPI.setDebug(true);
tessBaseAPI.init(path, "ita"); //Init the Tess with the trained data file, with english language
//For example if we want to only detect numbers
//Already defined on TessEngine
//tessBaseAPI.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "1234567890");
//tessBaseAPI.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "!##$%^&*()_+=-qwertyuiop[]}{POIU" +
// "YTREWQasdASDfghFGHjklJKLl;L:'\"\\|~`xcvXCVbnmBNM,./<>?");
tessBaseAPI.setImage(bitmap);
String text = tessBaseAPI.getUTF8Text();
//Log.d(TAG, "Got data: " + result);
tessBaseAPI.end();
return text;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "Surface Created - starting camera");
if (cameraEngine != null && !cameraEngine.isOn()) {
cameraEngine.start();
}
if (cameraEngine != null && cameraEngine.isOn()) {
Log.d(TAG, "Camera engine already on");
return;
}
cameraEngine = CameraEngine.New(holder);
cameraEngine.start();
Log.d(TAG, "Camera engine started");
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onResume() {
super.onResume();
cameraFrame = (SurfaceView) getActivity().findViewById(R.id.camera_frame);
shutterButton = (Button) getActivity().findViewById(R.id.shutter_button);
focusBox = (FocusBoxView) getActivity().findViewById(R.id.focus_box);
focusButton = (Button) getActivity().findViewById(R.id.focus_button);
shutterButton.setOnClickListener(this);
focusButton.setOnClickListener(this);
SurfaceHolder surfaceHolder = cameraFrame.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraFrame.setOnClickListener(this);
}
#Override
public void onPause() {
super.onPause();
if (cameraEngine != null && cameraEngine.isOn()) {
cameraEngine.stop();
}
SurfaceHolder surfaceHolder = cameraFrame.getHolder();
surfaceHolder.removeCallback(this);
}
#Override
public void onClick(View v) {
if(v == shutterButton){
if(cameraEngine != null && cameraEngine.isOn()){
cameraEngine.takeShot(this, this, this);
}
}
if(v == focusButton){
if(cameraEngine!=null && cameraEngine.isOn()){
cameraEngine.requestFocus();
}
}
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "Picture taken");
if (data == null) {
Log.d(TAG, "Got null data");
return;
}
Bitmap bmp = Tools.getFocusedBitmap(getActivity(), camera, data, focusBox.getBox());
Log.d(TAG, "Got bitmap");
//new TessAsyncEngine().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, this, bmp);
new TessAsyncEngine().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, getActivity(), bmp);
}
#Override
public void onShutter() {
}
}

Here you can also pass in constructor of Async Task.
private string;
public TessAsyncEngine(String string)
{
this.string = string;
}

Add a constructor to the Asynctask:
public class TessAsyncEngine extends AsyncTask<Object, Void, String> {
static final String TAG = "DBG_" + TessAsyncEngine.class.getName();
private Bitmap bmp;
private Activity context;
String search;
TessAsyncEngine(String search)
{
this.search=search;
}
#Override
protected String doInBackground(Object... params) {
try {
if(params.length < 2) {
Log.e(TAG, "Error passing parameter to execute - missing params");
return null;
}
if(!(params[0] instanceof Activity) || !(params[1] instanceof Bitmap)) {
Log.e(TAG, "Error passing parameter to execute(context, bitmap)");
//Log.e(TAG, "Error passing parameter " + params[0].toString() + params[1].toString());
return null;
}
context = (Activity)params[0];
bmp = (Bitmap)params[1];
if(context == null || bmp == null) {
Log.e(TAG, "Error passed null parameter to execute(context, bitmap)");
return null;
}
int rotate = 0;
if(params.length == 3 && params[2]!= null && params[2] instanceof Integer){
rotate = (Integer) params[2];
}
if(rotate >= -180 && rotate <= 180 && rotate != 0)
{
bmp = Tools.preRotateBitmap(bmp, rotate);
Log.d(TAG, "Rotated OCR bitmap " + rotate + " degrees");
}
TessEngine tessEngine = TessEngine.Generate(context);
bmp = bmp.copy(Bitmap.Config.ARGB_8888, true);
String result = tessEngine.detectText(bmp);
//detect words
String textSearch = new ScanFragment().txtSearch;
if (result.equalsIgnoreCase(textSearch)) {
String result1 = ("Warning!: ") + result.concat(" found");
return result1;
} else {
String result2 = ("I have found: ") + result.concat(" check it");
return result2;
}
//Log.d(TAG, result);
//return result;
} catch (Exception ex) {
Log.d(TAG, "Error: " + ex + "\n" + ex.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(s == null || bmp == null || context == null)
return;
ImageDialog.New()
.addBitmap(bmp)
.addTitle(s)
.show(context.getFragmentManager(), TAG);
super.onPostExecute(s);
}
}
Call the asynctask like this:
new TessAsyncEngine(txtSearch).execute();

Related

Retrofit enqueue gets dismissed on orientation change

I am trying to upload plain text and image to the api using RetroFit. I want make sure the request continues to execute on orientation change. To do this, I have encapsulated the RetroFit api call inside a Headless fragment. This works fine when I try to upload an image. The request stops and resumes on device rotation. However it just gets cancelled on a text upload.
The only difference between the two uploads is that for image upload I use execute() and for text I use enqueue(). However, if I try to use execute() with the text, it still does not work.
Below is some code :-
UpdateTaskHelper (Headless fragment)
public static class UploadTaskHelper extends Fragment
{
private UploadAsync uploadTask;
private ProgressDialog m_loadingp;
public static UploadTaskHelper newInstance()
{
return new UploadTaskHelper();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onDestroy()
{
Log.d(getClass().getName(), "[onDestroy]");
super.onDestroy();
if (uploadTask != null)
{
uploadTask.cancel(true);
}
}
public void startUpload(ActionActivity actionActivity, boolean shouldTakePhoto, boolean isTextNote, String noteContent)
{
uploadTask = new UploadAsync(actionActivity, shouldTakePhoto, isText, noteContent);
uploadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static class UploadAsync extends AsyncTask<Void, Void, Void>
{
private Bitmap m_bitmap = null;
private Pair<Boolean, String> m_errorPair;
private File m_uploadedFile = null;
private WeakReference<ActionActivity> m_weakActivity;
private boolean shouldTakePhoto;
private boolean isTextNote;
private java.io.File m_capturedImageFile;
UploadAsync(#NonNull ActionActivity activity, boolean shouldTakePhoto, boolean isTextNote, String textNoteContent)
{
this.m_weakActivity = new WeakReference<>(activity);
this.shouldTakePhoto = shouldTakePhoto;
this.isTextNote = isTextNote;
}
#Override
protected Void doInBackground(Void... params)
{
try
{
final ActionActivity activity = this.m_weakActivity.get();
activity.m_fileAPIWrapper = new FileAPIWrapper(new IHttpEventTracker<File>()
{
#Override
public void getCallProgress(int progress) {}
#Override
public void onCallFail(#NonNull String cause, #NonNull Throwable t, #Nullable ResponseBody responseBody)
{
m_errorPair = new Pair<>(true, t.getLocalizedMessage());
}
#Override
public void onCallSuccess(#NonNull RealmList<File> models)
{
m_errorPair = new Pair<>(false, AppConstants.EMPTY_STRING);
m_uploadedFile = models.get(0);
}
});
if(!isTextNote)
{
final java.io.File storageDir = new java.io.File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + java.io.File.separator + activity.getPackageName()
+ java.io.File.separator + "-" + java.io.File.separator);
if (!storageDir.exists())
{
storageDir.mkdirs();
}
this.m_capturedImageFile = java.io.File.createTempFile("IMG_" + System.currentTimeMillis(), ".jpg", storageDir);
final FileOutputStream outStream = new FileOutputStream(this.m_capturedImageFile);
this.m_bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
outStream.flush();
outStream.close();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
this.m_bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
activity.m_fileAPIWrapper.postImage(RequestBody.create(MediaType.parse("image/jpeg"), stream.toByteArray()));
stream.flush();
stream.close();
}
else
{
activity.m_fileAPIWrapper.postTextNote(RequestBody.create(MediaType.parse("multipart/raw"), activity.m_addContentNoteEdit.getText()
.toString()));
}
}
catch (Exception e)
{
e.printStackTrace();
this.m_errorPair = new Pair<>(true, e.toString());
}
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
activity.m_loading.show();
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
}
}
}
Network calls :-
public void postImage(#NonNull RequestBody reqFile) {
if (m_eventTracker != null) {
final ResponseToken token = NetworkUtil.getAccessToken();
if (getService() != null && m_httpOperationWrapper != null && token != null) {
m_call = getService().postImage(token.getTokenType() + " " + token.getAccessToken(), NetworkUtil.X_VERSION,
"filename=IMG_" + System.currentTimeMillis(), "image/jpeg", reqFile);
m_httpOperationWrapper.initCall(m_call, this, true);
} else {
m_eventTracker.onCallFail(AppConstants.BAD_REQUEST, new Throwable("Something went wrong, Try again later!"), null);
}
}
}
/**
* Execute HTTP call to post a new text note.
*/
public void postTextNote(#NonNull RequestBody requestBody) {
if (m_eventTracker != null) {
final ResponseToken token = NetworkUtil.getAccessToken();
if (getService() != null && m_httpOperationWrapper != null && token != null) {
m_call = getService().postFile(token.getTokenType() + " " + token.getAccessToken(), NetworkUtil.X_VERSION,
"filename=" + token.getOwnerId() + "_text_note_" + System.currentTimeMillis(), "text/plain",
requestBody);
m_httpOperationWrapper.initCall(m_call, this);
} else {
m_eventTracker.onCallFail(AppConstants.BAD_REQUEST, new Throwable("Something went wrong, Try again later!"), null);
}
}
}
public void initCall(#NonNull Call<ContentResponse> call, #NonNull IHttpOperationCallback callback, final boolean isSynchronousCall) {
m_callback = callback;
try {
if (NetworkUtil.isNetworkAvailable()) {
if (isSynchronousCall) {
m_executeRequest(call);
} else {
m_enqueueRequest(call);
}
} else {
m_callback.onFailure(call, new Throwable(AppConstants.NO_INTERNET), null);
}
} catch (Exception e) {
m_callback.onFailure(call, e.fillInStackTrace(), null);
}
}
private void m_enqueueRequest(#NonNull Call<ContentResponse> call) {
call.enqueue(new Callback<ContentResponse>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onResponse(#NonNull Call<ContentResponse> call, #NonNull Response<ContentResponse> response) {
if (m_callback != null) {
if (!Util.isValidResponse(response)) {
String error = "Status: " + response.code() + " " + response.message();
m_callback.onFailure(call, new Throwable(
response.code() == HttpURLConnection.HTTP_UNAUTHORIZED ? AppConstants.UNAUTHORIZED : error), response.errorBody());
return;
}
m_callback.onSuccess(call, response.body());
}
}
#Override
public void onFailure(#NonNull Call<ContentResponse> call, #NonNull Throwable t) {
if (m_callback != null) {
m_callback.onFailure(call, t, null);
}
}
});
}
#WorkerThread
private void m_executeRequest(#NonNull Call<ContentResponse> call) {
try {
Response<ContentResponse> response = call.execute();
if (m_callback != null) {
if (!Util.isValidResponse(response)) {
String error = "Status: " + response.code() + " " + response.message();
m_callback.onFailure(call,
new Throwable(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED ? AppConstants.UNAUTHORIZED : error),
response.errorBody());
return;
}
//noinspection ConstantConditions
m_callback.onSuccess(call, response.body());
}
} catch (IOException | RuntimeException e) {
e.printStackTrace();
if (m_callback != null) {
m_callback.onFailure(call, e.fillInStackTrace(), null);
}
}
}
How can I get the same behaviour for the text note? Any help is appreciated.
When you use enqueue your request sent async, and the orientation change destroys the activity and cancels your response code scope.
You should consider move the request code into a ViewModel class which is part of the MVVM architecture. The ViewModel would make the request even after orientation change and keep the data inside it, then you could access its data after the activity is re-created.

Google Play: update prices from IInAppBillingService

I created a class for working with subscriptions in the store.
In the beginning I receive from the server the list of subscriptions with the prices
The code is working and on most devices there is no problem.
But some users do not recive prices. It's like there's no response from the server. I've studied examples of implementation in Google documentation, but I can not understand where I can have problems in the code.
Part of my code:
public class BillingActivity extends AppCompatActivity {
RelativeLayout imageLayout;
View payButton;
// WebView payWebView;
// TextView useCodeButton;
ProgressBar progress1;
ProgressBar progress2;
ProgressBar progress3;
IInAppBillingService inAppBillingService;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_billing_subscription);
price_1monthTextView = (TextView) findViewById(R.id.price_1monthTextView);
relative_1month = (RelativeLayout) findViewById(R.id.relative_1month);
relative_1month.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (MainActivity.myAccount == null) return;
if (MainActivity.myAccount.getUniqid() == null) return;
if (subscription1m != null) {
try {
Log.d("my", "purchase..." + subscription1m.storeName);
purchaseProduct(subscription1m);
} catch (Exception e) {
e.printStackTrace();
Log.d("my", "purchase error = " + e.toString());
}
}
}
});
progress1 = (ProgressBar) findViewById(R.id.progress1);
startGoogleBilling();
}
private void startGoogleBilling() {
if (serviceConnection != null) {
unbindService(serviceConnection);
}
progress1.setVisibility(View.VISIBLE);
serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
inAppBillingService = IInAppBillingService.Stub.asInterface(service);
getSubscribtionsList();
}
#Override
public void onServiceDisconnected(ComponentName name) {
inAppBillingService = null;
}
};
Intent serviceIntent =
new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private static final int PR_CNT = 3;
List<InAppProduct> subscriptions = null;
InAppProduct subscription1m = null;
InAppProduct subscription3m = null;
InAppProduct subscription1y = null;
String[] productIds = {"eq.subscription.1m", "eq.subscription.3m.2", "eq.subscription.1y"};
private void getSubscribtionsList() {
mSwipeRefreshLayout.setRefreshing(false);
progress1.setVisibility(View.GONE);
try {
subscriptions =
getInAppPurchases("subs", productIds[0], productIds[1], productIds[2]);
if (subscriptions.size() == PR_CNT) {
for (InAppProduct inAppProduct : subscriptions) {
String productId = inAppProduct.productId;
Log.d("my", "productId= " + productId);
if (productId.contains(productIds[0])) subscription1m = inAppProduct;
if (productId.contains(productIds[1])) subscription3m = inAppProduct;
if (productId.contains(productIds[2])) subscription1y = inAppProduct;
}
Log.d("my", "1m= " + subscription1m.storeName + " pr=" + subscription1m.price + "\\n\\r " +
"3m= " + subscription3m.storeName + " pr=" + subscription3m.price + "\\n\\r " +
"1y= " + subscription1y.storeName + " pr=" + subscription1y.price + "\\n\\r ");
///----------------------!!!!
// purchaseProduct(inAppProduct);
}
updatePrices();
} catch (Exception e) {
Log.d("my", "exc = " + e.toString());
if (e.toString().contains("Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getSkuDetails")) {
if (attempt < 4) {
//getSubscribtionsList();
// startGoogleBilling();
} else {
}
}
// Toast.makeText(this, "Google inApp connection error", Toast.LENGTH_SHORT).show();
// refreshButton.setVisibility(View.VISIBLE);
startGoogleBilling();
}
}
private int attempt = 0;
#Override
public void onDestroy() {
super.onDestroy();
if (serviceConnection != null) {
unbindService(serviceConnection);
}
}
class InAppProduct {
public String productId;
public String storeName;
public String storeDescription;
public String price;
public boolean isSubscription;
public int priceAmountMicros;
public String currencyIsoCode;
public String getSku() {
return productId;
}
String getType() {
return isSubscription ? "subs" : "inapp";
}
}
List<InAppProduct> getInAppPurchases(String type, String... productIds) throws Exception {
ArrayList<String> skuList = new ArrayList<>(Arrays.asList(productIds));
Bundle query = new Bundle();
query.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails = inAppBillingService.getSkuDetails(
3, getPackageName(), type, query);
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
List<InAppProduct> result = new ArrayList<>();
for (String responseItem : responseList) {
JSONObject jsonObject = new JSONObject(responseItem);
InAppProduct product = new InAppProduct();
// "com.example.myapp_testing_inapp1"
product.productId = jsonObject.getString("productId");
// Покупка
product.storeName = jsonObject.getString("title");
// Детали покупки
product.storeDescription = jsonObject.getString("description");
// "0.99USD"
product.price = jsonObject.getString("price");
// "true/false"
product.isSubscription = jsonObject.getString("type").equals("subs");
// "990000" = цена x 1000000
product.priceAmountMicros =
Integer.parseInt(jsonObject.getString("price_amount_micros"));
// USD
product.currencyIsoCode = jsonObject.getString("price_currency_code");
result.add(product);
}
return result;
}
private void updatePrices() {
if (subscriptions.size() == PR_CNT) {
price_1monthTextView.setText(subscription1m.price);
price_3monthTextView.setText(subscription3m.price);
price_1yearTextView.setText(subscription1y.price);
}
}
}
my problem was the bit depth of the X variable priceAmountMicros
The price from playmarket is multiplied by a 1000000 , and Kazakh tenge has exchange rate = 1 USD= 331,3 KZT.
And if i have price 18 000 KTZ and * 1000 000.
For price variable I must use long type

How to wait for an activity to finish in asynctask

I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}

Call an AsyncTask subclass of activity from another class?

I know this kind of questions are maybe too old, but I got stock with this silly thing.
I have an AsyncTask class which is a subclass of an activity class, and right now I want to call it from another class: following codes shows what I mean:
public class STA extends Activity {
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
private static final String TAG = "ListSpdFiles: ";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private String initiator;
private String path;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(String initiator, String path) {
this.initiator = initiator;
this.path = path;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(getApplicationContext(), pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
// tv.setText("task concluded with a null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
//tv.setText("List of files received is:\n" + Arrays.toString(listOfFiles));
}
term();
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
final Global globalVariable = (Global) getApplicationContext();
if (globalVariable.getPasswordButt() == false) {
// Calling Application class (see application tag in AndroidManifest.xml)
// Get name and email from global/application context
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
String username = "/" + getLastAccessedBrowserPage() + ".username" + ".txt";
//String password = "/" + CurrentURL + "password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, username, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setUsername(name);
// getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsUsername(false);
} else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
// globalVariable.setUsernameButt(false);
} else if (globalVariable.getPasswordButt() == true) {
// Calling Application class (see application tag in AndroidManifest.xml)
// final Global globalVariable = (Global) getApplicationContext();
// Get name and email from global/application context
final boolean ispassword = globalVariable.getIsPassword();
if (ispassword == true) {
// String username = "/" + CurrentURL + "username" + ".txt";
String password = "/" + getLastAccessedBrowserPage() + ".password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, password, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setPassword(name);
//getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsPassword(false);
} else if (ispassword == false)
Log.i(TAG, "Wrong Input Type For Password.");
globalVariable.setPasswordButt(false);
// boolpassword=false;
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
Would you please tell me what should I do to fix this code?
Looking over the code I did not see anywhere you referenced anything from the Activity itself besides the application context so you can move the ListSpdFiles class to its own java file and pass it a context into the constructor when you make a new instance of it.
Put this class in a ListSpdFiles.java file so it is no longer an inner class.
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
Context applicationContext;
public ListSpdFiles(Context context, String initiator, String path) {
this.initiator = initiator;
this.path = path;
applicationContext = context.getApplicationContext();
}
// The rest of your code still goes here. Replace other calls to
// getApplicationContext() with the new applicationContext field
}
You can now use this class anywhere a Context is available. You create a new instance by doing:
ListSpdFiles listSpdFilesTask = new ListSpdFiles(context, "someInitiator", "somePath");
listSpdFilesTask.execute();

Flickr Sign out in Android programmatically

I am getting some issue when image is uploaded to flickr,oath token as well as user credentials get stored in the web browser cache.As a result am not being able to sign out from it.So when I go to flickr to upload my image again,it automatically uploads it rather than opening the login page.Now when I clear all the default browser cookies,then it ask for the login page.Is there any other way to sign out it automatically when I am redirected back to my application.Any kind of support will be appreciated.
Thanks in advance...
try this ,here....,FlickerHelper.java
public final class FlickrHelper {
private static FlickrHelper instance = null;
private static final String API_KEY = ""; //$NON-NLS-1$
public static final String API_SEC = ""; //$NON-NLS-1$
private FlickrHelper() {
}
public static FlickrHelper getInstance() {
if (instance == null) {
instance = new FlickrHelper();
}
return instance;
}
public Flickr getFlickr() {
try {
Flickr f = new Flickr(API_KEY, API_SEC, new REST());
return f;
} catch (ParserConfigurationException e) {
return null;
}
}
public Flickr getFlickrAuthed(String token, String secret) {
Flickr f = getFlickr();
RequestContext requestContext = RequestContext.getRequestContext();
OAuth auth = new OAuth();
auth.setToken(new OAuthToken(token, secret));
requestContext.setOAuth(auth);
return f;
}
public InterestingnessInterface getInterestingInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getInterestingnessInterface();
} else {
return null;
}
}
public PhotosInterface getPhotosInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getPhotosInterface();
} else {
return null;
}
}
}
FlickerjActivity.java
public class FlickrjActivity extends Activity {
public static final String CALLBACK_SCHEME = "flickrj-android-sample-oauth"; //$NON-NLS-1$
public static final String PREFS_NAME = "flickrj-android-sample-pref"; //$NON-NLS-1$
public static final String KEY_OAUTH_TOKEN = "flickrj-android-oauthToken"; //$NON-NLS-1$
public static final String KEY_TOKEN_SECRET = "flickrj-android-tokenSecret"; //$NON-NLS-1$
public static final String KEY_USER_NAME = "flickrj-android-userName"; //$NON-NLS-1$
public static final String KEY_USER_ID = "flickrj-android-userId"; //$NON-NLS-1$
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("flickImagePath")) {
path = getIntent().getStringExtra("flickImagePath");
}
}
new Thread() {
public void run() {
h.post(init);
};
}.start();
}
Handler h = new Handler();
Runnable init = new Runnable() {
#Override
public void run() {
OAuth oauth = getOAuthToken();
if (oauth == null || oauth.getUser() == null) {
OAuthTask task = new OAuthTask(getContext());
task.execute();
} else {
load(oauth);
}
}
};
private void load(OAuth oauth) {
if (oauth != null) {
UploadPhotoTask taskUpload = new UploadPhotoTask(this, new File(
path));
taskUpload.setOnUploadDone(new UploadPhotoTask.onUploadDone() {
#Override
public void onComplete() {
finish();
}
});
taskUpload.execute(oauth);
}
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
String scheme = intent.getScheme();
OAuth savedToken = getOAuthToken();
if (CALLBACK_SCHEME.equals(scheme)
&& (savedToken == null || savedToken.getUser() == null)) {
Uri uri = intent.getData();
String query = uri.getQuery();
String[] data = query.split("&"); //$NON-NLS-1$
if (data != null && data.length == 2) {
String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
String oauthVerifier = data[1]
.substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
OAuth oauth = getOAuthToken();
if (oauth != null && oauth.getToken() != null
&& oauth.getToken().getOauthTokenSecret() != null) {
GetOAuthTokenTask task = new GetOAuthTokenTask(this);
task.execute(oauthToken, oauth.getToken()
.getOauthTokenSecret(), oauthVerifier);
}
}
}
}
public void onOAuthDone(OAuth result) {
if (result == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
} else {
User user = result.getUser();
OAuthToken token = result.getToken();
if (user == null || user.getId() == null || token == null
|| token.getOauthToken() == null
|| token.getOauthTokenSecret() == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
return;
}
String message = String
.format(Locale.US,
"Authorization Succeed: user=%s, userId=%s, oauthToken=%s, tokenSecret=%s", //$NON-NLS-1$
user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
saveOAuthToken(user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
load(result);
}
}
public OAuth getOAuthToken() {
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
if (oauthTokenString == null && tokenSecret == null) {
// logger.warn("No oauth token retrieved"); //$NON-NLS-1$
return null;
}
OAuth oauth = new OAuth();
String userName = settings.getString(KEY_USER_NAME, null);
String userId = settings.getString(KEY_USER_ID, null);
if (userId != null) {
User user = new User();
user.setUsername(userName);
user.setId(userId);
oauth.setUser(user);
}
OAuthToken oauthToken = new OAuthToken();
oauth.setToken(oauthToken);
oauthToken.setOauthToken(oauthTokenString);
oauthToken.setOauthTokenSecret(tokenSecret);
return oauth;
}
public void saveOAuthToken(String userName, String userId, String token,
String tokenSecret) {
SharedPreferences sp = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(KEY_OAUTH_TOKEN, token);
editor.putString(KEY_TOKEN_SECRET, tokenSecret);
editor.putString(KEY_USER_NAME, userName);
editor.putString(KEY_USER_ID, userId);
editor.commit();
}
private Context getContext() {
return this;
}
}
GetAouthToken.java
public class GetOAuthTokenTask extends AsyncTask<String, Integer, OAuth> {
private FlickrjActivity activity;
public GetOAuthTokenTask(FlickrjActivity context) {
this.activity = context;
}
#Override
protected OAuth doInBackground(String... params) {
String oauthToken = params[0];
String oauthTokenSecret = params[1];
String verifier = params[2];
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthInterface oauthApi = f.getOAuthInterface();
try {
return oauthApi.getAccessToken(oauthToken, oauthTokenSecret,
verifier);
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(OAuth result) {
if (activity != null) {
activity.onOAuthDone(result);
}
}
}
Oauthtask.java
public class OAuthTask extends AsyncTask<Void, Integer, String> {
private static final Uri OAUTH_CALLBACK_URI = Uri
.parse(FlickrjActivity.CALLBACK_SCHEME + "://oauth"); //$NON-NLS-1$
private Context mContext;
private ProgressDialog mProgressDialog;
public OAuthTask(Context context) {
super();
this.mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext,
"", "Generating the authorization request..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
OAuthTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(Void... params) {
try {
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
OAUTH_CALLBACK_URI.toString());
saveTokenSecrent(oauthToken.getOauthTokenSecret());
URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
Permission.WRITE, oauthToken);
return oauthUrl.toString();
} catch (Exception e) {
return "error:" + e.getMessage(); //$NON-NLS-1$
}
}
private void saveTokenSecrent(String tokenSecret) {
FlickrjActivity act = (FlickrjActivity) mContext;
act.saveOAuthToken(null, null, null, tokenSecret);
}
#Override
protected void onPostExecute(String result) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (result != null && !result.startsWith("error")) { //$NON-NLS-1$
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(result)));
} else {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
}
}
}
uploadphototask.java
public class UploadPhotoTask extends AsyncTask<OAuth, Void, String> {
private final FlickrjActivity flickrjAndroidSampleActivity;
private File file;
public UploadPhotoTask(FlickrjActivity flickrjAndroidSampleActivity,
File file) {
this.flickrjAndroidSampleActivity = flickrjAndroidSampleActivity;
this.file = file;
}
private ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(flickrjAndroidSampleActivity,
"", "Uploading..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
UploadPhotoTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(OAuth... params) {
OAuth oauth = params[0];
OAuthToken token = oauth.getToken();
try {
Flickr f = FlickrHelper.getInstance().getFlickrAuthed(
token.getOauthToken(), token.getOauthTokenSecret());
UploadMetaData uploadMetaData = new UploadMetaData();
uploadMetaData.setTitle("" + file.getName());
return f.getUploader().upload(file.getName(),
new FileInputStream(file), uploadMetaData);
} catch (Exception e) {
Log.e("boom!!", "" + e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (response != null) {
Log.e("", "" + response);
} else {
}
if (monUploadDone != null) {
monUploadDone.onComplete();
}
Toast.makeText(flickrjAndroidSampleActivity.getApplicationContext(),
response, Toast.LENGTH_SHORT).show();
}
onUploadDone monUploadDone;
public void setOnUploadDone(onUploadDone monUploadDone) {
this.monUploadDone = monUploadDone;
}
public interface onUploadDone {
void onComplete();
}
}
mainactivty.java
public class MainActivity extends Activity {
File fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnFlickr = (Button) findViewById(R.id.btnFlickr);
btnFlickr.setOnClickListener(mFlickrClickListener);
Button btnPick = (Button) findViewById(R.id.btnPick);
btnPick.setOnClickListener(mPickClickListener);
}
View.OnClickListener mPickClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivityForResult(intent, 102);
}
};
View.OnClickListener mFlickrClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fileUri == null) {
Toast.makeText(getApplicationContext(), "Please pick photo",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(getApplicationContext(),
FlickrjActivity.class);
intent.putExtra("flickImagePath", fileUri.getAbsolutePath());
startActivity(intent);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 102) {
if (resultCode == Activity.RESULT_OK) {
Uri tmp_fileUri = data.getData();
((ImageView) findViewById(R.id.imageView1))
.setImageURI(tmp_fileUri);
String selectedImagePath = getPath(tmp_fileUri);
fileUri = new File(selectedImagePath);
Debug.e("", "fileUri : " + fileUri.getAbsolutePath());
}
}
};
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
usercard.java
public class UserCard {
public String name;
public String url;
public int upVotes;
public int downVotes;
}
debug.java
public class Debug {
private static final boolean DEBUG = true;
public static void e(String tag, String msg) {
if (DEBUG) {
Log.e(tag, msg);
}
}public static void i(String tag, String msg) {
if (DEBUG) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (DEBUG) {
Log.w(tag, msg);
}
}
public static void d(String tag, String msg) {
if (DEBUG) {
Log.d(tag, msg);
}
}
}

Categories

Resources