how to Parse user-selected data in an activity - android

i am trying to parse the json data,in my application,i have 2 dropdown box from which user select the country name to which he wants to convert the data.and the amount he want to convert is passed into the url. and i am using AsyncHttpClient lib to read the data,before using it on different api it work perfectly fine ,but when i change my api it start run the failure method.first i thought i passed wrong url.,but on toast i get to knw i am passing correct url of the api.
what is the problem can anyone tell me..??
Thanking you in advance.
private String API_URL = "http://devel.farebookings.com/api/curconversor/";
public void onClick(View arg0) {
final String url1 = API_URL + t1.toString() + "/" + t2.toString() + "/"
+ usdValue.getText().toString() + "/" + "json";
Toast.makeText(getApplicationContext(), url1.toString(),
Toast.LENGTH_LONG).show();
if (!usdValue.getText().toString().equals("")) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(url1, new AsyncHttpResponseHandler() {
#Override
public void onFailure(Throwable arg0, String arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
Toast.makeText(getApplicationContext(),
"unsuccess", Toast.LENGTH_LONG).show();
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
super.onFinish();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getApplicationContext(), "start",
Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(String response) {
Log.i("CHACHING", "HTTP Sucess");
Toast.makeText(getApplicationContext(), "success",
Toast.LENGTH_LONG).show();
try {
JSONObject jsonObj = new JSONObject(response);
Double usds = Double.valueOf(usdValue.getText()
.toString());
Double rate = jsonObj.getDouble("to_amount");
Toast.makeText(getApplicationContext(),
String.valueOf(rate), Toast.LENGTH_LONG)
.show();
double the_result = usds * rate;
ConvertedFrom.setText(usdValue.getText()
.toString()
+ " "
+ ConvertedFromCurr.getSelectedItem()
.toString() + " = ");
ConvertedTo.setText(String.valueOf(the_result)
+ " "
+ ConvertedToCurr.getSelectedItem()
.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} else {
Toast.makeText(getApplicationContext(),
"Please enter a Amount value!", Toast.LENGTH_LONG)
.show();
}

for cross domain api calls you must use jsonp.
This is an example in javascript
$.ajax({
url: "http://devel.farebookings.com/api/curconversor/EUR/GBP/1/",
dataType: 'jsonp',
success: function (data) {
alert(data.GBP);
}
});

Related

Get Video Title inside onLoaded() method

I know that I can get Video Id inside onLoaded() method of YoutubePlayer StateChangeListener, like this:
#Override
public void onLoaded(String s) {
// 's' contains Video ID
}
But now just for an experiment, I want to know How could I get Video Title...
Updated
#Override
public void onLoaded(String s) {
// 's' contains Video ID
Toast.makeText(YouTubeViewActivity.this, s, Toast.LENGTH_SHORT).show();
String youtubeUrl = "https://www.youtube.com/watch?v=" + s;
Toast.makeText(YouTubeViewActivity.this, youtubeUrl, Toast.LENGTH_SHORT).show();
try {
if (youtubeUrl != null) {
Toast.makeText(YouTubeViewActivity.this, "Found URL", Toast.LENGTH_SHORT).show();
URL embededURL = new URL("http://www.youtube.com/oembed?url=" + youtubeUrl + "&format=json");
strTitle = new JSONObject(IOUtils.toString(embededURL)).getString("title");
Toast.makeText(YouTubeViewActivity.this, strTitle, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here how its done
String video_title;
#Override
public void onLoaded(String s) {
String youtubeUrl = "https://www.youtube.com/watch?v=" + s;
try {
if (youtubeUrl != null) {
URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
youtubeUrl + "&format=json");
video_title = new JSONObject(IOUtils.toString(embededURL)).getString("title");
}
} catch (Exception e) {
e.printStackTrace();
}
}

Image is not attached in quickblox for android

I have made a demo for sending image to private chat using QuickBlox, I am struggling to attach an image with the chat message, I have gone through its document and have used the below Links, with no luck
Attach an image
My code is as below:
chatMessage = new QBChatMessage();
sendButton = (Button) findViewById(R.id.chatSendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String messageText = messageEditText.getText().toString();
if (TextUtils.isEmpty(messageText)) {
return;
}
// Send chat message
//
// send a message
// ...
int fileId = R.raw.ic_launcher;
InputStream is = ChatActivity.this.getResources()
.openRawResource(fileId);
File file = FileHelper.getFileInputStream(is,
"sample_file.png", "myFile");
Boolean fileIsPublic = true;
QBContent.uploadFileTask(file, fileIsPublic, messageText,
new QBEntityCallbackImpl<QBFile>() {
#Override
public void onSuccess(QBFile qbFile, Bundle params) {
String publicUrl = qbFile.getPublicUrl();
System.out
.println("==========image uploaded success++++++++"
+ publicUrl);
id = qbFile.getId();
System.out
.println("===================image id+++++++++++"
+ id + "");
}
#Override
public void onError(List<String> errors) {
System.out
.println("==========image uploaded Errors++++++++"
+ errors.toString());
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progress) {
}
});
QBAttachment atach = new QBAttachment("image");
atach.setId(id+"");
ArrayList<QBAttachment> aryatch = new ArrayList<QBAttachment>();
aryatch.add(atach);
chatMessage.setAttachments(aryatch);
chatMessage.setBody(messageText);
chatMessage.setProperty(PROPERTY_SAVE_TO_HISTORY, "1");
chatMessage.setDateSent(new Date().getTime() / 1000);
try {
chat.sendMessage(chatMessage);
} catch (XMPPException e) {
Log.e(TAG, "failed to send a message", e);
} catch (SmackException sme) {
Log.e(TAG, "failed to send a message", sme);
}
messageEditText.setText("");
if (dialog.getType() == QBDialogType.PRIVATE) {
showMessage(chatMessage);
}
}
});
Well it clear where the mistake is
your id is null here
atach.setId(id+"");
because it will != nil only in onSuccess block of uploadFileTask
So the right way is to forward all attachments logic inside onSuccess block of uploadFileTask
Because these QuickBlox request are asynchronous

android: How to wait for listener to complete before continuing?

I'm using the socialAuth plugin to connect a user to linkdin within my app. I have the connection set up correctly and retrieves data. However, I'm unsure how I can get my main activity to wait until the socialAuthListeners have fired and finished. I know a little about threading but I haven't used it with listeners before. Here's my code:
public class LinkdinAuth {
private static final String TAG = "TEST";
// SocialAuth Components
SocialAuthAdapter adapter;
ProgressDialog mDialog;
private Context context;
private boolean loggedIn = false;
private Bundle LinkdinData;
public LinkdinAuth(Context C){
this.context = C;
LinkdinData = new Bundle();
adapter = new SocialAuthAdapter(new ResponseListener());
}
public void adapterAuthorize(View v){
adapter.authorize(v.getContext(), Provider.LINKEDIN);
}
private final class ResponseListener implements DialogListener
{
public void onComplete(Bundle values) {
String providerName = values.getString(SocialAuthAdapter.PROVIDER);
Log.d("Main", "providername = " + providerName);
mDialog = new ProgressDialog(context);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setMessage("Loading...");
//Get profile information
adapter.getUserProfileAsync(new ProfileDataListener());
// get Job and Education information
mDialog.show();
adapter.getCareerAsync(new CareerListener());
loggedIn = true;
Log.d("Main", "LOGGED IN = " + loggedIn );
Toast.makeText(context, providerName + " connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onBack() {
Log.d("Main", "Dialog Closed by pressing Back Key");
}
#Override
public void onCancel() {
Log.d("Main", "Cancelled");
}
#Override
public void onError(SocialAuthError e) {
Log.d("Main", "Error");
e.printStackTrace();
}
}
// To receive the profile response after authentication
private final class ProfileDataListener implements SocialAuthListener<Profile> {
#Override
public void onExecute(String provider, Profile t) {
Log.d("Sign Up", "Receiving Data");
mDialog.dismiss();
Profile profileMap = t;
LinkdinData.putString("Validated ID", profileMap.getValidatedId() );
LinkdinData.putString("First Name", profileMap.getFirstName());
LinkdinData.putString("Last Name", profileMap.getLastName());
LinkdinData.putString("Email", profileMap.getEmail());
LinkdinData.putString("Country", profileMap.getCountry());
LinkdinData.putString("Language", profileMap.getLanguage());
LinkdinData.putString("Location", profileMap.getLocation());
LinkdinData.putString("Profile Image URL", profileMap.getProfileImageURL());
}
#Override
public void onError(SocialAuthError arg0) {
// TODO Auto-generated method stub
}
}
private final class CareerListener implements SocialAuthListener<Career> {
#Override
public void onExecute(String provider, Career t) {
Log.d("Custom-UI", "Receiving Data");
mDialog.dismiss();
Career careerMap = t;
//get education
Log.d("Main", "Education:");
if(careerMap.getEducations() != null){
for(Education E: careerMap.getEducations()){
Log.d("Main", "School = " +E.getSchoolName() );
Log.d("Main", "Major = " + E.getFieldOfStudy() );
Log.d("Main", "Degree = " + E.getDegree() );
Log.d("Main", "Start Date = " + E.getStartDate() );
Log.d("Main", "End Date = " + E.getEndDate() );
}
}
Log.d("SignUp", "Career");
if(careerMap.getPositions() != null){
for(Position P: careerMap.getPositions()){
LinkdinData.putString("Company Name", P.getCompanyName() );
LinkdinData.putString("Job Title", P.getTitle() );
Log.d("Main", "Industry = " + P.getIndustry() );
Log.d("Main", "Start Date = " + P.getStartDate() );
Log.d("Main", "End Date = " + P.getEndDate() );
}
}
}
#Override
public void onError(SocialAuthError e) {
}
}
public boolean isLoggedIn(){
return loggedIn;
}
public Bundle getLinkdinData(){
return LinkdinData;
}
So, as you can see. I have 2 listeners that get data after authorization goes through. And my main activity makes creates an instance, calls the adapterAuthroizeMethod and then if the user logs in a flag is set. Then getLinkedData is called. However I would like it to wait until I know the listeners have fired before calling getlinkdinData. Here's what my Main Activity does after a button press:
L.adapterAuthorize(v);
loggedInWithLinkdin = L.isLoggedIn();
Bundle B = L.getLinkdinData();
Intent i = new Intent(getBaseContext(), UserRegistration.class);
i.putExtra("linkdin bundle", B);
//startActivity(i);
Any ideas?
thanks
Well, not a recommend solution but more of a hack.
Here is what you can do.
Wrap the aync call around this construct :
AtomicBoolean done = new AtomicBoolean(false);
Global ans; // the return value holder
try{
result = someAsyncCall(query, new Thread()); // this new thread is for listener callback
result.setResultListener(result -> {
// do something with result.
ans = result.getAns() ; // set global ans
done.set(true);
synchronized (done) {
done.notifyAll(); // notify the main thread which is waiting
}
});
}
catch (Exception e ) {
Log(e);
}
synchronized (done) {
while (done.get() == false) {
done.wait(); // wait here until the listener fires
}
}
return ans; // return global ans

Restoring inapp purchased items in android

I'm trying to give the user the ability to restore his inapp purchased items from my application.
I'm using the following code:
ServiceConnection mServiceConn = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService = IInAppBillingService.Stub.asInterface(service);
Log.d("TEST", "mService ready to go!");
checkownedItems();
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
mService = null;
}
};
public void checkownedItems()
{
try
{
String base64EncodedPublicKey = "MY_KEY";
// Log.d("getPackageName ", "Items Owned: " + getPackageName());
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
if(ownedItems.getInt("RESPONSE_CODE") == 0)
{
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
//ownedSkus.toArray();
ownedSkus.add("test");
for (int n=0;n<ownedSkus.size();n++)
{
Log.d("Items: ", "Items: " + ownedSkus.get(n));
}
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
//Log.d("Items Owned: ", "Items Owned: " + ownedSkus.size()); toast
Log.d("Data List: ", "Data List: " + purchaseDataList.size());
Log.d("signature List: ", "signature List: " + signatureList);
Log.d("continuation Token: ", "continuation Token: " + continuationToken);
if(purchaseDataList.size() > 0)
{
//Item(s) owned
Log.d("purchaseDataList: ", "purchaseDataList: " + purchaseDataList.size());
for(int i=0; i<purchaseDataList.size(); ++i)
{
String sku = ownedSkus.get(i);
/* String xx = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.d(TAG, "INAPP_CONTINUATION_TOKEN: " + xx);
*/
Log.d(TAG, "Item_SKU: " + "consume");
String bookpdf = "http://www.mybook.com/"+sku+ ".pdf";
String Bookvalue= sku.substring(sku.lastIndexOf(".")+1);
downloadAndEncrypt(bookpdf,Bookvalue + ".pdf");
Log.d(TAG, "Item_SKU-Download: "
+ "Download Complete");
Log.d("OWNED_ITEMS_FINAL_SIZE","OWNED_ITEMS_FINAL_SIZE: " + ownedItems.size() );
Log.d("OWNED_ITEMS_FINAL_LIST","OWNED_ITEMS_FINAL_LIST: " + ownedItems.keySet());
Log.d("ownedSkus1","ownedSkus1: " + ownedSkus.size() );
Log.d("ownedSkus2","ownedSkus2: " + ownedSkus.toString());
Log.d("ownedSkus3","ownedSkus3: " + ownedSkus);
//Log.d("testtt","testtt " + "INAPP_PURCHASE_ITEM_LIST".length());
/* String value = ownedItems.getString("INAPP_PURCHASE_ITEM_LIST");
Log.d("my_test","my_test: " + value); */
}
}
else
{
//Item(s) not owned
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener()
{
#Override
public void onIabSetupFinished(IabResult result) {
// TODO Auto-generated method stub
if(!result.isSuccess())
{
Log.d("TEST", "In-app Billing setup failed: " + result);
}
else
{
Log.d("TEST", "In-app Billing is set up OK");
}
}
});
}
}
else
{
//Error checking owned items
}
}
catch(RemoteException e)
{
e.printStackTrace();
}
}
#Override
public void onDestroy()
{
super.onDestroy();
if(mServiceConn != null)
{
//unbindService(mServiceConn);
}
}
Note that I'm using the correct base64EncodedPublicKey key of my application.
The problem now is the above code only returns the first inapp item purchased from my application. I tried much everything possible with that piece of code, and it always returns only the first item when trying to log the output results.
Please advise.
Thank you.
Here is the code you are looking for:
private void queryUserPurcahses()
{
mHelper.queryInventoryAsync(mGotInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mGotInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else {
boolean is_purchased_1 = inventory.hasPurchase(product_1_ID);
boolean is_purchased_2 = inventory.hasPurchase(product_2_ID);
}
}
};
I figured it out. I was consuming the purchased items in my code. What I did I just commented the consumeitem() function, and when I published my apk (it has to be published to return all the purchased items don't know why!) it worked like a charm and restored all my item that I purchased after commenting the consumeitem().
Thank you all.

My TextView not update

Here is my code
this is my InstantMessage application
the method processMessage will automatically do when the applicaiton have new message
My problem is the textview not work when method processMessage do but when i send message when textview update by both use the same updateChat method
#Override
public void onClick(View v) {
String message = text.getText().toString();
try {
Log.e("On Click", message + " : " + contact);
chat.sendMessage(message);
message = username + " : " + message;
updateChat(message);
} catch (XMPPException e) {
e.printStackTrace();
}
}
public void updateChat(String message){
chatLog += message + "\n";
chatBox.setText(chatLog);
}
#Override
public void processMessage(org.jivesoftware.smack.Chat arg0, Message arg1) {
String temp = InstantMessage.usernameCutter(arg0.getParticipant()) + " : "+ arg1.getBody();
Log.e("ChatPage ", "ProcessMessage");
updateChat(temp);
}
Are processMessage method running on UI thread?
if not, use this construction
final String temp = InstantMessage.usernameCutter(arg0.getParticipant()) + " : "+ arg1.getBody();
runOnUiThread(new Runnable() {
public void run() {
updateChat(temp);
}
});

Categories

Resources