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();
}
}
Related
I was doing an android application which has a login, signup using MySQL,php and android studio but I had a problem when I was compiling and it was bringing a warning on the method POST but I couldn't figure out what the problem was, the code below is my code and was requesting for any possible solutions that I can use to fix my code
package com.example.wandie.clinicapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* Created by WANDIE on 8/1/2016.
*/
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
//THIS IS THE PROBLEM I HAVE POST shows an error
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Use this method to do call by post method
public static String httpPostRequest(Context context, String url, String data) {
String response = "";
BufferedReader reader = null;
HttpURLConnection conn = null;
try {
Log.d("RequestManager", url + " ");
Log.e("data::", " " + data);
URL urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
data += "&" + URLEncoder.encode("email", "UTF-8") + "="
+ URLEncoder.encode(email, "UTF-8");
wr.write(data);
wr.flush();
Log.d("post response code", conn.getResponseCode() + " ");
int responseCode = conn.getResponseCode();
if (responseCode == 401) {
Intent i = new Intent();
i.setAction(CUSTOM_INTENT);
context.sendBroadcast(i);
}
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "error");
} finally {
try {
reader.close();
if (conn != null) {
conn.disconnect();
}
} catch (Exception ex) {
}
}
Log.d("RESPONSE POST", response);
return response;
}
I am post Json object data using volley libraries in my app but I want to get response from that request and update UI according to response and also show progressdialog while doing background process.how can I do that please tell me.
here is my code:-
public void postData() {
try {
getText();// get Input Text by the user
String json;// storing json object
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szOldPassword);
jsonObject.put("newpin", s_szNewPassword);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
System.out.println("Server Request:-" + json);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.s_szChangePassUrl, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
public void getText() {// getting text from editText.....
s_szMobileNumber = m_MobileEditText.getText().toString().trim();// get mobile number from edit text
s_szNewPassword = m_NewPassEditText.getText().toString().trim();// get new pasword from edit Text
}
public void getResponse() throws JSONException {// method regarding condition.................
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
s_szResponseNewPassword = m_oResponseobject.getString("newpin");// getting new password response from server....
CSnackBar.getInstance().showSnackBarSuccess(findViewById(R.id.mainLayout), "Password Changed Successfully", getApplicationContext());
upDatePassword();// updating password in shared preference.......
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent login = new Intent(getApplicationContext(), CLoginScreen.class);
startActivity(login);
}
}, 3500);
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "User not found", getApplicationContext());
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("New Pin Can Not Be Empty")) {
CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "Enter valid password", getApplicationContext());
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "Old pin not found", getApplicationContext());
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "Enter valid mobile number", getApplicationContext());
}
}
public void upDatePassword() {// Update old password from new password in shared preference ......
m_Preferences = getApplicationContext().getSharedPreferences("LoginData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = m_Preferences.edit();
editor.putString("pin", s_szResponseNewPassword);
editor.apply();
}
Try this on your onResponse
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
}
This may helps you.
EDIT 1 :
try following code,
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public class Login extends AppCompatActivity{
public static final String LOGIN_URL = "YOUR_URL";
ProgressDialog pDialog;
public static final String KEY_USERNAME="username";
public static final String KEY_PASSWORD="password";
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonLogin;
private String username;
private String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isNetworkAvailable()){
userLogin();
}
else
{
showMessageDialog("Error", "Check your Internet Connection..!");
}
}
});
}
private void userLogin() {
username = editTextUsername.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//JSONArray myJSON= new JSONArray(response);
JSONObject parentObject = new JSONObject(response);
JSONObject childObject = parentObject.getJSONObject("Tracking");
String status = childObject.optString("status");
String type = childObject.optString("type");
//System.out.println("status : " + status);
//System.out.println("Type : " + type);
if(status.trim().equals("success"))
{
pDialog.hide();
showMessageDialog("Login", type + " Login Successfully..!");
}
else
{
pDialog.hide();
showMessageDialog("Login", "No Users/Admin were Found..! ");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
pDialog.hide();
showMessageDialog("JSON Error", "Server Error..! Try after Some Time..!");//e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
pDialog.hide();
showMessageDialog("Login", "Reponse => " + error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put(KEY_USERNAME,username);
map.put(KEY_PASSWORD,password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showMessageDialog(String title , String Message)
{
AlertDialog dialog = new AlertDialog.Builder(Login.this)
.setTitle(title)
.setMessage(Message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.show();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
I have mysql database on my hosting server
On simple android application I have feedback form and on submit I want to insert data into mysql database which is on server .
I tried google and found this following solution for local machine
how do I connect to my hosting server and mysql database without any php code?
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
Here
HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
insert.php is mentioned means you have to put this file on server
just change the http://10.0.2.2/insert.php to the path of your server file path where the file is stored
Code for insert.php
// this variables is used for connecting to database and server
$host="yourhost";
$uname="username";
$pwd='pass';
$db="dbname";
// this is for connecting
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
// getting id and name from the client
if(isset($_REQUEST)){
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];}
// variable used to tell the client whether data is stored in database or not
$flag['code']=0;
// for insertion
if($r=mysql_query("insert into emp_info values('$name','$id') ",$con))
{
//if insertion succeed set code to 1
$flag['code']=1;
echo"hi";
}
// send result to client that will be 1 or 0
print(json_encode($flag));
//close
mysql_close($con);
?>
as mentioned in your code , this will get the value from server whether the data is stored or not by code=1 for stored and code = 0 for not stored
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
package fluent.techno.shreedurgajyotish;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import fluentindia.database.mysql.JsonHelper;
import fluentindia.tech.MenuAdapter.ProductAdapter;
import fluentindia.tech.MenuModel.ProductModel;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class Feedback extends Fragment
{
Button close,home,btnback,btnsend;
EditText edname,edcompany,edemail,edcontact,edwebsite,edaddress,edcomment;
String na,con,email,comm,advname,advem,advcontact,nacompany,web,add;
Spinner product;
JsonHelper Jobj;
String WebUrl, UrlImg;
JSONObject obj = null;
String Id,name,em,contact,AdvocateId,city;
ProductAdapter madappppppppppp;
ArrayList<ProductModel> llistttt;
int proid=0;
TextView textViewt2,t1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View v =inflater.inflate(R.layout.feedback, null);
edname = (EditText)v.findViewById(R.id.editname);
edemail = (EditText)v.findViewById(R.id.editemail);
edcontact = (EditText)v.findViewById(R.id.editcontact);
edcomment = (EditText)v.findViewById(R.id.editcomment);
btnsend = (Button)v.findViewById(R.id.btnsend);
product = (Spinner)v.findViewById(R.id.editproduct);
textViewt2 = (TextView)v.findViewById(R.id.textViewt2);
t1 = (TextView)v.findViewById(R.id.textView1);
Bundle bung = this.getArguments();
if(bung!=null)
{
proid = bung.getInt("proid");
}
if(proid == 0)
{
Processtaluka pro = new Processtaluka();
pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectdistict.php"});
}
else
{
Processtaluka pro = new Processtaluka();
pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectsingledistict.php?proid="+proid});
}
t1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent callweb = new Intent(Intent.ACTION_VIEW);
callweb.setData(Uri.parse("http://pulleycoupling.com/"));
startActivity(callweb);
}
});
textViewt2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9824155380"));
startActivity(callIntent);
}
});
btnsend.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
na=edname.getText().toString();
con=edcontact.getText().toString();
email=edemail.getText().toString();
comm = edcomment.getText().toString();
if(na==null||na==""||na.length()<2)
{
edname.setError("Please Enter Name");
}
else if(con == null || con == "" || con.length()<10)
{
edcontact.setError("Please Enter Contact");
}
else if(email == null || email == "" || email.length()<4)
{
edemail.setError("Please Enter Email");
}
else if(comm == null || comm== "" || comm.length()<2)
{
edcomment.setError("Please Enter Comment");
}
else
{
ProcessInquiry pro = new ProcessInquiry();
pro.execute(new String[]{"insertfeedback.php"});
}
}
});
return v;
}
private class ProcessInquiry extends AsyncTask<String, Void, Boolean>
{
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute()
{
dialog.setMessage("Please Wait Feedback send..");
dialog.show();
}
#Override
protected Boolean doInBackground(String... Url)
{
for(String Url1 : Url)
{
try
{
Jobj = new JsonHelper();
ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("name", na));
pair.add(new BasicNameValuePair("contact", con));
pair.add(new BasicNameValuePair("email", email));
pair.add(new BasicNameValuePair("comment", comm));
pair.add(new BasicNameValuePair("product", city));
Jobj.MakeJsonCall(Url1, 2, pair);
Log.e("Url", Url1);
return true;
}
catch (Exception e)
{
return false;
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
if(result==true)
{
Toast.makeText(getActivity(), "Feedback Send Sucessfully", 1000).show();
Intent i=new Intent(getActivity(),FragmentMaster.class);
i.putExtra("frgNo", "0");
startActivity(i);
edname.setText("");
edcomment.setText("");
edcontact.setText("");
edemail.setText("");
}
dialog.dismiss();
}
}
private class Processtaluka extends AsyncTask<String, Void, Boolean>
{
#Override
protected void onPreExecute()
{
}
#Override
protected Boolean doInBackground(String... Url)
{
for(String Url1 : Url)
{
Jobj = new JsonHelper();
obj = Jobj.MakeJsonCall(Url1, 2);
try
{
llistttt = new ArrayList<ProductModel>();
JSONArray JArr = obj.getJSONArray("record");
if(proid == 0)
{
}
else
{
}
for(int i=0;i<JArr.length();i++)
{
JSONObject dObj = JArr.getJSONObject(i);
llistttt.add(new ProductModel( dObj.getString("sub_id"), dObj.getString("sub_name")));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return true;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
madappppppppppp = new ProductAdapter(getActivity(),llistttt);
product.setAdapter(madappppppppppp);
product.setPrompt("Select The Service You Want");
product.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
city= llistttt.get(arg2).getSubname();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
}
I need some help on Instagram api in android development, i need to search feeds or tags of Instagram in my app, is any one have suggestion about on it? or please provide links of tutorial
Advance thanks
You can find all you need on the instagram developer page:
http://instagram.com/developer/endpoints/tags/
Instagram provides a RESTful API, so you will make simple HTTP-calls on URLs with your specified parameters (like a tag you want to search for). The response will be in JSON-format, from which you can extract the desired information such as image urls, user-name, etc.
With the bold parts above you have all you need reach your goal. Just google for these parts, here is a tutorial for implementing REST in Android. Also see this question on StackOverflow to reach a more advanced implementation: Android rest client sample.
Also Vogella's tutorial is great and shows you both parts, the request call and the response parsing.
Here is a function that creates the URl to search for a certain hashtag:
public static String getSearchUrl(String hashtag) {
return "https://api.instagram.com/v1/tags/" + hashtag
+ "/media/recent?client_id=" + Constants.CLIENT_ID;
}
package com.pgd.Fragments;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.pgd.Adepters.InstagramTimelineAdapter;
import com.pgd.Beans.InstagramBeans;
import com.pgd.R;
import com.pgd.SocialLogin.Params;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
/**
* Created by admin on 9/26/2017.
*/
public class InstagramTimelineFragment extends Fragment {
public static final String API_AUTH_URL = "https://instagram.com/oauth/authorize/?";
public static final String API_ACCESS_TOKEN_URL = "https://api.instagram.com/oauth/access_token";
public static final String API_BASE_URL = "https://api.instagram.com/v1";
public String CLIENT_ID = "8c1e17fd79e1402e915d94c1f05c5c3c";
public String CLIENT_SECRET = "8885809e2b934647bedcec7068ea3e78";
public String REDIRECT_URL = "https://stackoverflow.com/users/6286004/amit-bhatnagar";
String username = "";
String fullName = "";
String profilePicture = "";
String accessToken = "";
String id = "";
private WebView _webView;
private LinearLayout _loadProgressLayout;
private ProgressBar _loadProgressBar;
InstagramBeans instagramBeansList;
InstagramTimelineAdapter instagramTimelineAdapter;
private RecyclerView recyclerView;
public static final String InstagramTimelineFragment = "InstagramTimelineFragment";
public static InstagramTimelineFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(InstagramTimelineFragment, page);
InstagramTimelineFragment fragment = new InstagramTimelineFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.instagram_timeline_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.insta_recyclerView);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
initWebView(view);
return view;
}
private void initWebView(View view) {
_loadProgressBar = (ProgressBar) view.findViewById(R.id.loadProgressBar);
_loadProgressLayout = (LinearLayout) view.findViewById(R.id.loadProgressLayout);
_webView = (WebView) view.findViewById(R.id.webView);
_webView.getSettings().setJavaScriptEnabled(true);
_webView.clearCache(true);
_webView.setWebViewClient(new InstagramWebViewClient());
_webView.setWebChromeClient(new InstagramWebChromeClient());
CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
_webView.loadUrl(getCodeRequest(CLIENT_ID, REDIRECT_URL));
}
public String authorize(String clientId, String clientSecret, String redirectUrl, String code) throws IOException, JSONException {
Params params = new Params();
params.put("client_id", clientId);
params.put("client_secret", clientSecret);
params.put("redirect_uri", redirectUrl);
params.put("grant_type", "authorization_code");
params.put("code", code);
JSONObject rootJson = sendRequest(API_ACCESS_TOKEN_URL, params, Request.POST);
JSONObject userJson = rootJson.getJSONObject("user");
id = userJson.getString("id");
username = userJson.optString("username");
fullName = userJson.optString("full_name");
profilePicture = userJson.optString("profile_picture");
accessToken = rootJson.optString("access_token");
Log.d("name", username);
return accessToken;
}
public JSONObject sendRequest(String url, Params params, Request request) throws IOException, JSONException {
String signedUrl = getSignedUrl(url, params, request);
String body = "";
if (request == Request.POST)
body = params.getParamsStringUtf8();
System.out.println("Tag" + " url : " + signedUrl);
if (body.length() != 0)
System.out.println("Tag" + " body : " + body);
String response = "";
for (int i = 1; i <= 3; ++i) {
try {
if (i != 1)
System.out.println("tag" + " try send = " + i);
response = sendDummyRequest(signedUrl, body, request);
break;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// JSONObject rootJSON = new JSONObject(response);
JSONObject rootJSON = (JSONObject) new JSONTokener(response).nextValue();
return rootJSON;
}
public enum Request {
GET,
POST
}
private String sendDummyRequest(String url, String body, Request request) throws IOException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setUseCaches(false);
connection.setDoInput(true);
// connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
if (request == Request.GET) {
connection.setDoOutput(false);
connection.setRequestMethod("GET");
} else if (request == Request.POST) {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
}
if (false)
connection.setRequestProperty("Accept-Encoding", "gzip");
if (request == Request.POST)
connection.getOutputStream().write(body.getBytes("utf-8"));
int code = connection.getResponseCode();
System.out.println("TAG" + " responseCode = " + code);
//It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
if (code == -1)
throw new IOException();
//может стоит проверить на код 200
//on error can also read error stream from connection.
InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
String encoding = connection.getHeaderField("Content-Encoding");
if (encoding != null && encoding.equalsIgnoreCase("gzip"))
inputStream = new GZIPInputStream(inputStream);
String response = convertStreamToString(inputStream);
System.out.println("TAG" + " response = " + response);
return response;
} finally {
if (connection != null)
connection.disconnect();
}
}
private String getSignedUrl(String url, Params params, Request request) {
String signedUrl = url + params.getEndpoint();
if (request == Request.GET) {
String args = params.getParamsStringUtf8();
return signedUrl + "?" + args;
}
return signedUrl;
}
public String convertStreamToString(InputStream is) throws IOException {
InputStreamReader r = new InputStreamReader(is);
StringWriter sw = new StringWriter();
char[] buffer = new char[1024];
try {
for (int n; (n = r.read(buffer)) != -1; )
sw.write(buffer, 0, n);
} finally {
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return sw.toString();
}
public class InstagramWebViewClient extends WebViewClient {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(REDIRECT_URL)) {
final Intent intent = new Intent();
if (url.contains("code")) {
String temp[] = url.split("=");
final String code = temp[1];
new Thread(new Runnable() {
#Override
public void run() {
try {
accessToken = authorize(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, code);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// getFeed();
// userNameTextView.setText(username);
//userFullnameTextView.setText(fullName);
//Picasso.with(getActivity()).load(profilePicture).into(userImageView);
_webView.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
getFeed();
}
});
} catch (final Exception e) {
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
intent.putExtra("error", e.getMessage());
// setResult(Activity.RESULT_OK, intent);
// finish();
}
});
}
}
}).start();
} else if (url.contains("error")) {
String temp[] = url.split("=");
String error = temp[temp.length - 1];
intent.putExtra("error", error);
// setResult(Activity.RESULT_OK, intent);
// finish();
}
return true;
}
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
_loadProgressLayout.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
_loadProgressLayout.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
_loadProgressLayout.setVisibility(View.GONE);
Toast.makeText(getActivity(),
getString(R.string.page_load_error),
Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("error", description);
// setResult(Activity.RESULT_OK, intent);
//finish();
}
}
public String getCodeRequest(String clientId, String redirectUrl) {
return API_AUTH_URL + "client_id=" + clientId + "&redirect_uri=" + redirectUrl + "&response_type=code";
}
private class InstagramWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
_loadProgressBar.setProgress(newProgress);
}
}
public void getFeed() {
try {
URL example = new URL("https://api.instagram.com/v1/users/self/media/recent?access_token="
+ accessToken);
Ion.with(getActivity())
.load(String.valueOf(example))
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
String response = result.toString();
Log.d("res_feed", response);
Gson gson = new Gson();
instagramBeansList = gson.fromJson(response, InstagramBeans.class);
if (instagramBeansList.getData().size() > 0) {
instagramTimelineAdapter = new InstagramTimelineAdapter(getActivity(), instagramBeansList.getData());
recyclerView.setAdapter(instagramTimelineAdapter);
} else {
Toast.makeText(getActivity(), "Data in empty", Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
} else {
}
}
}
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