i have develop a android application integrate with facebook login now i want to make facebook app invite function(invitable_friends api) but in my code i got red underline errors.
private void loadFriendsFromFacebook(final String str) {
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
new GraphRequest(AccessToken.getCurrentAccessToken(), str, null, HttpMethod.GET,
new GraphRequest.Callback() {
List<String> s = new ArrayList();
List<String> F = new ArrayList();
List<String> G = new ArrayList();
String t = "";
String u = "";
int w = 0;
boolean x = false;
String[] y = new String[2];
String E = "";
OnInviteListener onInviteListener = null;
public void onCompleted(GraphResponse response) {
SharedPreferences.Editor edit = getSharedPreferences("friendsData", 0).edit();
try {
int i;
JSONArray jSONArray = response.getJSONArray("data");
for (i = 0; i < jSONArray.length(); i++) {
this.s.add(jSONArray.getJSONObject(i).getString(Page.Properties.ID));
}
for (i = 0; i < jSONArray.length(); i++) {
this.G.add(jSONArray.getJSONObject(i).getJSONObject(Page.Properties.PICTURE).getJSONObject("data").getString("url"));
edit.putString("friendPhoto", jSONArray.getJSONObject(i).getJSONObject(Page.Properties.PICTURE).getJSONObject("data").getString("url"));
this.F.add(jSONArray.getJSONObject(i).getString(Page.Properties.NAME));
edit.putString("friendName", jSONArray.getJSONObject(i).getString(Page.Properties.NAME));
}
edit.commit();
for (i = 0; i < this.s.size(); i++) {
this.u += ((String) this.s.get(i)) + ",";
}
JSONObject jSONObject2 = response.getJSONObject("paging");
if (jSONObject2.toString().contains("next")) {
this.t = jSONObject2.getString("next").toString();
} else if (this.s.size() < 1) {
this.x = true;
}
} catch (Exception e) {
System.out.println("Exception=" + e);
e.printStackTrace();
}
}
}).executeAsync();
}
where the response.getJSONArray("data");
data is underline red which is click rover shows getJSONArray() in graphrespone cannot be applied to java.lang.sting..
and same error in the response.getJSONObject("paging");
Can anyone please tell me what is wrong in the code?
it will be appreciated..
From here (https://developers.facebook.com/docs/reference/android/current/class/GraphResponse/) I can see that getJSONObject() and getJSONArray() do not have parameters at all. You should retrieve the object respective the array from the GraphResponse using this methods and once you have a JsonObject or JsonArray you can access specific fields.
response.getJSONArray() will give you an object of type JSONArray and response.getJSONObject() will give you an object of type JSONObject. Using this objects you can access the fields using jsonObject.getString("user_id") or similar (see docs.oracle.com/javaee/7/api/javax/json/JsonObject.html)
Related
I am, updating the value in a JSONObject that is inside a JSONArray, when changing the value is updating in all the JSONArray. Does anybody know why?
public static void uploadMediaWithThumbnail( final LeagueActivity.UploadingCallback call,
final long leagueId,
final JSONArray information, final JsonHttpResponseHandler handler) {
final AtomicInteger receivedCount = new AtomicInteger();
receivedCount.set(0);
call.progressCall(10);
getMediaUploadUrl(leagueId, information, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
call.progressCall(20);
final JSONArray allData = response.getJSONArray("upload_data");
AsyncHttpClient[] clients = new AsyncHttpClient[allData.length()*2];
JSONArray jarr = information;
for (int i = 0; i < allData.length(); i++ ) {
final String uploadUrl = allData.getJSONObject(i).getString("content_url");
final String previewUrl = allData.getJSONObject(i).getString("preview_url");
jarr.getJSONObject(i).put("content", uploadUrl);
jarr.getJSONObject(i).put("preview", previewUrl);
}
final JSONArray newInfo = shallowCopy(jarr);
Log.d("Log1", newInfo.getJSONObject(1).getString("content"));
Log.d("Log2", newInfo.getJSONObject(0).getString("content"));
When logging Log1 and Log2 they contain the same link
information is a data like this [{"type":"video","format":"mp4","preview_format":"jpg"}, {"type":"video","format":"mp4","preview_format":"jpg"}]
AllData is information received from an REST HTTP call and has the same length as information
Thanks for the update.
You want to add the items for information into a JSONObject, and then add that object to your JSONArray.
JSONArray jarr = information;
for (int i = 0; i < allData.length(); i++ ) {
final String uploadUrl = allData.getJSONObject(i).getString("content_url");
final String previewUrl = allData.getJSONObject(i).getString("preview_url");
JSONObject object = new JSONObject();
object.put("content", uploadUrl);
object.put("preview", previewUrl);
jarr.put(i, object);
}
After the for loop, you can then get the values from the keys.
Or, if jarr already has objects...
JSONArray jarr = information;
for (int i = 0; i < allData.length(); i++ ) {
final String uploadUrl = allData.getJSONObject(i).getString("content_url");
final String previewUrl = allData.getJSONObject(i).getString("preview_url");
JSONObject object = new jarr.getJSONObject(i);
object.put("content", uploadUrl);
object.put("preview", previewUrl);
jarr.put(i, object);
}
this isnt tested, but should work. haha
Try like this,
JSONArray jsonArray;
try {
//here replace with your data object
jsonArray = new JSONArray(" [{\"type\":\"video\",\"format\":\"mp4\",\"preview_format\":\"jpg\"}, {\"type\":\"video\",\"format\":\"mp4\",\"preview_format\":\"jpg\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
jsonObject.put("content", "test value " + i);
}
Log.d("Print test", jsonArray.getJSONObject(0).toString());
Log.d("Print test", jsonArray.getJSONObject(1).toString());
} catch (
JSONException e) {
e.printStackTrace();
}
im literally new at working with JSON and I have a problem with my Web Service. With normal JSON Objects i no problems. I want to get two Arrays from the Web Service (String and Integer), so i tried to put them into two JSON Array´s and this two into a JSON Object. Now i want them to get into my Android application, but im just getting errors.
public static String constructJSON(Integer[] array, String[] array2) {
JSONObject mainObj = new JSONObject();
try {
JSONObject firstArray = new JSONObject();
firstArray.put("array0", array[0]);
firstArray.put("array1", array[1]);
firstArray.put("array2", array[2]);
firstArray.put("array3", array[3]);
firstArray.put("array4", array[4]);
JSONObject secondArray = new JSONObject();
secondArray.put("sArray0", array2[0]);
secondArray.put("sArray1", array2[1]);
secondArray.put("sArray2", array2[2]);
secondArray.put("sArray3", array2[3]);
secondArray.put("sArray4", array2[4]);
JSONArray JArr = new JSONArray();
JArr.put(firstArray);
JArr.put(secondArray);
mainObj.put("arrays", JArr);
} catch (JSONException e) {
}
return mainObj.toString();
}
And now the method in Android Studio:
private void getBW(String krankheit) {
RequestParams params = new RequestParams();
params.put("krankheit", krankheit);
// Invoke RESTful Web Service with Http parameters
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
// JSON Object
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("array1");
JSONArray secondJsonArr= obj.getJSONArray("array2");
for (int k = 0; k < 5; k++) {
Bewertung1[k] = (Integer) firstJsonArr.get(k);
}
for (int j = 0; j < 5; j++) {
medikament[j] = (String) secondJsonArr.get(j);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
I tried different solution´s, but none of them worked for me. I hope you guys can help me.
I would recommend you to use gson library for android. Its provides simple function to parse from and to json object.
Have a look at this library : https://github.com/google/gson
You switched your function istead of what you wanted it does [{}{}]
Try this:
public static String constructJSON(Integer[] array, String[] array2) {
try {
JSONArray firstArray = new JSONArray ();
firstArray.put( array[0]);
firstArray.put( array[1]);
firstArray.put( array[2]);
firstArray.put( array[3]);
firstArray.put( array[4]);
JSONArray secondArray = new JSONArray ();
secondArray.put(array2[0]);
secondArray.put( array2[1]);
secondArray.put( array2[2]);
secondArray.put( array2[3]);
secondArray.put( array2[4]);
JSONObject JArr = new JSONObject();
JArr.put("firstArr",firstArray);
JArr.put("secondArr", secondArray);
return JArr.toString();
} catch (JSONException e) {
}
return null;
}
this will give you the JSon you wanted , and this is the main code to use it:
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("firstArr");
JSONArray secondJsonArr= obj.getJSONArray("secondArr");
for (int k = 0; k < firstJsonArr.size(); k++) {
Log.e("item "+k,"item data : "+firstJsonArr.get(k));
}
for (int j = 0; j < secondJsonArr.size(); j++) {
Log.e("item "+j,"item data : "+secondJsonArr.get(j));
}
this is good for practices but later you should use a library that does these type of things for you like Gson etc...
I have a problem with parsing JsonArray response.
I take JsonObject from JsonArray, parse it and set in entity message and then that message add to ArrayList.
Problem is that in ArrayList that I want to return I always have only one message. This must be some fundamental error but I cant find it.
public ArrayList<Message> getSearchInfo(String response) {
ArrayList<Message> searchResult = new ArrayList<Message>();
int jsonMessageId = -1;
String jsonDate = "";
String jsonText = "";
String jsonAutor = "";
String jsonSource = "";
int jsonThemeID = -1;
int jsonSourceID = -1;
try {
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
Message m = new Message();
// Pulling items from the array
jsonMessageId = oneObject.getInt("MessageId");
jsonDate = oneObject.getString("CreatedDate");
jsonText = oneObject.getString("TextMessage");
jsonAutor = oneObject.getString("Autor");
jsonSource = oneObject.getString("Source");
jsonThemeID = oneObject.getInt("ThemeId");
jsonSourceID = oneObject.getInt("SourceId");
m.setMessageId(jsonMessageId);
m.setMessageText(jsonText);
m.setDate(jsonDate);
m.setAutor(jsonAutor);
m.setSource(jsonSource);
m.setThemeId(jsonThemeID);
m.setSourceId(jsonSourceID);
searchResult.add(m);
} catch (JSONException e) {
Log.d("URL EXC", "Exception 2");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return searchResult;
}
p.s. I use web-api as service and via android I take resources from service.
Any idea where is my mistake here?
You redefine your list every time in the loop.
Change your code from
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
searchResult = new ArrayList<Message>();
To
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
searchResult = new ArrayList<Message>();
for (int i = 0; i < jArray.length(); i++) {
try {
I have to build an array of some structures that i've built:
The class (Item) is built the following way: (It is shown below)
Now my problem is that im trying to parse some string number that Im getting from another place (a list in this case) to int.
But I get this error:
The method parseInt(String) in the type Integer is not applicable for
the arguments (R.string)
This is the piece of the code:
(It says the error is in ("Integer.parseInt"):
markers.add(new item(Integer.parseInt(items.get(0).get(i)), items.get(1).get(i), items.get(2).get(i), items.get(3).get(i), Integer.parseInt(items.get(4).get(i)), Integer.parseInt(items.get(5).get(i))));
its just long but its not complicated.
Thanks a lot!
Edit:
the items list is just a list of lists:
List<List<string>> items;
and the structure of the class is:
private int id;
private string title;
private string desc;
private string pub;
private int p;
private int n;
the code:
public List<List<String>> Download()
{
String data = null;
//String res = "";
try {
client = new DefaultHttpClient();// Reference to the Internet
httppost = new HttpPost(URL);
HttpResponse response = client.execute(httppost);
HttpEntity entity = response.getEntity();// get the content of the
// message
InputStream webs = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(webs,"iso-8859-1"));
StringBuffer sb = new StringBuffer("");
String l = " ";
// String nl=System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l + "\n");
}
data = sb.toString();
webs.close();
List<List<String>> all= new ArrayList<List<String>>();
all.add(new ArrayList<String>());
all.add(new ArrayList<String>());
all.add(new ArrayList<String>());
all.add(new ArrayList<String>());
all.add(new ArrayList<String>());
all.add(new ArrayList<String>());
all.add(new ArrayList<String>());
try {
JSONObject json = new JSONObject(data);
JSONArray jArray = json.getJSONArray("item");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
//res += json_data.getString("title")+"\n";
all.get(0).add(json_data.getString("id"));
}
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
//res += json_data.getString("title")+"\n";
all.get(0).add(json_data.getString("title"));
}
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
//res += json_data.getString("title")+"\n";
all.get(0).add(json_data.getString("desc"));
}
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
//res += json_data.getString("title")+"\n";
all.get(0).add(json_data.getString("pub"));
}
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
//res += json_data.getString("title")+"\n";
all.get(0).add(json_data.getString("p"));
}
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
//res += json_data.getString("title")+"\n";
all.get(0).add(json_data.getString("n"));
}
return all;
} catch (JSONException e) {
}
//return news;
} catch (Exception e) {
int x=3;
// TODO: handle exception
}
return null;
}
change Your code,
Use String insted string.
private int id;
private String title;
private String desc;
private String pub;
private int p;
private int n;
also change list
List<List<String>> items;
The type that you use, string, is apparently not java.lang.String, so you cannot give it as argument into Integer.parseInt(java.lang.String).
Other way of doing the same without changing your code is , you should call getString() in parseInt() so that getString() will return you java.lang.String, something like this :
getString(R.string.value);
Doing this will save your lot of efforts of replacing string with String.
If you open the R class you will see that it contains only numbers that are references to the compiled resources of your project.
Choice is yours :)
Cheers
in my application I'm trying to extract the values from a filter list (auto-complete field).
In that field I have [ID, Name] ex [j342234, A,S]. I was able to retrieve the whole criteria by
doing this
Object Filterlistresult = fliterList.getCriteria();
but now I want to get extract ID part only from that field. Any Ideas?
Thank you in advance.
// here I get the values from a web server and insert them to the work Vector
public void parseJSONResponceInWB(String jsonInStrFormat) {
try {
JSONObject json = new JSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("transport");
for (int i = 1; i < jArray.length(); i++) {
JSONObject j = jArray.getJSONObject(i);
ID = j.getString("ID");
Name = j.getString("Name");
WBenchVector.addElement(ID + " " + Name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// adding the values to the filter list
private void RequestAutoComplete() {
String[] returnValues = new String[WBenchVector.size()];
System.out.print(returnValues);
for (int i = 0; i < WBenchVector.size(); i++) {
returnValues[i] = (String) WBenchVector.elementAt(i);
}
autoCompleteField(returnValues);
}
// creating the filter list field
private void autoCompleteField(String[] returnValues) {
filterLst = new BasicFilteredList();
filterLst.addDataSet(ID, returnValues, "",
BasicFilteredList.COMPARISON_IGNORE_CASE);
autoFld.setFilteredList(filterLst);
}
Finally i'm getting what the user select using this
AutoFieldCriteria = filterLst.getCriteria();
Thank you Nate. I actually fixed the problem.
I converted the filterField Object to String and then I looked for the index of the first space, and substring the first word
Object AutoFieldCriteria = filterLst.getCriteria();
String AutoFieldString = AutoFieldCriteria.toString();
int spacePos = AutoFieldString.indexOf(" ");
String AutoFieldFirstWord = AutoFieldString.substring(0,spacePos);
Thanks again.