Hey guys i have implemented twitter sharing in my app and got some problem it gave 215 in response
TwitterCore.getInstance().logInGuest(new Callback<AppSession>() {
#Override
public void success(Result<AppSession> result) {
guestAppSession = result.data;
try {
Log.d("guestAppSession" + guestAppSession.getAuthToken(),
"=" + result.data.getId());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.d("URL", "=" + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
inputStream = res.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Log.d("bufferedReader_", "=" + bufferedReader.readLine());
while(bufferedReader.readLine() != null)
{
Log.d("bufferedReader", "=" + bufferedReader.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void failure(TwitterException exception) {
// unable to get an AppSession with guest auth
}
});
above is my code let me know what is wrong. and give me proper response to implement it...
Thanks ..
Error code: {"errors":[{"code":215,"message":"Bad Authentication data."}]}
I have solved my problem as ..
TwitterCore.getInstance().logInGuest(
new Callback<AppSession>() {
#Override
public void success(
Result<AppSession> appSessionResult) {
AppSession guestAppSession = appSessionResult.data;
final TwitterApiList apiClient = new TwitterApiList(
guestAppSession);
apiClient.getListService().statuses(
" shjh", "user",
50, new Callback<List<Tweet>>() {
#Override
public void success(
Result<List<Tweet>> listResult) {
Log.d("twittercommunity",
"user's profile url is "
+ listResult.data
.get(0).user.profileBackgroundColor);
// Do something with the
// list
}
}
#Override
public void failure(
TwitterException e) {
// FAIL
}
});
}
#Override
public void failure(TwitterException e) {
e.printStackTrace();
}
});
Related
Hi i have a requirement of calling a web service when application goes to background and come back to foreground.I tried both Volley and HttpURLConnection but unfortunately both of them are not working for me. Some times it gives result but some times it is not.Below is my code
#Override
protected void onResume() {
try {
super.onResume();
// app.activityResumed();
// Toast.makeText(this, "QuizActivity Resumed", Toast.LENGTH_LONG).show();
/* if (session.getAreaName()!= null) {
if (GetGeoCodingTask.mAutoCompText != null)
autoCompView.setText(GetGeoCodingTask.mAutoCompText);
}*/
if (GetGeoCodingTask.mAutoCompText != null) {
autoCompView.setText(GetGeoCodingTask.mAutoCompText);
}
autoCompView.post(new Runnable() {
public void run() {
autoCompView.dismissDropDown();
}
});
LoadFoodListData();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
and my Method using HttpURLConnection is
private void LoadFoodListData() {
try {
StringBuffer chaine = new StringBuffer("");
URL url = new URL(myUrl);
connectionOpp = (HttpURLConnection) url.openConnection();
//connection.setReadTimeout(15000);
//connection.setConnectTimeout(15000);
connectionOpp.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connectionOpp.setRequestMethod("POST");
connectionOpp.setDoInput(true);
connectionOpp.setDoOutput(true);
Log.d("Tag", "Webservice after connect");
OutputStream os = connectionOpp.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(child.toString());
writer.flush();
writer.close();
os.close();
connectionOpp.connect();
int responseCode = connectionOpp.getResponseCode();
Log.d("Tag", String.valueOf(responseCode));
if (responseCode == HttpsURLConnection.HTTP_OK) {
// Toast.makeText(mContext, "Httpok",Toast.LENGTH_SHORT).show();
InputStream inputStream = connectionOpp.getInputStream();
Log.d("Tag", "Webservice httpok");
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
chaine.append(line);
}
}
String readJSON = chaine.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
and Using Volley is
private void LoadFoodListData() {
final ProgressDialog ringProgressDialog = ProgressDialog.show(QuizActivity.this, "Please wait ...", "Fetching data nearby you ...", true);
ringProgressDialog.setCancelable(false);
JsonObjectRequest jsObjRequest = null;
try {
jsObjRequest = new JsonObjectRequest(Request.Method.POST, myurl, child,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
ongoing = response.getJSONArray("Listongoing");
if (ongoing != null) {
if (ongoing.length() != 0) {
runOnUiThread(new Runnable() {
#Override
public void run() {
livecount.setText("(" + ongoing.length() + ")");
}
});
}
}
upcoming = response.getJSONArray("ListUpcoming");
Expire = response.getJSONArray("ListExpire");
if (Expire != null) {
if (Expire.length() != 0) {
runOnUiThread(new Runnable() {
#Override
public void run() {
expiredcount.setText("(" + Expire.length() + ")");
}
});
}
}
}
catch (JSONException e) {
e.printStackTrace();
ringProgressDialog.dismiss();
}
// dialogPro.cancel();
ringProgressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ringProgressDialog.dismiss();
}
});
} catch (Exception e) {
ringProgressDialog.dismiss();
}
if (jsObjRequest != null) {
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
AppController.getInstance().addToRequestQueue(jsObjRequest);
}
Any help would be very thankfull.
I am using Thread for Webservice but i cant get the data from Thread because i cant return data from Thread.
This is my WebService.java :
public class Webservice {
static String result;
public static String readUrl(final String url) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
result = ConvertInputStreamToString(stream);
Log.i("xxx","OK" + result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return result;
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is NotesActivity.java :
public class NotesActivity extends Activity {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String result = Webservice.readUrl("http://192.168.200.101:8081/note-server/");
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
thread.start();
}
}
This is my StructTask.java :
public class StructTask {
public long id;
public String title;
public String desc;
public boolean done;
}
This code return for me NULL .
Just try this way
1) Webservice.java
public class Webservice {
public interface WebCallListener{
void onCallComplete(String result);
}
public static void readUrl(final String url,final WebCallListener callListener) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
callListener.onCallComplete(ConvertInputStreamToString(stream));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
2) NotesActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Webservice.readUrl("http://192.168.200.101:8081/note-server/",new WebCallListener() {
#Override
public void onCallComplete(String result) {
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
}
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
}
You may use your code some thing like this:
private class ImageDownloader extends AsyncTask {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return myBackgroundImageDownloadFun(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = ProgressDialog.show(ImageDownladerActivity.this,
"Wait", "Downloading Image");
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
MyImageView.setImageBitmap(result);
simpleWaitDialog.dismiss();
}
For this you can use AsyncTask i.e,
private class Webservice extends AsyncTask<Void, Void, ArrayList<StructTask>> {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<StructTask> doInBackground(Void... params) {
try {
String result = readUrl("http://192.168.200.101:8081/note-server/");
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
}
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nettasks;
}
/* after parsing response this method will be called*/
#Override
protected void onPostExecute(ArrayList<StructTask> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
private String readUrl(String url) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
String result = ConvertInputStreamToString(stream);
Log.i("xxx", "OK" + result);
return result;
}
private String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
In your activity class in onCreate method try to call like this
Webservice service=new Webservice();
service.excute();
so it will starts the excution of the above thread.
i think this will helps you
I used facebook 3.6 sdk . i want to get profile picture from graph user , last time i got image but now it returns null Bitmap.
I used following code
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
URL imgUrl = new URL("http://graph.facebook.com/"
+ user.getId() + "/picture?type=large");
InputStream in = (InputStream) imgUrl.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
//Bitmap bitmap = BitmapFactory.decodeStream(imgUrl // tried this also
//.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
}
}
When i use direct link then it works.
imgUrl = new URL("https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-ash3/t39.2365-6/851558_160351450817973_1678868765_n.png");
i refered this also Graph API Reference
Auto redirection works automatically when original and redirected protocols are same.
So, try to load images from https instead of http : "https://graph.facebook.com/USER_ID/picture"; since image's url is "https://fbcdn-profile-a.akamaihd.net/...."
Then BitmapFactory.decodeStream shall work again.
Try this code,
try {
URL image_value = new URL("http://graph.facebook.com/"+ user.getId()+ "/picture?type=large");
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
profile_pic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
here profile_pic is your ImageView replace it with your ImageView Name.
Edit
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
try {
URL image_value = new URL("http://graph.facebook.com/"+ user.getId()+ "/picture?type=large");
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
profile_pic.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Error...",
Toast.LENGTH_LONG);
}
}
});
Try this code
public static String getProfilePicture() {
String stringURL = null;
try {
stringURL = "http://graph.facebook.com/" + URLEncoder.encode(DataStorage.getFB_USER_ID(), "UTF-8") + "?fields=" + URLEncoder.encode("picture", "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
LogUtil.log(TAG, "getProfilePicture final url is : "+stringURL);
JSONObject jsonObject = null;
String response = "";
try {
HttpGet get = new HttpGet(stringURL);
get.setHeader("Content-Type", "text/plain; charset=utf-8");
get.setHeader("Expect", "100-continue");
HttpResponse resp = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
resp = httpClient.execute(get);
} catch (Exception e) {
e.printStackTrace();
}
// get the response from the server and store it in result
DataInputStream dataIn = null;
try {
// dataIn = new DataInputStream(connection.getInputStream());
if (resp != null) {
dataIn = new DataInputStream((resp.getEntity().getContent()));
}
}catch (Exception e) {
e.printStackTrace();
}
if(dataIn != null){
String inputLine;
while ((inputLine = dataIn.readLine()) != null) {
response += inputLine;
}
if(Constant.DEBUG) Log.d(TAG,"final response is : "+response);
if(response != null && !(response.trim().equals(""))) {
jsonObject = new JSONObject(response);
}
dataIn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
String profilePicture = "";
try{
if(jsonObject != null){
JSONObject jsonPicture = jsonObject.getJSONObject("picture");
if(jsonPicture != null){
JSONObject jsonData = jsonPicture.getJSONObject("data");
if(jsonData != null){
profilePicture = jsonData.getString("url");
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
LogUtil.log(TAG, "user fb profile picture url is : "+profilePicture);
return profilePicture;
}
I tried to use redirect page "https://fbcdn-profile-a.akamaihd.net/" + USERID + "/picture?type=large" but it didn't work.
It seems that now facebook redirect you to a different page that we cannot guess. Kind of random variables in URL.
So try below method to get the new redirect page provided by facebook.
private String getProfileGif(String userId) throws IOException {
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("http.protocol.handle-redirects", false);
HttpGet pageToRequest = new HttpGet("http://graph.facebook.com/" + userId + "/picture?type=large");
pageToRequest.setParams(httpParams);
AndroidHttpClient httpClient = AndroidHttpClient
.newInstance("Android");
HttpMessage httpResponse = httpClient.execute(pageToRequest);
Header header = httpResponse.getFirstHeader("location");
if(header != null){
return(header.getValue());
}
return "";
}
This is gonna return you the real gif URL (final URL).
After that, use this new URL to parse your bitmap.
Change from:
URL image_value = new URL("http://graph.facebook.com/"+ user.getId()+ "/picture?type=large");
to
URL image_value = new URL(getProfileGif(user.getId());
Bitmap bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
PS: Dont execute getProfileGif or any URL request in main thread.
Let me know your results.
I am trying to hit a url through asynctask class and some times, url might not be reachable, in such cases application crashes, how do i prevent this from happening, I would like to display an error message/Toast on UI..I tried to implement runOnUiThread(), but was not successful.
This is my asynctask class: In this case I will be gettin IOException.
public class SelectedEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee>>{
private CaptureActivity captureActivity;
public SelectedEmployeeAsyncTask(CaptureActivity activity) {
this.captureActivity = activity;
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.selectedEmployeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
captureActivity.display(employees);
//activity.showEmployees(employees);
//activity.setContentView(R.layout.activity_capture);
}
}
This is my activity class, where asynctask would be called:
public class CaptureActivity extends Activity {
//private String url = "http://192.168.3.140:8080/EmployeeXmlDemo/EmployeeList.xml";
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
//if(employees!=null){
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
//selectedEmployeeAsyncTask = new SelectedEmployeeAsyncTask(this);
employeeAsyncTask.execute(url);
setContentView(R.layout.activity_capture);
System.out.println("Status "+employeeAsyncTask.getStatus());
//}
}
try this,
catch (final Exception e) {if (e != null) {
e.printStackTrace();
Temes.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
});
}
my HttpGet request is calling my indexAction, instead of getAction. What's going on?
Here are my codes:
public function getAction() {
$id = $this->_getParam('id');
if(!$id)
{
$this->getResponse()
->setHttpResponseCode(400)
->setBody("no id");
return;
}
try
{
$q = Doctrine_Query::create()
->from('Milotin_Model_Locations l')
->where ('l.id=?', $id);
$result = $q->fetchArray();
if(count($result) == 1)
{
$this->getResponse()
->setHttpResponseCode(200)
->setBody(json_encode($result));
}
}
catch(Exception $e)
{
$this->getResponse()
->setHttpResponseCode(500)
->setBody($e->getMessage());
}
}
public function indexAction() {
}
And here is my code in Android:
private static void getLoc()
{
final HttpResponse response;
final HttpGet getRequest = new HttpGet(LOCATION_URI + "?geolat=" + geoLat + "&geolong=" + geoLong);
try {
response = mHttpClient.execute(getRequest);
if(response.getStatusLine().getStatusCode() == 200)
{
//do something
}
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
My HttpPost is working correctly (it calls postAction), Any explanation?
Thanks.
I found the answer. It's actually the behavior of Zend Framework. If the 'id' element is not found in the GET request, it will redirect to indexAction, instead of getAction.
Example:
'GET localhost/student' will redirected to indexAction, while
'GET localhost/student/23' will redirected to getAction. (23 is the id)
Found it in Zend Framework: A beginner's guide, by Vikram Vaswani.