Display info from API to widget using OkHttp - java

I have such an OkHttp code to retreive data from OpenWeather API:
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new okhttp3.Request.Builder().url(url).build();
AsyncTask.execute(() -> {
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
if(response.code() == 200) {
Log.d("weather", "200");
JSONArray array;
try {
JSONObject mObj = new JSONObject(response.body().string());
array = mObj.getJSONArray("weather");
widgetView.setTextViewText(R.id.weatherTextView, array.getJSONObject(0).getString("main"));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
It's located in my Widget class in void updateWidget, which is called from onUpdate() void. But the problem is that this OkHttp code just doesn't get executed.
What can cause this problem?

Related

Web API call too slow

I have an android app that most of its feature consumes an API. My client complained that the retrieving of data from the web api is very slow. I wonder what's causing this.
Here's a basic structure of how I do my calls:
String returnString = "";
token = tokenBuilder.generateToken("Customers/All");
try {
HttpGet request = new HttpGet(apiUrl + "CustomerRewards/All?customerId=" + id);
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
request.setHeader("AccountId", headerAccountId);
request.setHeader("StoreId", headerStoreId);
request.setHeader("AppKey", headerAppKey);
request.setHeader("Token", token);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
String responseString = EntityUtils.toString(response.getEntity());
Log.i("Api Message", responseString);
returnString = responseString;
} catch (Exception e) {
returnString = e.getMessage();
}
return returnString;
I'm calling this method from a progress dialog in order to display a loader while, retrieving data from the web API. Is there a better way to do this? Or is somewhat my android code affects its performance?
Here's the code on the calling progress dialog.
rewardsErrorMessage = "";
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading info ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.setCancelable(false);
progressBar.show();
apiLoadStatus = false;
new Thread(new Runnable() {
public void run() {
while (!apiLoadStatus) {
apiLoadStatus = RewardApi();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (apiLoadStatus) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.dismiss();
}
}}).start();
progressBar.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
SetValues();
}
});
And here's the method that actually calls the api class that connects to the web api
ApiConnection api = new ApiConnection();
try {
Log.i("CustomerId", customerInfos.getString("customer_id", ""));
transactionMessage = api.GetTransactions(customerInfos.getString("customer_id", ""));
availableRewardsMessage = api.GetCustomerRewards(customerInfos.getString("customer_id", ""));
try
{
if(transactionMessage.contains("Timestamp"))
{
Log.i("Transaction", "Success");
GetPoints(transactionMessage);
}
if(!availableRewardsMessage.equals("[]") && !availableRewardsMessage.equals("[]"))
{
JSONObject rewardsJson = new JSONObject(availableRewardsMessage);
availableRewardsMessage = rewardsJson.getString("AvailableRewards");
hasRewards = true;
}
return true;
}
catch(Exception e)
{
rewardsErrorMessage = transactionMessage.replace('[', ' ').replace(']', ' ').replace('"', ' ');
}
} catch(Exception e) {
e.printStackTrace();
rewardsErrorMessage = e.getMessage();
return true;
}
return true;
As you notice, I have two api calls here.
I really would like to speed up the retrieving of data. Or is the api I'm consuming that slow? Any ideas guys? Thanks!
As you're probably aware, there are a number of factors that can affect HTTP service calls, of which the client code is only one:
Network speed and latency
Server availability and load
Size of data payload
Client device resources
Client code
You really need to determine where the bottleneck(s) are in order to know where to try to optimize. Additionally, you should make sure that the server is using Gzip to compress the payload and add the following to your client code:
request.setHeader("Accept-Encoding", "gzip");

Why same notification is pushed many times to android and iphone devices

I have used javapns for pushing notifications to ios and android.gcm.server to push notification for android devices. But when I sent one notifications to many devices each device get multiple number of copies of the notification sent. Sometimes this number is 2 and sometimes 3. Hardly it delivers only one which I expect always. Any Ideas ?
My code is as below
public void pushNotificationsToAndroid(String pushMessage,
String contentType, String content, String notification_id,
List<String> devices) {
try {
Sender sender = new Sender(
properties
.getProperty("notification.android.senderIdDemo"));
com.google.android.gcm.server.Message message = new com.google.android.gcm.server.Message.Builder()
.collapseKey("1").timeToLive(3).delayWhileIdle(true)
.addData("message", pushMessage)
.addData("content_type", contentType)
.addData("content", content)
.addData("notification_id", notification_id).build();
MulticastResult result = sender.send(message, devices, 1);
if (result.getResults() == null) {
System.out.println(result.getFailure());
logger.debug("getFailure() of sender.send() method :",
result.getFailure());
}
} catch (Exception exception) {
logger.error("erorr push notification ");
}
System.out.println("sent not at " + new Date());
logger.debug(
"exit pushNotificationsToAndroid() method : current time is ",
new Date());
}
public void pushNotificationsToIOS(String pushMessage, String contentType,
String content, String notification_id, List<String> devices)
{
boolean production = true;
String password = properties
.getProperty("notification.ios.password");
String keyStroke = properties
.getProperty("notification.ios.certFileName");
AppleNotificationServer jksServer = null;
try {
jksServer = new AppleNotificationServerBasicImpl(keyStroke,
password, ConnectionToAppleServer.KEYSTORE_TYPE_JKS,
production);
} catch (KeystoreException keystoreException) {
logger.error("erorr creating jksServer");
}
PushNotificationPayload payload = PushNotificationPayload.complex();
try {
payload.addAlert(pushMessage);
} catch (JSONException e2) {
logger.error("erorr creating payload alert");
}
try {
payload.addCustomDictionary("content_type", contentType);
} catch (JSONException e1) {
logger.error("erorr creating payload content_type");
}
try {
payload.addCustomDictionary("content", content);
} catch (JSONException e1) {
logger.error("erorr creating payload content");
}
try {
payload.addCustomDictionary("notification_id", notification_id);
} catch (JSONException e1) {
logger.error("erorr creating payload notification_id");
}
PushNotificationManager pushManager = new PushNotificationManager();
try {
pushManager.initializeConnection(jksServer);
} catch (CommunicationException | KeystoreException e) {
logger.error("erorr connecting Server");
}
try {
List<PushedNotification> notifications = pushManager
.sendNotifications(payload, Devices.asDevices(devices));
} catch (CommunicationException | KeystoreException e) {
logger.error("erorr push notifications");
}
}
In android official site says about some reasons for duplicate message conditions .

Error Parse JSON Response String Android

I have a response String from an API service like this :
{"id":"login","status":"true"}
and This is the way to parse Response String to get Value from Key "Status"
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
}
catch(JSONException e){
e.printStackTrace();
}
JSONArray innerJsonArray = null;
try {
innerJsonArray = jsonObj.getJSONArray("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObject = null;
try {
jsonObject = innerJsonArray.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println(jsonObject.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and I've got error
"org.json.JSONArray cannot be converted to JSONObject"
Anyone can give me suggestion?
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
System.out.println(jsonObj.getString("status"));
}
catch(JSONException e){
e.printStackTrace();
}
You do not need to bother with any other arrays.
In which line you get the exception ? In any way may be you should use
jsonObj =JSONObject.fromObject(responseString);
Kindly try the snippet code below. Try this link for gaining better knowledge about parsing an JSON response.
JSONObject jObj;
try {
jObj = new JSONObject(responseString);
Log.i("id==", jObj.getString("id"));
Log.i("status==", jObj.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

android: google APi OAuth 2.0 - error 400 getting user info

I have the following on a web servlet:
EDITED:
public String tryGoogleAuthentication(String auth_token){
HttpURLConnection connection = null;
try {
//connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2v1/tokeninfo?access_token={"+auth_token+"}")).openConnection();
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/user info")).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer {"+auth_token+"}");
connection.setRequestProperty("Host", "googleapis.com");
//read response
String response = fromInputStreamToString(connection.getInputStream());
System.out.println(response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return CONST.STATUS_OK;
}
In android:
private void googleAuthenticate(){
try {
mOAauthHelper = new OAuthHelper("something.net", "xxxxxxxxxx",
"https://www.googleapis.com/auth/userinfo.profile", "alex://myScheme");
String uri = mOAauthHelper.getRequestToken();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(uri)));
//Intent i = new Intent(this, GoogleOAUTHActivity.class);
//i.putExtra(GoogleOAUTHActivity.GOOGLE_OAUTH_ENDPOINT_KEY, uri);
//startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
}
}
and
#Override
protected void onNewIntent(Intent intent) {
//super.onNewIntent(intent);
Uri uri = intent.getData();
String oauthToken = uri.getQueryParameter("oauth_token");
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
if(oauthToken != null){
authorizeGoogleSessionToServer(oauthToken);
}
}
After this, I send the request token to my servlet where I tried to get user profile, but with no success.
Could you please tell me what's wrong and why I'm getting error 400 from google?
Thanks.
Unfortunately, I can see a few issues with this already
you should never have curly braces in your URL or even in the Bearer header as stated in the draft.
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/userinfo?access_token={"+auth_token+"}")).openConnection()
400 means that you're missing something in your request, there is probably more information about it in the same response as specific error node.
Finally, take care, oauth_verifier param is from OAuth 1.
I suggest you test your request URL's, using the Google OAuth2 playground
Good luck!

How to append listview items from the Internet

I'm still struggling to find an answer to my question. I want to download 3 strings for each item in the listview to the phone. I know how to get all the data from the server, just not how to append the data to the litview, I'm really annoyed and this problem is dragging me down.
My Code:
public class ChatService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
try {
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CheckLogin();
private void CheckLogin() {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//put intent here(21/3/12);
} else {
Log.w("HttpPost", "FALSE");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
private void ContactsandIm() throws URISyntaxException, ClientProtocolException, IOException {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
//now we'll return the data that the PHP set from the MySQL Database.
if (in.equals("True")); {
Toast.makeText(this,"yay", Toast.LENGTH_LONG).show();
}
}
// end bracket for "ContactsandIm"
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Use an ArrayAdapter on your list, and add items to this adapter, then call notifyDatasetChanged on it, and zou
First of all when we connect to Server using the Network Threads, then you should go for AsyncTask or Handlers. Which is specially used for handling such Threads.
ListView can be created by using default Listview ans also the Custom Listview where we can design our own Row design in the Row.xml and the same design will be used for all the rows.
If you want move forward or go for some advanced Listview then even we can use 'n' number of designs for different rows.
Here in your case, You should use a AsyncTask for fetching the data and use the Listview for displaying rows.
You can get more information from the below link.
https://docs.google.com/leaf?id=0B2qCFbmeiTFxN2ViZjVlOTUtNmY3ZS00NThhLTg3N2UtYjVkYjgyM2Y4MWUy&hl=en&authkey=COeP8JYN

Categories