I have the below method:
public String tryGoogleAuthentication(String auth_token){
ContactsService contactsService = new ContactsService(".....");
contactsService.setUserToken(auth_token);
IFeed feed = null;
try {
feed = contactsService.getFeed(new URL("https://www.google.com/m8/feeds/ contacts/default/full?max-results=10000"), ContactFeed.class);
} catch (IOException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (ServiceException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (NullPointerException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
}
if (feed == null)
return "";
String externalId = feed.getId();
IPerson person = feed.getAuthors().get(0);
String email = person.getEmail();
String name = person.getName();
String nameLang = person.getNameLang();
System.out.println("externalId: " + externalId);
System.out.println("email: " + email);
System.out.println("name: " + name);
System.out.println("nameLang: " + nameLang);
return CONST.STATUS_OK;
}
and I get the error:
java.lang.NullPointerException: No authentication header information
at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96)
at com.google.gdata.util.AuthenticationException.<init>(AuthenticationException.java:67)
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:998)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:631)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at ro.servlet.data.ClientAuthenticator.tryGoogleAuthentication(ClientAuthenticator.java:96)
....
Please tell what shoud I set to contactsService(except setUserToken) in order to work proper?
I don't used gData before(I'm an android/iPhone developer) - I took the auth string from the android device(by letting the user to confirm this) and pass it over a secured channel to my server - now I want to gather some data about this Contact(first, last name and provider uid - I need for a database with users in my app).
I really need to finish this task, so please, if anyone knows how this can be fixed, help me !
The below class describe the way I get the auth string from the android device.
package ro.locationsApp.android.login;
import java.io.IOException;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import ro.locationsApp.android.CONST;
import android.R;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class AccountList extends ListActivity {
protected AccountManager accountManager;
protected Intent intent;
DefaultHttpClient http_client = getThreadSafeClient();
private Account currentUsedAccount;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountManager = AccountManager.get(getApplicationContext());
Account[] accounts = accountManager.getAccountsByType("com.google");
String[] names = new String[accounts.length];
for (int i = 0; i < accounts.length; i++) {
System.out.println(accounts[i].name);
names[i] = accounts[i].name;
}
this.setListAdapter(new ArrayAdapter<String>(this,
R.layout.simple_list_item_1, names));
}
#SuppressWarnings("unchecked")
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Account account = accountManager.getAccountsByType("com.google")[position];
accountManager.getAuthToken(account, "ah", false,
new GetAuthTokenCallback(), null);
currentUsedAccount = account;
}
public static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
#SuppressWarnings("rawtypes")
private class GetAuthTokenCallback implements AccountManagerCallback {
public void run(AccountManagerFuture result) {
Bundle bundle;
try {
bundle = (Bundle) result.getResult();
Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (intent != null) {
// User input required
startActivity(intent);
} else {
onGetAuthToken(bundle);
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
protected void onGetAuthToken(Bundle bundle) {
final String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
System.out.println("AUTH TOKEN: " + auth_token);
new Thread(new Runnable() {
#Override
public void run() {
try {
JSONObject request = new JSONObject();
request.put(CONST.ID_ATTR, CONST.ID_GOOGLE_AUTH);
JSONObject body = new JSONObject();
body.put(CONST.GOOGLE_AUTH_TOKEN, auth_token);
request.put(CONST.DATA_ATTR, body);
JSONObject response = new JSONObject(new RequestHandler().request(DataSource.LOCATIONS_SERVER_URL, request.toString()));
String bodyResponse = response.optJSONObject(CONST.DATA_ATTR).optString(CONST.STATUS_ATTR);
if(bodyResponse.equals(CONST.STATUS_OK)){
}
else if(bodyResponse.equals(CONST.GOOGLE_AUTH_INVALID_TOKEN)){
runOnUiThread(new Runnable() {
#SuppressWarnings("unchecked")
public void run() {
invalidateUserToken(auth_token);
accountManager.getAuthToken(currentUsedAccount, "ah", false,
new GetAuthTokenCallback(), null);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public void invalidateUserToken(String token){
AccountManager accountManager = AccountManager.get(this);
accountManager.invalidateAuthToken("com.google", token);
}
}
Thanks,
Alex.
accountManager.getAuthToken(currentUsedAccount, "ah", false,
new GetAuthTokenCallback(), null);
Your accountTokenType is wrong. The Contacts API scope is http://www.google.com/m8/feeds/ for v2 or https://www.google.com/m8/feeds/ for v3
Related
hey i've written a server in app engine. i've used so far the HttpDefaultClient in order to do so.
protected Boolean doInBackground(String... tokens) {
try {
// Don't follow redirects
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpGet httpGet = new HttpGet("http://" + appId
+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);
response = httpclient.execute(httpGet);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
if(response.getStatusLine().getStatusCode() != 302){
// Response should be a redirect
return false;
}
//check if we received the ACSID or the SACSID cookie, depends on http or https request
for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
} finally {
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
return false;
}
does any one knows how do i get the same coockie via other connection??
i know how to recieve the token : by httpUrlconnection:
private String getAuthToken() {
AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(
mAccount, "ah", null, true, null, null);
Bundle bundle;
try {
bundle = future.getResult(10, TimeUnit.SECONDS);
} catch (OperationCanceledException | IOException | AuthenticatorException e) {
Log.e(TAG, "Unexpected error while getting an auth token: ", e);
throw new RuntimeException(e);
}
return bundle.getString(AccountManager.KEY_AUTHTOKEN);
}
:
private URL getAuthUrl(String token) {
api = "http://" + appId+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + token;
String path = Uri.parse(mBaseUrl)
.buildUpon()
.appendEncodedPath("_ah/login")
.appendQueryParameter("continue", mBaseUrl)
.appendQueryParameter("auth", token)
.build()
.toString();
try {
return new URL(api);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
private String getAuthCookie(URL authUrl) {
HttpURLConnection conn = ((HttpURLConnection) authUrl.openConnection());
String cookie = conn.getHeaderField("Set-Cookie"); // returns null!
return cookie;
}
any idea why?? and how to fix it?
i've recieved : NID=72=bIkTJcJ1o1iX988WeqjEhAELifvxtDOoD0sIe-VqZQK0ToezFvDSx0ctjko8KZyJYA7S1aAyl-7WYh6Wue-UHhSJYgXSQg9NrFXEMjUujONGIomcrSsX5373zYb59oBI; expires=Thu, 07-Apr-2016 22:56:30 GMT; path=/; domain=.google.com; HttpOnly
answer :
package com.example.daniel.testing9;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* AppEngine authentication with a Google account works as follows:
1. First we obtain a token from the Google account on device.
2. We authenticate with Appengine at /_ah/login URL
3. If authentication is successful, an ACSID (SACSID for https) cookie is set
4. If the token has expired (default 24 hours), then we invalidate it and try again.
5. Set the [S]ACSID cookie on future requests, e.g.:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
*/
public class AuthHelper {
private static final String TAG = "auth";
public static boolean finished = false;
private final AccountManager mAccountManager;
private final Account mAccount;
private final String mBaseUrl;
private static String _cookie = null;
String appId;
String api;
String token;
static AuthHelper instance = null;
public static AuthHelper getInstance() {
if (instance == null) {
AccountManager accountManager = AccountManager.get(MainActivity.context.getApplicationContext());
accountManager = AccountManager.get(MainActivity.context.getApplicationContext());
// assembling all gmail accounts
Account[] accounts = accountManager.getAccountsByType("com.google");
// add all gmail accounts :
ArrayList<String> accountList = new ArrayList<String>();
for (Account account : accounts) {
accountList.add(account.name);
}
Account account = accounts[0];
instance = new AuthHelper(accountManager, account, Constants.SERVER_REQUESTS.MY_APP_WEBSITE,
Constants.SERVER_REQUESTS.MY_APP_ID);
}
return instance;
}
public AuthHelper(#NonNull AccountManager accountManager,
#NonNull Account account,
#NonNull String appspotBaseUrl, String appid) {
mAccountManager = accountManager;
mAccount = account;
mBaseUrl = appspotBaseUrl;
this.appId = appid;
}
public String getAuthPath(String url) {
if (token == null) {
token = getAuthToken();
}
return api = Constants.SERVER_REQUESTS.MY_APP_WEBSITE+"_ah/login?continue="+url+"&auth=" + token;
}
public String authenticateAndGetCookie() {
for (int i = 0; i < 2; i++) {
token = getAuthToken();
URL authUrl = getAuthUrl(token);
String cookie = getAuthCookie(authUrl);
if (cookie != null) {
_cookie = cookie;
return cookie;
}
invalidateAuthToken(token);
}
return null;
}
private String getAuthCookie(URL authUrl) {
try {
HttpURLConnection conn = ((HttpURLConnection) authUrl.openConnection());
return conn.getHeaderField("Set-Cookie");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private URL getAuthUrl(String token) {
api = "http://" + appId+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + token;
String path = Uri.parse(mBaseUrl)
.buildUpon()
.appendEncodedPath("_ah/login")
// .appendQueryParameter("continue", mBaseUrl)
.appendQueryParameter("auth", token)
.build()
.toString();
try {
return new URL(path);
//return new URL(api);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
private String getAuthToken() {
AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(
mAccount, "ah", null, true, null, null);
Bundle bundle;
try {
bundle = future.getResult(10, TimeUnit.SECONDS);
} catch (OperationCanceledException | IOException | AuthenticatorException e) {
Log.e(TAG, "Unexpected error while getting an auth token: ", e);
throw new RuntimeException(e);
}
return bundle.getString(AccountManager.KEY_AUTHTOKEN);
}
private void invalidateAuthToken(String token) {
mAccountManager.invalidateAuthToken(mAccount.type, token);
finished = true;
}
}
I'm trying to implement a WebDav client in Android. For this purpose, I'm using a version of JackRabbit modified for Android that I got here (version 2.2.6).
I want to connect to my account in box.com and upload a file. Sincerely, I don't mind box or any other, i just happened to use this one.
Well, continuing with box.com, according to (this link)[https://support.box.com/hc/en-us/articles/200519748-Does-Box-support-WebDAV-] I should used "https://dav.box.com/dav" as server.
I have followed these links to build my code:
http://jackrabbit.apache.org/api/2.1/org/apache/jackrabbit/webdav/client/methods/package-summary.html
http://wiki.apache.org/jackrabbit/WebDAV
I'm getting an UnknownHostException sayingo my the URL I'm using for the server ("https://dav.box.com/dav") couldn't be found.
Any idea why does it not work? Otherwise, have you tried with other server and succeeded?
My code is here:
Thread t = new Thread() {
public void run(){
try {
String uri = "https://app.box.com/files";
HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setHost(uri);
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
client.setHostConfiguration(hostConfig);
Credentials creds = new UsernamePasswordCredentials("USER", "PASSWORD");
client.getState().setCredentials(AuthScope.ANY, creds);
String baseUrl = "/";
File f = new File(Environment.getExternalStorageDirectory() + "/working-draft.txt");
PutMethod method = new PutMethod(baseUrl + "/" + f.getName());
RequestEntity requestEntity = new InputStreamRequestEntity(
new FileInputStream(f));
method.setRequestEntity(requestEntity);
client.executeMethod(method);
}
catch (FileNotFoundException fnfe){
Log.i("SERVICE", "FileNotFoundException");
}
catch (HttpException he){
Log.i("SERVICE", "HttpException");
}
catch (IOException ioe){
Log.i("SERVICE", "IOException");
}
catch (Exception e){
Log.i("SERVICE", "Other Exception");
}
}
};
t.start();
I tried for a long time with JackRabbit and another webDav library but could not get it to work. This is how I eventually managed to send images to a WebDav hosted in IIS7 on a windows server. Hope this helps somebody.
SendImage.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import ntlm.NTLMSchemeFactory;
//import org.apache.http.client.HttpClient;
public class SendImage extends AsyncTask<String, Context, String> {
Context cxt;
public SendImage(Context cxtIn){
cxt = cxtIn;
}
#Override
protected String doInBackground(String... params) {
if (!Globals.sendImagesBeingPerformed) {
Globals.sendImagesBeingPerformed = true;
String filepath = cxt.getExternalFilesDir("/MyFileStorage/qrscans/").getAbsolutePath();
File myExternalFile = new File(filepath.toString());
File[] sdDirList = myExternalFile.listFiles();
if(sdDirList != null && sdDirList.length>0){
for(int x=0;x<sdDirList.length;x++){
if(sdDirList[x].toString().endsWith(".jpg")){
File myExternalFile2 = new File(cxt.getExternalFilesDir("/MyFileStorage/qrscans/"), sdDirList[x].getName());
//String URL="";
System.out.println("SENDING QR4");
if(myExternalFile2.exists()) {
System.out.println("ScannedExists");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
String url = Globals.getWebDavUrl().trim();
String u = Globals.getWebDavUser().trim();
String p = Globals.getWebDavPass().trim();
String d = Globals.getWebDavDomain().trim();
if(d!=null && !d.isEmpty() && (d.length()>0)){
//use value of d as domain
}else{
//use a space as domain
d = " ";
}
String device = Globals.deviceId;
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new NTCredentials(u, p, device, d));
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),5000);
if(url.endsWith("/") || url.endsWith("\\")){
url = url.substring(0, url.length()-1);
}
HttpPut put = new HttpPut(url.trim()+"/"+sdDirList[x].getName());
put.setEntity(new FileEntity(sdDirList[x],"application/octet-stream"));
HttpResponse response = null;
try {
response = httpclient.execute(put);
}catch(Exception e){
return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
}
System.out.println("execute done");
BufferedReader in = null;
String webResponse="";
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String stringLine="";
StringBuilder stringBuilder = new StringBuilder();
while ((stringLine = in.readLine()) != null) {
//stringBuilder.append("\n");
stringBuilder.append(stringLine);
}
webResponse=stringBuilder.toString()+"s";
if(webResponse.toString().trim().equalsIgnoreCase("s")){
myExternalFile2.delete();
}
System.out.println("webResponse:" + webResponse);
return null; //webResponse;
}catch(Exception e){
return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
}
}
}
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
if(result!=null){
Toast.makeText(cxt, result, Toast.LENGTH_LONG).show();
}
Globals.sendImagesBeingPerformed = false;
super.onPostExecute(result);
}
}
NTLMSchemeFactory.java
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.impl.auth.NTLMScheme;
import org.apache.http.params.HttpParams;
public class NTLMSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new NTLMScheme(new JCIFSEngine());
}
}
JCIFSEngine.java
package ntlm;
import java.io.IOException;
import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
public class JCIFSEngine implements NTLMEngine {
public String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException {
Type1Message t1m = new Type1Message(
Type1Message.getDefaultFlags(),
domain,
workstation);
return Base64.encode(t1m.toByteArray());
}
public String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException {
Type2Message t2m;
try {
t2m = new Type2Message(Base64.decode(challenge));
} catch (IOException ex) {
throw new NTLMEngineException("Invalid Type2 message", ex);
}
Type3Message t3m = new Type3Message(
t2m,
password,
domain,
username,
workstation,0);
return Base64.encode(t3m.toByteArray());
}
}
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
ArrayList<String> mNameList = new ArrayList<String>();
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=10&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("carriots.apikey", "1234567");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
return returnMsg;
}
protected void onPostExecute(String result)
{
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
How can I actually display a toast without stoping it? Whenever it falls into the catch it is not responding.
............................................................................................................................................................................................................................................................................
If you are using try-catch in a worker thread and want to display Toast, then I am afraid it is not going to work. You will have to do it in Main(UI) thread.
Try following:
try {
dateTo = dateFormatTo.parse(To);
}
catch (java.text.ParseException e) {
your_activity_context.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
Try following:
In getDateTo():
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return -1L; // attention here
}
In getData():
long dateTo = -1L;
if((dateTo = getDateTo()) == -1L){
return null;
}
String toTS = "" + getDateTo();
In onPostExecute:
if(result == null) {
return;
}
Make boolean flag = false; globally.
Inside catch block make flag = true;
Run Toast inside an if block like
if (flag) {
Toast.makeText(this, "Sorry, Couldn't find anything!", Toast.LENGTH_LONG).show();
}
inside your onclick method.
Here is my code to post data on user facebook wall but but getting error in request
here is my code here is my code here is my code here is my code here is my code here is my code
private void postToFacebook(String review) {
mProgress.setMessage("Posting ...");
mProgress.show();
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
params.putString("message", review);
params.putString("name", "Dexter");
params.putString("caption", "londatiga.net");
params.putString("link", "http://www.londatiga.net");
params.putString(
"description",
"Dexter, seven years old dachshund who loves to catch cats, eat carrot and krupuk");
params.putString("picture", "http://twitpic.com/show/thumb/6hqd44");
mAsyncFbRunner.request("me/feed", params, "POST",new WallPostListener());
}
Here is error image
EDIT:
Here is my Login activity
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.sunil.R;
public class LoginActivity extends Activity {
// Facebook APP ID
public static String APP_ID = "3***********";
// Instance of Facebook Class
public Facebook facebook = new Facebook(APP_ID);
public AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Person person = new Person();
// Buttons
Button btnFbLogin;
String fb_userid;
String fb_useremail;
String fb_username;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.loginscreen);
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.example.authenticationdemo",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
// check if you are connected or not
if (isConnected()) {
Toast.makeText(getApplicationContext(), "You are connected",
Toast.LENGTH_LONG);
} else {
Toast.makeText(getApplicationContext(), "You are NOT connected",
Toast.LENGTH_LONG);
}
// Implementing Login button functionality
btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
mAsyncRunner = new AsyncFacebookRunner(facebook);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
/**
* Function to login into facebook
* */
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
// Check access token is present or not
if (access_token != null) {
facebook.setAccessToken(access_token);
getProfileInformation();
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
person.setFacebook_access_token1(facebook
.getAccessToken().toString());
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
getProfileInformation();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getBaseContext(), result,
// Toast.LENGTH_LONG).show();
System.out.println(result);
try {
JSONObject parentObject = new JSONObject(result);
// And then read attributes like
String message = parentObject.getString("Message");
String status = parentObject.getString("Status");
String hash_key = parentObject.getString("hash_key");
Toast.makeText(
getApplicationContext(),
"Status: " + status + " Message: " + message
+ " Hash_Key" + hash_key, Toast.LENGTH_LONG)
.show();
Intent i = new Intent(getApplicationContext(),
Transaction.class);
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("key", hash_key);
startActivity(i);
finish();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String POST(String url, Person person) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email_id", person.getFacebook_emailid1()
.toString());
jsonObject.accumulate("device_type", "Android");
jsonObject.accumulate("facebook_user_id", person
.getFacebook_user_id1().toString());
jsonObject.accumulate("screen_name", person
.getFacebook_user_name1().toString());
jsonObject.accumulate("facebook_user_name", person
.getFacebook_user_name1().toString());
jsonObject.accumulate("facebook_access_token", person
.getFacebook_access_token1().toString());
/*
* JSONObject jsonObject = new JSONObject();
*
* jsonObject.accumulate("hash_key", "Daily");
* jsonObject.accumulate("fb_post_frequency",
* "9afc15d212107f03d08037290631df5****");
*/
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
System.out.println(result);
} else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Get Profile information by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
person.setFacebook_user_name1(profile.getString("name"));
// getting id of the user
person.setFacebook_user_id1(profile.getString("id"));
// getting email of the user
person.setFacebook_emailid1(profile.getString("email"));
// final String user_id = profile.getString("")
runOnUiThread(new Runnable() {
#Override
public void run() {
fb_useremail = person.getFacebook_emailid1()
.toString();
fb_userid = person.getFacebook_user_id1()
.toString();
fb_username = person.getFacebook_user_name1()
.toString();
//Toast.makeText(LoginActivity.this,"Name: " + fb_username + "\nEmail: "+ fb_useremail + " id:"+ fb_userid, Toast.LENGTH_LONG).show();
new HttpAsyncTask()
.execute("http://www.powe****************");
+ "/account/signup_map");
// new
// HttpAsyncTask().execute("http://www.powercheck.icloco.com/rest/index.php"+"/account/fbpostfrequecy");
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
}
use this code for facebook 2.x sdk this sdk deprecated that's why error showing. try to use facebook 3.x sdk
NOTE: as for your requirement this is working once try this
private void SendRequest() {
try {
String response = facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", "contentStr");
parameters.putString("description", "data");
parameters.putString("name", "name");
parameters.putString("picture","http://twitpic.com/show/thumb/6hqd44");
parameters.putString("link", "http://www.londatiga.net");
response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
Log.i("TAG", "Blank Response...");
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
Hey all..I am struck here, I have to display news in a separate list view from a news link web site, but when I debug the cursor goes null. How do I resolve this? Here is my code
package adn.GoMizzou.NB;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class NB extends ListActivity {
public static final String URL = "http://nbsubscribe.missouri.edu/news-releases/feed/atom/";
private String msg;
private boolean success;
private int scrollIndex;
private int scrollTop;
private HttpClient httpClient;
private NBDBAdapter dbAdapter;
private ProgressDialog pDialog;
private Context ctx = this;
private SharedPreferences prefs;
private SharedPreferences.Editor prefsEditor;
//private Cursor cur;
private Cursor q;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg){
pDialog.dismiss();
fillList();
}
};
/* ACTIVITY METHODS */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.nb);
setTitle("News");
q=null;
scrollIndex = 0;
dbAdapter = new NBDBAdapter(this);
dbAdapter.open();
registerForContextMenu(getListView());
getData();
}
public void getData(){
pDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
new Thread(){
public void run(){
dbAdapter.deleteAll();
dbAdapter.close();
doPost(URL, "");
dbAdapter.open();
handler.sendEmptyMessage(0);
}
}.start();
}
public boolean doPost(String url, String postMsg){
HttpResponse response = null;
createHttpClient();
try {
URI uri = new URI(url);
HttpPost httppost = new HttpPost(uri);
StringEntity postEntity = new StringEntity(postMsg);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
postEntity.setContentType("application/x-www-form-urlencoded");
httppost.setEntity(postEntity);
response = httpClient.execute(httppost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response == null){
msg = "No internet connection.";
return false;
}
if(response.getStatusLine().getStatusCode()!= 200){
msg = "Server error.";
return false;
}
return doParse(response);
}
public void createHttpClient(){
if(httpClient == null){
httpClient = new DefaultHttpClient();
}
}
public boolean doParse(HttpResponse response){
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
NBParser respHandler = new NBParser(ctx);
xr.setContentHandler(respHandler);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buffEntity = new BufferedHttpEntity(entity);
xr.parse(new InputSource(buffEntity.getContent()));
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
if(e.getMessage().toString().contains("nothing found")){
msg = e.getMessage().toString();
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = q;
q.moveToPosition(position);
//Intent i = new Intent(this, NB.class);
//i.putExtra("link", c.getString(c.getColumnIndexOrThrow(NBDBAdapter.NB_LINK)));
String newsLinkString = q.getString(q.getColumnIndexOrThrow(NBDBAdapter.NB_LINK));
TextView linkTV = (TextView) v.findViewById(R.id.rowlink);
newsLinkString = linkTV.getText().toString();
if (newsLinkString.startsWith("http://")){
Uri uri = Uri.parse(newsLinkString);
Intent i = new Intent(this, NB.class);
// Save ListView position
i.putExtra("link", c.getString(c.getColumnIndexOrThrow(NBDBAdapter.NB_LINK)));
startActivity(i);
}
}
//else {
//showLinkError();
//}
// Sends an error message to the user if the news item link is malformed
//public void showLinkError() {
//Toast.makeText(getApplicationContext(), "Error - Link to story unavailable with news source could not load the News Story", Toast.LENGTH_SHORT).show();
//}
private void showLinkError() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Error - Link to story unavailable with news source could not load the News Story", Toast.LENGTH_SHORT).show();
}
public void fillList(){
if(!success) {
TextView emptyView = (TextView) findViewById(android.R.id.empty);
emptyView.setText(msg);
msg = "";
}
if(!dbAdapter.isOpen()) dbAdapter.open();
Cursor cursor = dbAdapter.fetchAll();
startManagingCursor(cursor);
String [] from = new String[] { dbAdapter.NB_AUTHOR, dbAdapter.NB_TITLE,dbAdapter.NB_LINK };
int[] to = new int[] { R.id.rowAuthor, R.id.rowTitle, R.id.rowlink };
SimpleCursorAdapter list = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
setListAdapter(list);
}
}
Which cursor are you talking about?
If it's when you click on an item it's because you assign the cursor q null in onCreate and then call moveToPosition on it in onListItemClick.