I want to get Facebook friends list in my android application (friend picker not required).I have followed the the procedure describe on Facebook application development
I have also run the samples , but confused to get the friends list. your suggestions will be appreciated.
you can get friend list with this code
String returnString = null;
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("me/friends"));
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
for(int i=0;i<jArray.length();i++){
Log.i("log_tag","User Name: "+json_data.getString("name")+
", user_id: "+json_data.getString("id"));
returnString += "\n\t" + jArray.getJSONObject(i);
};
flist.setText(returnString);
progressDialog.dismiss();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
I get just name and id , if you want get different things,
public class MainActivity extends FragmentActivity implements OnClickListener {
private static final String LOGTAG = "MainActivity";
private List<GraphUser> tags;
private Button pickFriendsButton;
Button locationtoast;
private ProfilePictureView profilePictureView;// 2
private LoginButton fb_loginBtn;// loginbtn
private TextView userName, userName2, userName3, userName4, text;
private UiLifecycleHelper uiHelper;
// private Button pickFriendsButton;
Button btnlogin;
String Name;
String Id;
String lastname;
String firstname;
String getUsername;
String get_gender;
GraphPlace location;
String profileid;
String birthday;
String get_email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationtoast = (Button) findViewById(R.id.location_button);
locationtoast.setOnClickListener(this);
btnlogin = (Button) findViewById(R.id.profile_view);
btnlogin.setOnClickListener(this);
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);// 3
text = (TextView) findViewById(R.id.text);
userName = (TextView) findViewById(R.id.user_name);
fb_loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
pickFriendsButton = (Button) findViewById(R.id.add_friend);
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
pickFriendsButton.setEnabled(enableButtons);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
private void onClickPickFriends() {
final FriendPickerFragment fragment = new FriendPickerFragment();
setFriendPickerListeners(fragment);
showPickerFragment(fragment);
}
private void showPickerFragment(FriendPickerFragment fragment) {
fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> pickerFragment,
FacebookException error) {
String text = getString(R.string.exception,
error.getMessage());
Toast toast = Toast.makeText(MainActivity.this, text,
Toast.LENGTH_SHORT);
toast.show();
}
});
}
private void setFriendPickerListeners(
final FriendPickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(
PickerFragment<?> pickerFragment) {
onFriendPickerDone(fragment);
}
});
}
private void onFriendPickerDone(FriendPickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String results = "";
List<GraphUser> selection = fragment.getSelection();
tags = selection;
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = getString(R.string.no_friends_selected);
}
// showAlert("fghjklkbvbn", results);
showAlert(getString(R.string.you_picked), results);
}
private void showAlert(String title, String message) {
new AlertDialog.Builder(MainActivity.this).setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null).show();
}
});
fb_loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
// Intent intent = new Intent(this, ValuesShow.class);
// startActivity(i);
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
profilePictureView.setProfileId(user.getId());// 4
userName.setText("Hello , " + user.getName()
+ "\n you logged In Uaar Alumni ");
// userName2.setText("frstname"+ user.getFirstName());
// userName3.setText("address"+user.getBirthday());
// userName4.setText("texr"+user.getLocation());
get_email = (String) user.getProperty("email");
Name = user.getName();
Id = user.getId();
lastname = user.getLastName();
firstname = user.getFirstName();
getUsername = user.getUsername();
location = user.getLocation();
get_gender = (String) user.getProperty("gender");
// birthday=user.getBirthday();
// profileid=user.getId();
// profilePictureView.setProfileId(Id.getId());
// text.setText(Name + " \n " + Id + "\n" + firstname +
// "\n"
// + lastname + "\n" + getUsername + "\n" + get_gender);
// profilePicture=user.getId();
} else {
userName.setText("You are not logged");
}
}
});
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
text.setText("");
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = null;
switch (v.getId()) {
// case R.id.fb_login_button:
case R.id.location_button:
i = new Intent(this, LocationGet.class);
break;
// i=new Intent (this,Main_menu.class);
// break;
case R.id.profile_view:
i = new Intent(this, ValuesShow.class);
Log.d(Name, "" + Name);
i.putExtra("Name", Name);
i.putExtra("get_gender", get_gender);
i.putExtra("lastname", lastname);
i.putExtra("firstname", firstname);
i.putExtra("Id", Id);
i.putExtra("birthday", birthday);
i.putExtra("get_email", get_email);
// i.putExtra("profileid",profileid);
break;
}
// profilePictureView.setProfileId(user.getId());
// Intent intent = new Intent(this, ValuesShow.class);
// intent.getBooleanExtra("location", location);
Log.d(lastname, "" + lastname);
Log.d(get_gender, "" + get_gender);
// Log.d(LOGTAG,"Name value name....");
startActivity(i);
}
}
Related
I have a listview which consist of image.Now i want to check whether user is logged in or not for every image click.
Here is an CustomStatusGrid.java:
package com.example.kalpesh.statuscollection.Status.Adapter;
import java.util.ArrayList;
import static com.example.kalpesh.statuscollection.LoginActivity.MY_PREFS_NAME;
/**
* Created by Kalpesh on 12/9/2017.
*/
public class CustomStatusGrid extends BaseAdapter {
private Context mContext;
ArrayList<StatusFrmCatResponse_Model> arrayList = new ArrayList<>();
public static final String MY_PREFS_NAME = "MyPrefsFile";
protected static final SharedPreferences settings = null;
public CustomStatusGrid(Context c, ArrayList<StatusFrmCatResponse_Model> arrayList) {
mContext = c;
this.arrayList = arrayList;
}
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_status, null);
TextView txt_StatusName = (TextView) grid.findViewById(R.id.txt_StatusName);
txt_StatusName.setText(arrayList.get(position).getStatusName());
//TextView txt_status = (TextView) grid.findViewById(R.id.txt_StatusId);
//final String StatusID =txt_status.toString();
ImageView imageClick = (ImageView) grid.findViewById(R.id.ImgAddtoFav);
imageClick.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
}
});
}
else {
grid = (View) convertView;
}
return grid;
}
}
Here is an LoginActivity.java :
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
ArrayList<LoginUserResponse_Model> arrayList=new ArrayList<>();
private static final String TAG = LoginActivity.class.getSimpleName();
private EditText editTextUsername, editTextPassword;
private UserInfo userInfo;
private Session session;
private Button login;
public static final String MY_PREFS_NAME = "MyPrefsFile";
protected static final SharedPreferences settings = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextUsername = (EditText) findViewById(R.id.email);
editTextPassword = (EditText) findViewById(R.id.password);
userInfo = new UserInfo(this);
login = (Button)findViewById(R.id.login);
login.setOnClickListener(this);
findViewById(R.id.link_Register).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if user pressed on login
//we will open the login screen
finish();
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
}
private void login(final String email, final String password){
final String username = editTextUsername.getText().toString();
final String password1 = editTextPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username))
{
editTextUsername.setError("Please enter your Email");
editTextUsername.requestFocus();
return;
}
/* if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
email.setError("Enter a valid email");
email.requestFocus();
return;
}*/
if (TextUtils.isEmpty(password1))
{
editTextPassword.setError("Please enter your password");
editTextPassword.requestFocus();
return;
}
// Tag used to cancel the request
String tag_string_req = "req_login";
//progressDialog.setMessage("Logging in...");
// progressDialog.show();
String URL = "http://api.statuscollection.in/api/login";
StringRequest strReq = new StringRequest(Request.Method.POST,
URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.wtf(TAG, "Login Response: " + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject datajsonObject = jsonObject.getJSONObject("data");
LoginUserResponse_Model getDetailStatusModel= new LoginUserResponse_Model();
getDetailStatusModel.setCostamarId(datajsonObject.getString("CostamarId"));
getDetailStatusModel.setEmail(datajsonObject.getString("Email"));
getDetailStatusModel.setPassword(datajsonObject.getString("Password"));
String CostamarId = getDetailStatusModel.setCostamarId(datajsonObject.getString("CostamarId"));
Log.wtf("LoginActivity", "CostamarId " + datajsonObject.getString("CostamarId"));
Log.wtf("LoginActivity", "Email " + datajsonObject.getString("Email"));
Log.wtf("LoginActivity", "Password " + datajsonObject.getString("Password"));
Toast.makeText(LoginActivity.this, "You are Login Successfuly !!!", Toast.LENGTH_LONG).show();
// String CID =arrayList.get(CostamarId);
SharedPreferences settings = getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("logged", true);
// set it to false when the user is logged out
editor.putString("CostamarId",CostamarId);
// Commit the edits!
editor.commit();
SharedPreferences.Editor editor1 = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor1.putString("CostamarId",CostamarId);
Intent intent = new Intent(LoginActivity.this,ForgetPasswordActivity.class);
//intent.putExtra("CUSTID",CostamarId);
startActivity(intent);
finish();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
toast("Json error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
toast("Unknown Error occurred");
//progressDialog.hide();
//progressDialog.hide();
//progressDialog.hide();
//progressDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
// headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authentication", "5vLGpxfO4_FktAkPB0iM--FQh18USYEG7LWWUCbITpGioOZ16QRxe0JuoryqhMHArMcv-lBleaddcJPG3bsj3m94qOke3uq3mXDtvPUZHFkqm9_3Eub7MYlVCudtd8i_qxnFYQFVV8OTNfQ4w01vDjwBvJI2zVUXl8M-A9YfH09sPslbJKyZUBZBNcAqjSOzeIneaNVPH0WWcBP9xx_GvsvISNLWAM1KWlSia5Kb7Glj2ufmdZwl_XE5h1C_0guL5AkJniyLK1cCFjOXH7dgjJA6vjwgc0ol488TyWPWA19sOzsdPrnuzr724-BK3Z84");
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
strReq.setRetryPolicy(
new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
MySingleton.getInstance(LoginActivity.this).addToRequestQueue(strReq);
}
private void toast(String x){ Toast.makeText(this, x, Toast.LENGTH_SHORT).show();}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login:
String uName = editTextUsername.getText().toString().trim();
String pass = editTextPassword.getText().toString().trim();
login(uName,pass);
break;
case R.id.buttonRegister:
startActivity(new Intent(this, RegisterActivity.class));
break;
}
}
public void Login_cancel(View view) {
editTextUsername.setText("");
editTextPassword.setText("");
}
}
I have a RemoteCar Control app where on the MainActivity page there is a button "location" which you can click on to get redirected into another activity (locationActivity). In this activity im displaying a JSON File in a Listview and now I want to click on those objects to select them and display the location on the main page in something like a simple TextView nothing special. How can I do that?
This is my location page:
public class location extends AppCompatActivity {
private String TAG = location.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> locationList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
locationList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(location.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "url";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray locations = jsonObj.getJSONArray("");
JSONArray locations_ = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < locations_.length(); i++) {
JSONObject c = locations_.getJSONObject(i);
String type = c.getString("type");
String name = c.getString("name");
String address = c.getString("address");
String lat = c.getString("lat");
String lon = c.getString("lon");
String icon;
if(c.has("icon")){
//your json is having "icon" Key, get the value
icon = c.getString("icon");
}
else{
//your json is NOT having "icon" Key, assign a dummy value
icon = "/default/icon_url()";
}
// tmp hash map for single contact
HashMap<String, String> location = new HashMap<>();
// adding each child node to HashMap key => value
location.put("type", type);
location.put("name", name);
location.put("address", address );
location.put("lat", lat);
location.put("lon", lon);
location.put("icon", icon);
// adding contact to contact list
locationList.add(location);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(location.this, locationList,
R.layout.list_item, new String[]{"type", "name", "address", "lat", "lon", "icon"},
new int[]{R.id.type, R.id.name, R.id.address, R.id.lat, R.id.lon, R.id.icon});
lv.setAdapter(adapter);
}
}
and this is my MainActivity page
public class MainActivity extends AppCompatActivity {
public ProgressBar fuelBar;
public Button lockButton;
public Button engButton;
public Button refuelButton;
public Button locationButton;
public SeekBar seekBarButton;
public TextView seekText;
int incFuel = 0;
final String FUELBAR = "fuelBar";
final String AC_BARTEXT = "acBarText";
final String AC_BAR = "acBar";
final String REFUELBUTTON = "refuelButton";
final String STARTENGINE = "startEngineButton";
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = (Button) findViewById(R.id.locationB);
lockButton = (Button) findViewById(R.id.lockB);
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
fuelBar.setMax(100);
fuelBar.setProgress(30);
refuelButton.setText(R.string.refuelB);
lockButton.setText(R.string.lockB);
locationButton.setText(R.string.locationB);
engButton.setText(R.string.engB);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
sharedPref = getPreferences(Context.MODE_PRIVATE);
editor = sharedPref.edit();
seek_bar();
lockPage();
locationPage();
}
#Override
protected void onPause(){
super.onPause();
editor.putInt(FUELBAR, fuelBar.getProgress());
editor.commit();
String tmpAC = "AC : " + String.valueOf(seekBarButton.getProgress()+18) + "°";
editor.putString(AC_BARTEXT, tmpAC);
editor.commit();
editor.putInt(AC_BAR, seekBarButton.getProgress());
editor.commit();
editor.putString(REFUELBUTTON, refuelButton.getText().toString());
editor.commit();
editor.putString(STARTENGINE, engButton.getText().toString());
editor.commit();
}
#Override
public void onResume(){
super.onResume();
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
incFuel = sharedPref.getInt(FUELBAR, 0);
fuelBar.setProgress(incFuel);
seekText = (TextView) findViewById(R.id.seekText);
String tmpAC = sharedPref.getString(AC_BARTEXT, "error");
seekText.setText(tmpAC);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
int tmpInt = sharedPref.getInt(AC_BAR, 18);
seekBarButton.setProgress(tmpInt);
tmpAC = sharedPref.getString(REFUELBUTTON, "REFUEL");
refuelButton.setText(tmpAC);
tmpAC = sharedPref.getString(STARTENGINE, "START ENGINE");
engButton.setText(tmpAC);
}
#Override
public void onStop(){
super.onStop();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.engB:
if (engButton.getText() == "ENGINE RUNNING") {
engButton.setText("START ENGINE");
} else {
if (fuelBar.getProgress() > 0) {
Toast.makeText(MainActivity.this, "starting engine..", Toast.LENGTH_SHORT).show();
engButton.setText("ENGINE RUNNING");
if (fuelBar.getProgress() >= 10) {
incFuel = fuelBar.getProgress();
incFuel -= 10;
fuelBar.setProgress(incFuel);
if (fuelBar.getProgress() < 100)
refuelButton.setText("REFUEL");
}
} else if (fuelBar.getProgress() == 0) {
Toast.makeText(MainActivity.this, "no fuel", Toast.LENGTH_SHORT).show();
engButton.setText("EMPTY GASTANK");
} else
engButton.setText("START ENGINE");
}
break;
case R.id.refuelB:
if (fuelBar.getProgress() == 0) {
engButton.setText("START ENGINE");
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else if (fuelBar.getProgress() < 100) {
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else {
Toast.makeText(MainActivity.this, "tank is full", Toast.LENGTH_SHORT).show();
refuelButton.setText("FULL");
}
break;
}
}
public void seek_bar() {
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNum;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressNum = progress;
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
});
}
public void lockPage() {
lockButton = (Button) findViewById(R.id.lockB);
lockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
startActivity(lockPage);
}
});
}
public void locationPage() {
locationButton = (Button) findViewById(R.id.locationB);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent locationPage = new Intent(MainActivity.this, location.class);
startActivity(locationPage);
}
});
}
}
Sorry for the wall of code I'm always unsure how much information to provide.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MyActivity.this, "location:" + " "+ stringList[position] + " " + "hauptbahnhof selected", Toast.LENGTH_SHORT).show();
}
});
define your list of string as private out of onCreate
I have to fetch LinkedIn details from the loginned user . I am able to get basic basic details through the below code.
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName());
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
Now I want to take education and work details.
Educations items = p.getEducations();
System.out.println("items =="+items);
I got values for p.getfirstname(),p.getlastname() but for p.getEducations() , I got null.
I didn't find any solution anywhere. Please help me
Thanks in advance.
public class LinkCon_Main extends BaseActivityListView {
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(Config.CONSUMER_KEY,
Config.CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
/*LinkCon Widgets*/
ProgressDialog mPrograss;
String name;
View experiencePage;
TextView prof_Name, prof_Headline, prof_Location, prof_Industry;
String prof_name, prof_headline, prof_location, prof_industry, prof_summary, prof_experience,prof_education,prof_languages,prof_skills, prof_interests,prof_birthdate,prof_contatct,prof_email;
String con_name, con_headline, con_location,con_industry, con_summary,con_experience,con_education,con_languages,con_skills,con_interets,con_birthdate,con_phone;
Connections con_email;
String pic_url,con_pic_url;
String startDate, endDate;
String item;
String dty;
String dtm;
String dtd;
ImageView person_Pic, con_pic;
ListView connections_list;
ArrayList<Person> itemslist;
#SuppressWarnings({ "rawtypes" })
Iterator localIterator;
Person mylist;
RelativeLayout layout_persondetils,layout_con_profile;
LinkedInApiClient client;
Person person;
Connections connections;
ImageLoader imageLoader;
DisplayImageOptions options;
LinkConApp myLinkCon;
LayoutInflater inflater;
String[] months= {"Jan", "Feb", "March", "April", "May","June", "July", "August","Sep", "Oct", "Nov", "Dec"};
StringBuilder localStringBuilder;
#Override
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLinkCon=new LinkConApp();
prof_Name=(TextView)findViewById(R.id.user_name);
prof_Headline=(TextView)findViewById(R.id.user_headline);
prof_Location=(TextView)findViewById(R.id.user_Location);
prof_Industry=(TextView)findViewById(R.id.user_industry);
person_Pic=(ImageView)findViewById(R.id.profile_pic);
layout_persondetils=(RelativeLayout)findViewById(R.id.layout_profiledetils);
layout_con_profile=(RelativeLayout)findViewById(R.id.layout_con_profile);
layout_persondetils.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userpersons();
}
});
mPrograss=new ProgressDialog(LinkCon_Main.this);
inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ImageLoader options
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.photo)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
connections_list=(ListView)findViewById(R.id.connectionslist);
itemslist = new ArrayList<Person>();
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final SharedPreferences pref = getSharedPreferences(Config.OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
mPrograss.setMessage("Loading...");
mPrograss.setCancelable(true);
mPrograss.show();
new AsyncTask<Void, Void, LinkedInRequestToken>() {
#Override
protected LinkedInRequestToken doInBackground(Void... params) {
return oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
}
#Override
protected void onPostExecute(LinkedInRequestToken liToken) {
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET,
liToken.getTokenSecret()).commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.execute();
mPrograss.dismiss();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
if (problem == null) {
new AsyncTask<Void, Void, LinkedInAccessToken>() {
#Override
protected LinkedInAccessToken doInBackground(Void... params) {
final SharedPreferences pref = getSharedPreferences(
Config.OAUTH_PREF, MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
pref.getString(
Config.PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(Config.PREF_TOKEN, accessToken.getToken())
.putString(Config.PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(Config.PREF_REQTOKENSECRET).commit();
return accessToken;
}
#Override
protected void onPostExecute(LinkedInAccessToken accessToken) {
mPrograss.dismiss();
showCurrentUser(accessToken);
}
}.execute();
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE).edit()
.remove(Config.PREF_TOKEN).remove(Config.PREF_TOKENSECRET)
.remove(Config.PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
client = factory.createLinkedInApiClient(accessToken);
mPrograss.setMessage("Loading..");
mPrograss.show();
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
try {
final Person user_Profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
person = client.getProfileById(user_Profile.getId(), EnumSet.of(
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL,
ProfileField.INDUSTRY,
ProfileField.MAIN_ADDRESS,
ProfileField.HEADLINE,
ProfileField.SUMMARY,
ProfileField.POSITIONS,
ProfileField.EDUCATIONS,
ProfileField.LANGUAGES,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL));
prof_name = person.getFirstName() + " " + person.getLastName();
prof_headline = person.getHeadline();
prof_location = person.getMainAddress();
prof_industry = person.getIndustry();
return person;
} catch (LinkedInApiClientException ex) {
return ex;
}
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
//result is an Exception :)
final Exception ex = (Exception) result;
clearTokens();
Toast.makeText(
LinkCon_Main.this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
} else if (result instanceof Person) {
final Person person = (Person) result;
prof_Name.setText( person.getFirstName() + " " + person.getLastName());
prof_Headline.setText(person.getHeadline());
prof_Location.setText(person.getMainAddress());
prof_Industry.setText(person.getIndustry());
prof_Name.setVisibility(0);
prof_Headline.setVisibility(0);
prof_Location.setVisibility(0);
prof_Industry.setVisibility(0);
person_Pic.setVisibility(0);
userConnections();
userDetails();
}
}
}.execute();
mPrograss.dismiss();
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
public void userDetails(){
if(person.getPictureUrl()!=null){
pic_url = person.getPictureUrl().toString();
imageLoader.displayImage(pic_url, person_Pic);
}else{
person_Pic.setImageResource(R.drawable.ic_launcher);
}
/*************** person Details Summary/experience/education/languages/skills/contacts/interests **********************/
if (person.getSummary()!=null) {
prof_summary = person.getSummary();
}
prof_experience="";
for (Position position:person.getPositions().getPositionList())
{
if(position.isIsCurrent()){
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate="Currently Working";
}else{
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate=months[(int) (position.getEndDate().getMonth()-1)]+"-"+position.getEndDate().getYear();
}
prof_experience=prof_experience+"<b>" +"Position :"+"</b>"+position.getTitle()+"<br><b>" +"Company :"+ "</b>"+ position.getCompany().getName()+"<br><b>" +"Start Date:"+ "</b>"+ startDate +"<br><b>" +"End Date:"+ "</b>"+ endDate +"<br>"+"<br>";
}
prof_education="";
for (Education education:person.getEducations().getEducationList())
{
prof_education=prof_education +"<b>" +"Gaduation :"+ "</b>" +education.getDegree()+"<br><b>" +"Institute :"+ "</b>" +education.getSchoolName()+ "<br><b>" +"Graduation Year :"+ "</b>" +education.getEndDate().getYear()+"<br>"+"<br>";
}
prof_languages="";
for(Language language:person.getLanguages().getLanguageList())
{
prof_languages=prof_languages+language.getLanguage().getName()+"\n";
}
prof_skills="";
for(Skill skill:person.getSkills().getSkillList())
{
prof_skills=prof_skills+skill.getSkill().getName()+"\n";
}
prof_contatct="";
PhoneNumbers contactinfo=person.getPhoneNumbers();
if(contactinfo!=null ){
for(PhoneNumber phoneno:person.getPhoneNumbers().getPhoneNumberList())
{
prof_contatct=prof_contatct+ phoneno.getPhoneNumber().toString();
}
}
if(person.getEmailAddress()!=null){
prof_email=person.getEmailAddress();
}
prof_interests = person.getInterests();
prof_birthdate= person.getDateOfBirth().getDay()+"-"+ months[(int) (person.getDateOfBirth().getMonth()-1)]+"-"+person.getDateOfBirth().getYear();
}
public void userConnections(){
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.HEADLINE,
ProfileField.INDUSTRY,
ProfileField.PICTURE_URL,
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
itemslist.add(person);
}
connection_Adapter myadpter=new connection_Adapter();
connections_list.setAdapter(myadpter);
connections_list.setVisibility(0);
connections_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*Connections List item position selection*/
person = itemslist.get(position);
/*Intent mycon=new Intent(LinkCon_Main.this, Con_Profile.class);
mycon.putExtra("conid", con_name);
startActivity(mycon);
*/
con_name=person.getFirstName()+" "+person.getLastName();
System.out.println("Name:"+con_name);
con_headline=person.getHeadline();
System.out.println("Designation:"+con_headline);
con_industry=person.getIndustry();
System.out.println("Industry:"+con_industry);
Location localLocation = person.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
System.out.println("Con_Loaction:"+con_location);
}
/*****PICTURE/NAME/INDUSTRY/LOCATION Tested OK******/
/********need to get SUMMARY/EXPERIENCE/EDUCATION/SKILLS/LANGUAGES/DATEOFBIRTH/PHONENUMBER/EMAIL**********/
Toast.makeText(LinkCon_Main.this, "Name:"+" "+con_name +"\n"+"Position:"+" "+con_headline+"\n"+"Industry:"+" "+con_industry+"\n"+"Locations:"+" "+con_location, Toast.LENGTH_LONG).show();
}//onItemClick
});
}
public class connection_Adapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row,
null);
holder = new ViewHolder();
holder.con_Itenames = (TextView) convertView
.findViewById(R.id.connection_name);
holder.con_designations = (TextView) convertView
.findViewById(R.id.connection_headline);
holder.con_ItemImage = (ImageView) convertView
.findViewById(R.id.connection_image);
holder.con_locationad = (TextView) convertView
.findViewById(R.id.connection_location);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SetData(holder,position);
return convertView;
}
protected Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void SetData(final ViewHolder holder, int position) {
final Person con_details = itemslist.get(position);
holder.con_Itenames.setText(con_details.getFirstName()+" "+con_details.getLastName());
holder.con_designations.setText(con_details.getIndustry());
Location localLocation = con_details.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
}
holder.con_locationad.setText(con_location);
holder.con_Itenames.setTag(con_details);
if (con_details.getPictureUrl()!=null) {
imageLoader.displayImage(con_details.getPictureUrl(), holder.con_ItemImage, options);
}else {
holder.con_ItemImage.setImageResource(R.drawable.ic_launcher);}
}
public void setListItems(ArrayList<Person> newList) {
itemslist = newList;
notifyDataSetChanged();
}
}
public class ViewHolder{
TextView con_Itenames,con_designations, con_locationad;
ImageView con_ItemImage;
}
private void userpersons() {
// TODO Auto-generated method stub
Intent user_prof = new Intent(LinkCon_Main.this, User_Profile.class);
user_prof.putExtra("pic", pic_url);
user_prof.putExtra("name", prof_name);
user_prof.putExtra("headline", prof_headline);
user_prof.putExtra("locations", prof_location);
user_prof.putExtra("industry", prof_industry);
user_prof.putExtra("summary", prof_summary);
user_prof.putExtra("languages", prof_languages);
user_prof.putExtra("experience", prof_experience);
user_prof.putExtra("education", prof_education);
user_prof.putExtra("skills", prof_skills);
user_prof.putExtra("interests", prof_interests);
user_prof.putExtra("dateofbirth", prof_birthdate);
user_prof.putExtra("phoneno", prof_contatct);
user_prof.putExtra("email", prof_email);
startActivity(user_prof);
}
}
I have used this api for linkedIn. It helps me to get education, recommendation and career.
http://code.google.com/p/socialauth-android/
I am getting some issue when image is uploaded to flickr,oath token as well as user credentials get stored in the web browser cache.As a result am not being able to sign out from it.So when I go to flickr to upload my image again,it automatically uploads it rather than opening the login page.Now when I clear all the default browser cookies,then it ask for the login page.Is there any other way to sign out it automatically when I am redirected back to my application.Any kind of support will be appreciated.
Thanks in advance...
try this ,here....,FlickerHelper.java
public final class FlickrHelper {
private static FlickrHelper instance = null;
private static final String API_KEY = ""; //$NON-NLS-1$
public static final String API_SEC = ""; //$NON-NLS-1$
private FlickrHelper() {
}
public static FlickrHelper getInstance() {
if (instance == null) {
instance = new FlickrHelper();
}
return instance;
}
public Flickr getFlickr() {
try {
Flickr f = new Flickr(API_KEY, API_SEC, new REST());
return f;
} catch (ParserConfigurationException e) {
return null;
}
}
public Flickr getFlickrAuthed(String token, String secret) {
Flickr f = getFlickr();
RequestContext requestContext = RequestContext.getRequestContext();
OAuth auth = new OAuth();
auth.setToken(new OAuthToken(token, secret));
requestContext.setOAuth(auth);
return f;
}
public InterestingnessInterface getInterestingInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getInterestingnessInterface();
} else {
return null;
}
}
public PhotosInterface getPhotosInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getPhotosInterface();
} else {
return null;
}
}
}
FlickerjActivity.java
public class FlickrjActivity extends Activity {
public static final String CALLBACK_SCHEME = "flickrj-android-sample-oauth"; //$NON-NLS-1$
public static final String PREFS_NAME = "flickrj-android-sample-pref"; //$NON-NLS-1$
public static final String KEY_OAUTH_TOKEN = "flickrj-android-oauthToken"; //$NON-NLS-1$
public static final String KEY_TOKEN_SECRET = "flickrj-android-tokenSecret"; //$NON-NLS-1$
public static final String KEY_USER_NAME = "flickrj-android-userName"; //$NON-NLS-1$
public static final String KEY_USER_ID = "flickrj-android-userId"; //$NON-NLS-1$
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("flickImagePath")) {
path = getIntent().getStringExtra("flickImagePath");
}
}
new Thread() {
public void run() {
h.post(init);
};
}.start();
}
Handler h = new Handler();
Runnable init = new Runnable() {
#Override
public void run() {
OAuth oauth = getOAuthToken();
if (oauth == null || oauth.getUser() == null) {
OAuthTask task = new OAuthTask(getContext());
task.execute();
} else {
load(oauth);
}
}
};
private void load(OAuth oauth) {
if (oauth != null) {
UploadPhotoTask taskUpload = new UploadPhotoTask(this, new File(
path));
taskUpload.setOnUploadDone(new UploadPhotoTask.onUploadDone() {
#Override
public void onComplete() {
finish();
}
});
taskUpload.execute(oauth);
}
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
String scheme = intent.getScheme();
OAuth savedToken = getOAuthToken();
if (CALLBACK_SCHEME.equals(scheme)
&& (savedToken == null || savedToken.getUser() == null)) {
Uri uri = intent.getData();
String query = uri.getQuery();
String[] data = query.split("&"); //$NON-NLS-1$
if (data != null && data.length == 2) {
String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
String oauthVerifier = data[1]
.substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
OAuth oauth = getOAuthToken();
if (oauth != null && oauth.getToken() != null
&& oauth.getToken().getOauthTokenSecret() != null) {
GetOAuthTokenTask task = new GetOAuthTokenTask(this);
task.execute(oauthToken, oauth.getToken()
.getOauthTokenSecret(), oauthVerifier);
}
}
}
}
public void onOAuthDone(OAuth result) {
if (result == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
} else {
User user = result.getUser();
OAuthToken token = result.getToken();
if (user == null || user.getId() == null || token == null
|| token.getOauthToken() == null
|| token.getOauthTokenSecret() == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
return;
}
String message = String
.format(Locale.US,
"Authorization Succeed: user=%s, userId=%s, oauthToken=%s, tokenSecret=%s", //$NON-NLS-1$
user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
saveOAuthToken(user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
load(result);
}
}
public OAuth getOAuthToken() {
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
if (oauthTokenString == null && tokenSecret == null) {
// logger.warn("No oauth token retrieved"); //$NON-NLS-1$
return null;
}
OAuth oauth = new OAuth();
String userName = settings.getString(KEY_USER_NAME, null);
String userId = settings.getString(KEY_USER_ID, null);
if (userId != null) {
User user = new User();
user.setUsername(userName);
user.setId(userId);
oauth.setUser(user);
}
OAuthToken oauthToken = new OAuthToken();
oauth.setToken(oauthToken);
oauthToken.setOauthToken(oauthTokenString);
oauthToken.setOauthTokenSecret(tokenSecret);
return oauth;
}
public void saveOAuthToken(String userName, String userId, String token,
String tokenSecret) {
SharedPreferences sp = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(KEY_OAUTH_TOKEN, token);
editor.putString(KEY_TOKEN_SECRET, tokenSecret);
editor.putString(KEY_USER_NAME, userName);
editor.putString(KEY_USER_ID, userId);
editor.commit();
}
private Context getContext() {
return this;
}
}
GetAouthToken.java
public class GetOAuthTokenTask extends AsyncTask<String, Integer, OAuth> {
private FlickrjActivity activity;
public GetOAuthTokenTask(FlickrjActivity context) {
this.activity = context;
}
#Override
protected OAuth doInBackground(String... params) {
String oauthToken = params[0];
String oauthTokenSecret = params[1];
String verifier = params[2];
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthInterface oauthApi = f.getOAuthInterface();
try {
return oauthApi.getAccessToken(oauthToken, oauthTokenSecret,
verifier);
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(OAuth result) {
if (activity != null) {
activity.onOAuthDone(result);
}
}
}
Oauthtask.java
public class OAuthTask extends AsyncTask<Void, Integer, String> {
private static final Uri OAUTH_CALLBACK_URI = Uri
.parse(FlickrjActivity.CALLBACK_SCHEME + "://oauth"); //$NON-NLS-1$
private Context mContext;
private ProgressDialog mProgressDialog;
public OAuthTask(Context context) {
super();
this.mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext,
"", "Generating the authorization request..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
OAuthTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(Void... params) {
try {
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
OAUTH_CALLBACK_URI.toString());
saveTokenSecrent(oauthToken.getOauthTokenSecret());
URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
Permission.WRITE, oauthToken);
return oauthUrl.toString();
} catch (Exception e) {
return "error:" + e.getMessage(); //$NON-NLS-1$
}
}
private void saveTokenSecrent(String tokenSecret) {
FlickrjActivity act = (FlickrjActivity) mContext;
act.saveOAuthToken(null, null, null, tokenSecret);
}
#Override
protected void onPostExecute(String result) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (result != null && !result.startsWith("error")) { //$NON-NLS-1$
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(result)));
} else {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
}
}
}
uploadphototask.java
public class UploadPhotoTask extends AsyncTask<OAuth, Void, String> {
private final FlickrjActivity flickrjAndroidSampleActivity;
private File file;
public UploadPhotoTask(FlickrjActivity flickrjAndroidSampleActivity,
File file) {
this.flickrjAndroidSampleActivity = flickrjAndroidSampleActivity;
this.file = file;
}
private ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(flickrjAndroidSampleActivity,
"", "Uploading..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
UploadPhotoTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(OAuth... params) {
OAuth oauth = params[0];
OAuthToken token = oauth.getToken();
try {
Flickr f = FlickrHelper.getInstance().getFlickrAuthed(
token.getOauthToken(), token.getOauthTokenSecret());
UploadMetaData uploadMetaData = new UploadMetaData();
uploadMetaData.setTitle("" + file.getName());
return f.getUploader().upload(file.getName(),
new FileInputStream(file), uploadMetaData);
} catch (Exception e) {
Log.e("boom!!", "" + e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (response != null) {
Log.e("", "" + response);
} else {
}
if (monUploadDone != null) {
monUploadDone.onComplete();
}
Toast.makeText(flickrjAndroidSampleActivity.getApplicationContext(),
response, Toast.LENGTH_SHORT).show();
}
onUploadDone monUploadDone;
public void setOnUploadDone(onUploadDone monUploadDone) {
this.monUploadDone = monUploadDone;
}
public interface onUploadDone {
void onComplete();
}
}
mainactivty.java
public class MainActivity extends Activity {
File fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnFlickr = (Button) findViewById(R.id.btnFlickr);
btnFlickr.setOnClickListener(mFlickrClickListener);
Button btnPick = (Button) findViewById(R.id.btnPick);
btnPick.setOnClickListener(mPickClickListener);
}
View.OnClickListener mPickClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivityForResult(intent, 102);
}
};
View.OnClickListener mFlickrClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fileUri == null) {
Toast.makeText(getApplicationContext(), "Please pick photo",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(getApplicationContext(),
FlickrjActivity.class);
intent.putExtra("flickImagePath", fileUri.getAbsolutePath());
startActivity(intent);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 102) {
if (resultCode == Activity.RESULT_OK) {
Uri tmp_fileUri = data.getData();
((ImageView) findViewById(R.id.imageView1))
.setImageURI(tmp_fileUri);
String selectedImagePath = getPath(tmp_fileUri);
fileUri = new File(selectedImagePath);
Debug.e("", "fileUri : " + fileUri.getAbsolutePath());
}
}
};
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
usercard.java
public class UserCard {
public String name;
public String url;
public int upVotes;
public int downVotes;
}
debug.java
public class Debug {
private static final boolean DEBUG = true;
public static void e(String tag, String msg) {
if (DEBUG) {
Log.e(tag, msg);
}
}public static void i(String tag, String msg) {
if (DEBUG) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (DEBUG) {
Log.w(tag, msg);
}
}
public static void d(String tag, String msg) {
if (DEBUG) {
Log.d(tag, msg);
}
}
}
I am developing an Android app. Please see the Java code below. Can you please explain why textView doesn't update at specific lines in code but updates at others. I have them commented in the code.
I have updated the code see below.
The idea is to get a facebook profile from a server. When profiling_status equals 2 means that the profile is not ready, so I'll just ping the server until I get profiling_status != 2..
I tried the progress dialog thingy but gave up cause I put my activity in a thread, but then I couldn't get some information because I should have run it in nonUIThread.. Tried that but I failed and I lost patience.. so decided that while I ping the server I should just print "Loading profile. Please wait." No mess, no fuss! Only as said, textView doesn't update. Interestingly enough.. System.out.println("Here"); gets executed. I am running it only on AVD at the moment cause the server is not on the wireless network so I can't use a mobile phone to test it.
public class SelectionFragment extends Fragment {
private ProfilePictureView profilePictureView;
private TextView userNameView;
private UiLifecycleHelper uiHelper;
private static final int REAUTH_ACTIVITY_CODE = 100;
private TextView textView;
private String username = null;
Context context;
JSONObject json = null;
JSONObject json_facebook = null;
int time = 0;
int time_interval = 3000;
int profiling_status = 2;
String logincode;
String usermessage = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void deleteProfile() throws JSONException {
IDThiefHTTPRequest.deleteProfile();
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
//Facebook logout
Session session2 = Session.getActiveSession();
if (session2 != null) {
session2.close();
}
else {
session2 = new Session(context);
Session.setActiveSession(session2);
session2.close();
}
}
private String readRiskScoreArray(JSONArray json_riskscore) throws NumberFormatException, JSONException{
//get the risk score with only two digits
double risk_score = Double.valueOf(json_riskscore.get(0).toString());
String risk_score2digits = new DecimalFormat("##.##").format(risk_score);
String usermessage = "Your risk score is: ";
usermessage = usermessage + risk_score2digits;
usermessage = usermessage + " which is ranked as: ";
usermessage = usermessage + json_riskscore.get(2).toString();
JSONArray json_reasons = json_riskscore.getJSONArray(1);
for (int i = 0; i < json_reasons.length(); i++){
JSONArray json_reason = json_reasons.getJSONArray(i);
JSONArray json_reasondetails = json_reason.getJSONArray(1);
usermessage = usermessage + "\n\nReason: ";
usermessage = usermessage + json_reasondetails.get(0);
usermessage = usermessage + "\n\nIDThief suggests you to: ";
usermessage = usermessage + json_reasondetails.get(1);
usermessage = usermessage + "\n\nFix it through this link:\n";
usermessage = usermessage + json_reasondetails.get(2);
}
return usermessage;
}
private void displayProfileInfo() throws JSONException {
Session session = Session.getActiveSession();
if (session.isOpened()) {
System.out.println(session.getAccessToken());
}
if (username != null) {
System.out.println("Login stage: Getting profile info for user:" + username);
logincode = username + "!" + session.getAccessToken();
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
System.out.println(json.toString(4));
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
if (profiling_status == 2) {
try {
while (profiling_status == 2 && time < 100000) {
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText("Loading profile. Please wait.");
System.out.println("Here");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
}
if (time >= 100000) {
System.out.println("Time is out");
textView.setText("Server is not responding. Please try again later.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
JSONArray json_riskscore = json_facebook.getJSONArray("risk_score");
System.out.println(json_riskscore.toString(4));
usermessage = readRiskScoreArray(json_riskscore);
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText(usermessage);
}
else System.out.println("username is null");
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection,
container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button deletebutton = (Button) view.findViewById(R.id.ImageButton2);
deletebutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
deleteProfile();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Button button = (Button) view.findViewById(R.id.ImageButton1);
textView = (TextView) view.findViewById(R.id.profiletext);
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setMovementMethod(LinkMovementMethod.getInstance());
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
displayProfileInfo();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
// Check for an open session
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
return view;
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
username = user.getUsername();
//System.out.println("Log in=====================================");
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
makeMeRequest(session);
}
else if (session != null && session.isClosed()) {
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
}
I thing your username is a string . Normally it will be so use !username.equals() dont use != in string comparison. that code may not get executed
if (username != null || !username.equals("")) {
//to do
}
Try out as below to compare the string do not use == use equalsIgnoreCase() or equals() method.
if (profiling_status.equalsIgnoreCase("2")) {
//would not update here either
try {
while (profiling_status.equalsIgnoreCase("2") && time < 100000) {
textView.setText("Loading profile. Please wait.");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
e.printStackTrace();
}