Here I am getting my data in comma seperated format.
1,2,3,4....n
Response ids are more than 300.
requestButton = (Button) findViewById(R.id.requestButton);
I want to take first 45 on button click, then again next 45 on button click and so on.
Ids should not repeat.
Is there any way how can I do that.
try {
JSONObject rob = response.getJSONObject();
JSONArray array = rob.getJSONArray("data");
fr = new ArrayList();
for (int i = 0; i < array.length(); i++) {
friend = array.getJSONObject(i);
fr.add(friend.get("id"));
formatedString = fr.toString()
.replace("[", "")
.replace("]", "");
Log.d("uid", String.valueOf(formatedString));
}
} catch (JSONException e) {
e.printStackTrace();
}
Simply pass count as parameter in your url .Thats will fetch data from server(you have to create code). Then if you want more call the same url with increased count.
first time
url="http://androidexample.com/getPage.php?count=45";
when more button clicked call the same url with increased count
url="http://androidexample.com/getPage.php?count=90";
another way is store all the value in local database when first time data loaded from server then display listview based on the count.
Related
I have an android program that passes 2 value to mySQL, that is Time in and Time out. I don`t know what happen but I have a scenario that the data passed is incomplete. For example i will create a record and the only need to put is time in after i type the time i will click save so the record is time in has a data and time out is null. After saving, my auto passer sends that data to mySQL. The next thing I will do is to edit that record to add Time Out so both of them has a data. auto passer will run after checking to my database my both of columns has a data. Now this is where the error begins, I have a button call refresh which will retrieve my data from mySQL,create a JSON of that then send it in my android after the process the returned data has no Time Out and when i check it the data in mySQL has no time out also even i add it. I dont know what happened
What I did in my Java is to create a JSONArray the convert it to string the pass it in my php file then my php file decodes it then loop it while saving to database.
This is how i create a json
JSONArray vis_array = new JSONArray();
Cursor unsync_vis = Sync.Unsync_Visit_All();
while (unsync_vis.moveToNext()) {
JSONObject vis_data = new JSONObject();
try {
vis_data.put("t1", formatInsert_n(unsync_vis.getString(unsync_vis.getColumnIndex("t1"))));
vis_data.put("t2", formatInsert_n(unsync_vis.getString(unsync_vis.getColumnIndex("t2"))));
vis_array.put(vis_data);
} catch (JSONException e) {
e.printStackTrace();
Log.e("Auto Sync Error", e.getMessage());
}
}
public String formatInsert_n(String data) {
if (TextUtils.isEmpty(data) || data.length() == 0) {
data = "null";
} else {
data = data.replace("'", "''");
data = data.replace("null", "");
if (data.toString().matches("")) {
data = "null";
} else {
data = "'" + data + "'";
}
}
return data;
}
after creating that json, i will convert it to string the pass it using stringRequest then in my php i will decode it use for loop the save it in mySQL
Here is the php code
<?php
header('Content-Type: application/json');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$insert_visit_new = isset($_POST['insert_visit_new']) ? $_POST['insert_visit_new'] : "";
if ($insert_visit_new != "") {
$vis_array = json_decode($insert_visit_new, true);
$vis_count = count($vis_array);
for ($i = 0; $i < $vis_count; $i++) {
$vis = $vis_array[$i];
$t1 = $vis['t1'];
$t2 = $vis['t2'];
$ins_sql = "INSERT INTO table t1,t2 VALUES ('$t1','$t2') ON DUPLICATE KEY UPDATE t1 = $t1,t2 = $t2"
$stmt = $DB->prepare($ins_sql);
$stmt->execute();
}
}
echo "done";
?>
by the way the code above is inside an AsyncTask and the class is a BroadcastReceiver
is the cause is i dont unregister my BroadcastReceiver?
or my jsonArray name from this class and inside my refresh button are same?
my question is whats wrong? looks like it still passes the old data. any help is appreciated TYSM
I have a json array of all names and contacts on my phone, looks something like this:
[{"name":"andy","phone_number":"+123"},{"name":"bob","phone_number":"+456"},{"name":"chris","phone_number":"+789"}]
I check the phone numbers against phone numbers in a db, if there's a match I want to show the name in the recycler view, if no match, then show just the number.
For example, +123, yes, it is in the db, so show andy in the cell in recyclerview. +789 is not in the db, so show +789 in the cell.
Here's what I'm working with so far: it works when there is a match, the if part, but I don't know how to deal with the else part (for when there is no match). If I uncomment my else code it always jumps straight to there.
public void onResponse(String response) {
try {
//name our JSONObject User_Private_Public_Obj, which is response from server
//the response from server will be like:
//{"private_review_ids":[{"reviewid":7,"username":"+123"},{"reviewid":14,"username":"+456"}]}
JSONObject User_Private_Public_Obj = new JSONObject(response);
//Now break up the response from server
//We want the JSON Array part, "private_review_ids"
JSONArray private_ids = User_Private_Public_Obj.getJSONArray("private_review_ids");
for
//get the number of objects in User_Private_Public_Obj
(int i = 0; i < private_ids.length(); i++)
{
//for each object in the array private_ids, name it obj
//each obj will consist of reviewid and username
JSONObject obj = private_ids.getJSONObject(i);
Review review = new Review();
//get the string from sharedpreferences, AllPhonesandNamesofContacts,
//it will be like [{"phone_number":"+123","name":"andy"}, etc...]
//we want this so we can display phone name in recyclerView, if it's a contact
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("AllPhonesandNamesofContacts", "0");
//convert the string above into a json array
JSONArray jsonArray = new JSONArray(json_array);
//set a string to the phone number from the DB,
//the phone number of the person who made the review
phoneNoInDB = obj.getString("username");
//set the setter to the phone number string, the string is
//the phone number of the person who made the review
review.setPhoneNumberofUserFromDB(phoneNoInDB);
//jsonArray is our All Phones and Names of Contacts array
int matching = jsonArray.length();
for (int n = 0; n < matching; n++) {
try {
//for every object in "All Phones and Names of Contacts" array...
JSONObject object = jsonArray.getJSONObject(n);
//if the review maker is a contact...that is,
//if the phone_number in AllPhonesandNamesofContacts equals
//the phone number in the DB
if (object.getString("phone_number").equals(phoneNoInDB)) {
//just for testing purposes...
Toast.makeText(NewActivity.this, object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
//then rip out the other part of the object, the name in
// AllPhonesandNamesofContacts
//of the person who made the review
review.setphoneNameonPhone(object.getString("name"));
//add the review to the sharedReviewList
reviewList.add(review);
}
/* else {
//just for testing...
Toast.makeText(NewActivity.this, " should be green" + object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
review.setphoneNameonPhone(object.getString("phone_number"));
//add the review to the sharedReviewList
//reviewList.add(review);
}*/
} catch (JSONException e) {
System.out.println("error in if else");
//Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
//set the adapter to show the random reviews
recyclerView.setAdapter(uAdapter);
I have been wondering if there is a way to access all the twitter followers list.
We have tried using call to the REST API via twitter4j:
public List<User> getFriendList() {
List<User> friendList = null;
try {
friendList = mTwitter.getFollowersList(mTwitter.getId(), -1);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (TwitterException e) {
e.printStackTrace();
}
return friendList;
}
But it returns only a list of 20 followers.
I tried using the same call in loop, but it cause a rate limit exception - says we are not allowed to make too many requests in a small interval of time.
Do we have a way around this?
You should definitely use getFollowersIDs. As the documentation says, this returns an array (list) of IDs objects. Note that it causes the list to be broken into pages of around 5000 IDs at a time. To begin paging provide a value of -1 as the cursor. The response from the API will include a previous_cursor and next_cursor to allow paging back and forth.
The tricky part is to handle the cursor. If you can do this, then you will not have the problem of getting only 20 followers.
The first call to getFollowersIDs will need to be given a cursor of -1. For subsequent calls, you need to update the cursor value, by getting the next cursor, as done in the while part of the loop.
long cursor =-1L;
IDs ids;
do {
ids = twitter.getFollowersIDs(cursor);
for(long userID : ids.getIDs()){
friendList.add(userID);
}
} while((cursor = ids.getNextCursor())!=0 );
Here is a very good reference:
https://github.com/yusuke/twitter4j/blob/master/twitter4j-examples/src/main/java/twitter4j/examples/friendsandfollowers/GetFriendsIDs.java
Now, if the user has more than around 75000 followers, you will have to do some waiting (see Vishal's answer).
The first 15 calls will yield you around 75000 IDs. Then you will have to sleep for 15 minutes. Then make another 15 calls, and so on till you get all the followers. This can be done using a simple Thread.sleep(time_in_milliseconds) outside the for loop.
Just Change like this and try, this is working for me
try {
Log.i("act twitter...........", "ModifiedCustomTabBarActivity.class");
// final JSONArray twitterFriendsIDsJsonArray = new JSONArray();
IDs ids = mTwitter.mTwitter.getFriendsIDs(-1);// ids
// for (long id : ids.getIDs()) {
do {
for (long id : ids.getIDs()) {
String ID = "followers ID #" + id;
String[] firstname = ID.split("#");
String first_Name = firstname[0];
String Id = firstname[1];
Log.i("split...........", first_Name + Id);
String Name = mTwitter.mTwitter.showUser(id).getName();
String screenname = mTwitter.mTwitter.showUser(id).getScreenName();
// Log.i("id.......", "followers ID #" + id);
// Log.i("Name..", mTwitter.mTwitter.showUser(id).getName());
// Log.i("Screen_Name...", mTwitter.mTwitter.showUser(id).getScreenName());
// Log.i("image...", mTwitter.mTwitter.showUser(id).getProfileImageURL());
}
} while (ids.hasNext());
} catch (Exception e) {
e.printStackTrace();
}
Try This...
ConfigurationBuilder confbuilder = new ConfigurationBuilder();
confbuilder.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(secretToken)
.setOAuthConsumerKey(TwitterOAuthActivity.CONSUMER_KEY)
.setOAuthConsumerSecret(TwitterOAuthActivity.CONSUMER_SECRET);
Twitter twitter = new TwitterFactory(confbuilder.build()).getInstance();
PagableResponseList<User> followersList;
ArrayList<String> list = new ArrayList<String>();
try
{
followersList = twitter.getFollowersList(screenName, cursor);
for (int i = 0; i < followersList.size(); i++)
{
User user = followersList.get(i);
String name = user.getName();
list.add(name);
System.out.println("Name" + i + ":" + name);
}
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , list));
listView.setVisibility(View.VISIBLE);
friend_list.setVisibility(View.INVISIBLE);
post_feeds.setVisibility(View.INVISIBLE);
twit.setVisibility(View.INVISIBLE);
}
This is a tricky one.
You should specify whether you're using application or per user tokens and the number of users you're fetching followers_ids for.
You get just 15 calls per 15 minutes in case of an application token. You can fetch a maximum of 5000 followers_ids per call. That gives you a maximum of 75K followers_ids per 15 minutes.
If any of the users you're fetching followers_ids for has over 75K followers, you'll get the rate_limit error immediately. If you're fetching for more than 1 user, you'll need to build strong rate_limit handling in your code with sleeps and be very patient.
The same applies for friends_ids.
I've not had to deal with fetching more than 75K followers/friends for a given user but come to think of it, I don't know if it's even possible anymore.
Hi I'm using the Google Sheets API v4 for Java.
I want to make a Server List where I register up new Server IP's for my own small project. At the moment I can append a new Entry at a empty row using
AppendCellsRequest appendCellReq = new AppendCellsRequest();
appendCellReq.setSheetId(0);
appendCellReq.setRows(rowData);
appendCellReq.setFields("userEnteredValue");
The Problem is now, that I want delete this row later, so I need to figure out how to find it later. My Idea was to add a UniqueID or to search for the exact added Values or to remember the row number. However a way would it be to find and replace all cells. But I would rather have a way to get the row number of my added data.
I'm very happy to hear some advices.
Since long search I finaly found an answer. There are tutorials which indeed made it possible to append a row, but wasnt able to return in which Row they inserted. With this code its now possible. I found it after hours of searching somewhere. It is not the best code, but it works and can be modified.
String range = "A1"; // TODO: Update placeholder value.
// How the input data should be interpreted.
String valueInputOption = "RAW"; // TODO: Update placeholder value.
// How the input data should be inserted.
String insertDataOption = "INSERT_ROWS"; // TODO: Update placeholder value.
// TODO: Assign values to desired fields of `requestBody`:
ValueRange requestBody = new ValueRange();
List<Object> data1 = new ArrayList<Object>();
data1.addAll(Arrays.asList(dataArr));
List<List<Object>> data2 = new ArrayList<List<Object>>();
data2.add(data1);
requestBody.setValues(data2);
Sheets sheetsService;
try {
sheetsService = getSheetsService();
Sheets.Spreadsheets.Values.Append request = sheetsService.spreadsheets().values().append(spreadSheetId,
range, requestBody);
request.setValueInputOption(valueInputOption);
request.setInsertDataOption(insertDataOption);
AppendValuesResponse response = request.execute();
// TODO: Change code below to process the `response` object:
Logger.println(response.getTableRange());
String startCell = response.getTableRange().split(":")[1];
String colString = startCell.replaceAll("\\d", "");
String row = startCell.replaceAll(colString, "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have a JSON with an array of 3 objects. So when I retrieveEventJSON(), I am simply setting the attributes to an Event object. And when I call the plotEventOnMap() from another activity, I expect to see 3 markers on the map.
public void retrieveEventJSON() throws JSONException {
String page;
JSONArray jsonArray;
try {
// Code to retrieve data from servlet
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("Events");
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void plotEventOnMap(Context context) {
graphicIcon = new PictureMarkerSymbol(res);
Point p = new Point(Double.parseDouble(eventModel.getEventX()),
Double.parseDouble(eventModel.getEventY()));
Symbol symbol = graphicIcon;
HashMap<String, Object> attrMap = new HashMap<String, Object>();
attrMap.put("eventName", eventModel.getEventName());
attrMap.put("eventBy", eventModel.getEventBy());
ENeighbourhoodActivity.graphicsLayer.addGraphic(new Graphic(p, symbol,
attrMap));
}
But with these codes, it just display the last row of record in my JSON instead of looping and plot each of them. Any guides?
Thanks in advance.
You need to call .plotEventOnMap(), or otherwise do something with the EventModel you've constructed, from inside your loop, after setting all the EventModel properties. At the moment, you're just overwriting your EventModel without ever using it.
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
}
Just before the loop ends, you need to do something with the EventModel you've now constructed. This might be plotting it, or adding it to some collection, or whatever. But at the moment, you're going straight back into the loop, and then in the next iteration, overwriting all the good work you've done. The reason you're only ending up with the last one is that when you've done the last iteration, what's left in eventModel is what you wrote the last time you went through the loop.
In fact I think you also want
EventModel eventModel = new EventModel();
as the first thing inside your loop. (I don't know if this is exactly right because we haven't seen the code for EventModel so I don't know what the constructor looks like.) If you want to keep a List (or similar) of all of them, you need to make sure they're all different instances.
I would suggest recasting like this:
List<EventModel> events = new ArrayList<EventModel>(); //NEW
for (int i = 0; i < length; i++) {
EventModel eventModel = new EventModel(); //NEW
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
events.add(eventModel); //NEW
}
After the loop has finished, you'll have a list of EventModels that you can send to your plotting method or whatever's appropriate.
eventModel.setEventName(eventName); returns the latest element added to it because on every iteration you are resetting it.
You may add the object to the list after each iteration so that the list will have the elements. Declare the your EventModel object inside the for loop to have the instance for every iteration.
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
EventModel eventModel=new eventModel();
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
list.add(eventModel);
}