Unable to Get Friend List Android - java

The following code i am using for Getting Friend List From Facebook, I have Session in Another class But Session data comming in this class properly . But after Request for getting Friend list from Facebook. i am getting graphObject {data:[] Just like this .. After that getting JArry Null..
//Class For Getting FacebookUserdata
private void getFacebookUserData() {
Log.d(Utilities.logg, "getFacebookUserData");
//Getting Session information
Log.d(Utilities.logg, "session=" + session);
Request requests;
//Making request for getting Friend list
requests = new Request(session, "me/friends", null, HttpMethod.GET,
new Request.Callback() {
//On Complete Request
public void onCompleted(Response response) {
// threadForUI();
GraphObject graphObject = response.getGraphObject();
FacebookUserDataClass userData = null;
try {
JSONObject json = graphObject.getInnerJSONObject();
//Exit from Dailog
if (json != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mrootInnerInviteFriendsInitiateWars
.setVisibility(RelativeLayout.VISIBLE);
mrootInnerInitiateWars
.setVisibility(RelativeLayout.INVISIBLE);
}
}
//Array for getting data
JSONArray JArray = json.getJSONArray("data");
for (int i = 0; i < JArray.length(); i++) {
if (i == 10) {
mtvFriendLoadingInviteFriend
.setVisibility(TextView.GONE);
setListAdapte(mChoose);
}
//Set Json Object for getting all friends
JSONObject innerObject1 = JArray.getJSONObject(i);
//.get(i);
//Geting Pojo Class
userData = new FacebookUserDataClass();
userData.setUserId((String) innerObject1
.getString("id"));
userData.setUserName((String) innerObject1
.getString("name"));
mFacebookUserDataListFull.add(userData);
}
placeFcaebookList();
mtvFriendLoadingInviteFriend
.setVisibility(TextView.GONE);
// if(Utilities.getSharedPref(Utilities.API_regId,
// "").isEmpty())
// {
// getSelfFacebookProfile();
// }
//Storing data into local database
Utilities.database
.insertIntoFacebookFriendListTable(mFacebookUserDataListFull);
mckbCheckAll.setChecked(true);
checkUncheckAll(mChoose, true);
mbtnRefreshInviteFriend.setEnabled(true);
Utilities.foolFlag = false;
Utilities.saveFriendListOnServer(
mFacebookUserDataListFull,
Utilities.FACEBOOK);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e(logg,
"getUserData EXCEPTION1 " + e.toString());
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
Log.e(logg,
"getUserData EXCEPTION2 " + e.toString());
e.printStackTrace();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
Utilities.errorFlag = true;
// onClickFacebookButton();
}
}
});
pendingRequest = false;
requests.executeAsync();
// Utilities.database
// .insertIntoFacebookFriendListTable(mFacebookUserDataListFull);
// Utilities.foolFlag = false;
// Utilities.saveFriendListOnServer(mFacebookUserDataListFull,
// Utilities.FACEBOOK);
// Log.d(logg, "frnds loding done");
// getFacebookImages();
//Getting Image from the Image Class
new GetFacebookImagesUrl().execute();
}

Related

How to retrieve all tagged facebook photos from the facebook sdk

After many attempts I have been unable to retrieve all of my tagged photos from the facebook sdk. I would like something similar to what tinder has, but my query only returns 110 photos, of which some repeat, compared to tinder retrieving all 296 tagged photos.
Here is the code for my request:
Bundle paramaters = new Bundle();
paramaters.putString("fields", "source");
paramaters.putInt("limit", 1000);
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + userId + "/photos",
paramaters,
HttpMethod.GET,
graphCallback
).executeAsync();
GraphRequest.Callback graphCallback = new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
try {
if (response.getError() == null) {
JSONObject joMain = response.getJSONObject();
if (joMain.has("data")) {
final JSONArray jaData = joMain.optJSONArray("data");
for (int i = 0; i < jaData.length(); i++) {
JSONObject joImages = jaData.getJSONObject(i);
String url = (String) joImages.get("source");
if (i == 0) {
facebookAlbum.setDisplayUrl(url);
}
facebookAlbum.addImage(url);
albumnListAdapter.notifyDataSetChanged();
}
}
}
GraphRequest nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
if(nextRequest != null) {
nextRequest.setCallback(this);
nextRequest.executeAsync();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};

Realm Not saving datas

I am trying save the data's which i get from API and my function is as below
try {
// Simulate network access.
mNetworkSubscription = NetworkRequest.performAsyncRequest(api.getPatientsData(tenantID), (data) -> {
// Update UI on main thread
try {
// long pat_id = 0;
if(data != null) {
if(data.getAsJsonObject().get("error") != null){
publishResults("getPatientsData",STATUS_ERROR, null);
}
if (data != null && data.get("result") != null && data.get("result").toString() != "false") {
Realm realm = Realm.getDefaultInstance();
JsonParser parser = new JsonParser();
// realm.beginTransaction();
// realm.where(Patient.class).findAll().deleteAllFromRealm();
//realm.commitTransaction();
try {
JsonArray casesJsonArray = data.get("result").getAsJsonArray();//parser.parse(data.get("result").getAsJsonObject().toString()).getAsJsonArray();
Log.v(Constants.TAG,"PatientJsonArray: "+casesJsonArray);
if(casesJsonArray.size() > 0) {
Patient patientRecord = new Patient();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
for (int i = 0; i < casesJsonArray.size(); i++) {
try {
JsonObject jsonObject = (JsonObject) casesJsonArray.get(i);
Log.e(Constants.TAG, "execute: jsonObject "+jsonObject);
Log.e(Constants.TAG, "execute: id "+id);
if(realm.where(Patient.class).max("id") != null) {
id = realm.where(Patient.class).max("id").intValue();
Log.e(Constants.TAG, "execute:getPatientsData : In DataSync: " + id);
}
Log.e(Constants.TAG, "execute: jsonObject "+jsonObject);
Log.e(Constants.TAG, "execute: id "+pat_id);
patientRecord.setId(id + 1);
patientRecord.setTenantID(jsonObject.get("tenant_id").getAsLong());
patientRecord.setPatientID(jsonObject.get("patient_id").getAsLong());
patientRecord.setFirstName(jsonObject.get("first_name").getAsString());
patientRecord.setLastName(jsonObject.get("last_name").getAsString());
patientRecord.setPatientWeight(jsonObject.get("patient_weight").getAsString());
patientRecord.setPatientAge(jsonObject.get("patient_age").getAsString());
patientRecord.setGender(jsonObject.get("gender").getAsString());
patientRecord.setStreetAddress(jsonObject.get("street_address").getAsString());
patientRecord.setArea(jsonObject.get("area").getAsString());
patientRecord.setCity(jsonObject.get("city").getAsString());
patientRecord.setZipcode(jsonObject.get("zipcode").getAsString());
patientRecord.setState(jsonObject.get("state").getAsString());
patientRecord.setEmail(jsonObject.get("email").getAsString());
patientRecord.setEnqNumber(jsonObject.get("alternate_number").getAsString());
patientRecord.setEnqName(jsonObject.get("enquirer_name").getAsString());
realm.copyToRealmOrUpdate(patientRecord);
}catch (Exception e){
Log.v(Constants.TAG,"caseList Insert exception: "+e.toString());
}
}
}
});
//realm.close();
}
} catch (Exception e) {
Log.v(Constants.TAG, "getPatientsData Exception: " + e.toString());
}
realm.close();
}
}
} catch (Exception e) {
Log.e(Constants.TAG, "getPatientsData() exception: " + e.toString());
publishResults("getPatientsData",STATUS_ERROR, null);
}finally {
publishResults("getPatientsData",STATUS_FINISHED, null);
}
}, (error) -> {
// Handle Error
Log.e(Constants.TAG,"getPatientsData() Error: "+error.getCause());
publishResults("getPatientsData",STATUS_ERROR, null);
});
}catch (Exception e){
Log.e(Constants.TAG,"getPatientsData() Exception: "+e.toString());
publishResults("getPatientsData",STATUS_ERROR, null);
}
But realm.copyOrUpdate(patientRecords);
is not creating/saving a record in local.
First confirm, if there is no exceptions arises?
Try following workarounds,
Check casesJsonArray.size() > 0 must be true. (OR)
Remove realm.close() and try it once. Sometime it will close realm database connection in between the operation. (OR)
Try with hardcoded(dummy) data.
If above doesn't work then post your Patient Model here.
Note: For auto increment of id you can use following code which will reduce no of database calls-
Number num = realm.where(Patient.class).max("id");
int l_id;
if (num == null) {
i_id = 0;
} else {
i_id = num.intValue() + 1;
}

Accessing data from the table - JSON/Java

I need to access to the "mid" but I need to sort it somehow, so I need to get the "code" and then get the "mid" value.
Can you help me with this, I have no idea how to refer to that.
Here is what I have:
public void onSuccess(String response) {
Log.i("CHACHING", "HTTP Sucess");
try {
JSONObject jsonObj = new JSONObject(response);
JSONObject ratesObject = jonObj.getJSONObject("rates");
String gbpcode = ratesObject.getString("code");
Double gbpRate = ratesObject.getDouble(gbpcode."mid");
Log.i("CHACHING", "GBP: " + gbpRate);
// Log.i("CHACHING", "EUR: " + eurRate);
Double usds = Double.valueOf(usdValue.getText().toString());
Double gbps = usds * gbpRate;
// Double euros = usds * eurRate;
gbpValue.setText("GBP: " + String.valueOf(gbps));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and the json looks like this
http://api.nbp.pl/api/exchangerates/tables/A/?format=json
The json received is list of json objects(json array) and in each json object "rates" is another json Array.
So, in order to access mid.
public void onSuccess(String response) { Log.i("CHACHING", "HTTP Sucess");
try {
JSONArray jsonArr = new JSONArray(response);
JSONObject jsonObj=jsonArr.getJSONObject(0);
//this jsonObj holds the first jsonObject of your response
JSONArray rateList = jonObj.getJSONArray("rates");
//rateList has the list of rates you obtained
//NOW, to get all mids for this rate list
for(int i=0;i<rateList.length();i++) {
JSONObject jO=rateList.getJSONObject(i);
Double mid=jO.getDouble("mid");
Double gbpcode = jO.getString("code");
/*
your code here
*/
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Multiple if else statement with parameter in doGet() servlet

I am having some problem when trying to execute different method in servlet doGet(). So when my button on click, it will pass along the eventID:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent eventDtlIntent = new Intent(context, EventDetail.class);
eventDtlIntent.putExtra("eventID", eventIDTV.getText());
startActivity(eventDtlIntent);
}
});
Then in my EventDetail class, I am executing the method in AsyncTask class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_detail);
context = this;
Bundle extras = getIntent().getExtras();
if (extras != null) {
eventID = extras.getString("eventID");
}
eventModel.setEventID(eventID);
new GetEventDetailAsyncTask(context).execute(eventModel);
}
And in my AsyncTask class, I am calling the method in my controller which retrieving the JSON returned from servlet:
#Override
protected Double doInBackground(Event... params) {
try {
eventCtrl.getEventDetailByID(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
And in my controller class:
public Event getEventDetailByID(Event event) throws JSONException {
Event eventModel = new Event();
String page;
JSONArray jsonArray;
String eventID = event.getEventID();
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ENeighbourhoodActivity.URL
+ "?getEventDetailByID&eventID=" + eventID +"");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
page = "{\'EventDetail\':" + responseString + "}";
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("EventDetail");
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventName = attribute.getString("eventName");
eventModel.setEventName(eventName);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return event;
}
And basically from here, I am accessing the servlet. And in my doGet() in serlvet class:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONArray jsonArray = new JSONArray();
PrintWriter out = response.getWriter();
if (request.getParameter("getAllEvent") != null) {
}
catch (JSONException je) {
System.out.println(je.getMessage());
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
out.println(jsonArray.toString());
}
}
I already have one if statement for some other methods. I wonder how should I pass the getEventDetailByID and the eventID parameter into servlet so that it knows which method to runs.
Thanks in advance.
Here is a example of how you can get the eventID value.
//gets value from getEventDetailByID parameter.
String detail = request.getParameter("getEventDetailByID");
if (detail != null && !detail.equals("")) {
int eventId = Integer.parseInt(request.getParameter("eventID"));
//get event detail by id with id
//e.g resultObject = myMethod(detail, eventId);
}
Update 1:
A better way of doing what is required:
String action = request.getParameter("action");
if (action.equalsIgnoreCase("GetById")) {
int eventId = Integer.parseInt(request.getParameter("eventID"));
//get event detail by id with id
//e.g resultObject = getById(eventId);
} else if (action.equalsIgnoreCase("GetAllEvents")) {
//Get all events
//e.g resultObject = GetAllEvents();
} else {
}
The URL usage:
to get event by id:
http://localhost:8080/WebService/EventDetailServlet?action=GetById&eventID=46
to get all event details
http://localhost:8080/WebService/EventDetailServlet?action=GetAllEvents

How to modify values of JsonObject / JsonArray directly?

Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}

Categories