How do you get tweets for a particular hashtag using twitter's fabric sdk for android?
the current documentation only shows getting tweets by ID.
List<Long> tweetIds = Arrays.asList(503435417459249153L,510908133917487104L,
473514864153870337L,
477788140900347904L);
final TweetViewFetchAdapter adapter =
new TweetViewFetchAdapter<CompactTweetView>(
TweetListActivity.this);
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(SecretKet);
User user;
AccessToken newAcc = new AccessToken(getoken, getokensecret);
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(newAcc);
try {
List<twitter4j.Status> statuslist = new ArrayList<twitter4j.Status>();
//23 for hash #
Query AA = new Query("%23" + HASH_TAG_string);
AA.setCount(20);
//if (!statusid.equals("")) {
//long l = Long.parseLong(statusid);
//AA.setMaxId(l - 1);
//}
QueryResult result = twitter.search(AA);
statuslist = result.getTweets();
long id = result.getMaxId();
System.out.println("Count : " + result.getTweets().size());
mList = new ArrayList<GetterSetteList>();
for (twitter4j.Status status : statuslist) {
GetterSetteList obj = new GetterSetteList();
String sts = status.getText();
obj.setStatusID("" + status.getId());
Log.d("STATE", sts);
System.out.println("=======ID=====" + status.getId());
User u = status.getUser();
obj.setImageURL(u.getProfileImageURLHttps());
obj.setmStatus(status.getText());
Date date = status.getCreatedAt();
obj.setStatustime(date.toString());
obj.setUser_id(u.getScreenName());
obj.setUsername(u.getName());
mList.add(obj);
}
// user = twitter.showUser("jaswinderwadali");
// System.out.println(user.getName());
} catch (TwitterException e) {
// TODO Auto-generated catch block
flag = 1;
Log.v("ERROR", "GetHastTagdata" + e.toString());
e.printStackTrace();
}
In this moment it's more easy.
import com.twitter.sdk.android.tweetui.TweetTimelineListAdapter;
import com.twitter.sdk.android.tweetui.UserTimeline;
public class TimelineActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timeline);
final SearchTimeline searchTimeline = new SearchTimeline.Builder().query("#twitterflock").build();
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter(this, searchTimeline);
setListAdapter(adapter);
}
}
Regards
Related
I'm trying to add alert dialog to my project to notify the users if there has return data from previous activity, however in my approach the if statement has a problem or something missing , even without return data the alert dialog is always pop up any suggestion or idea will be appreciated.
//This part is my method
public void dataReceive(){
//requesting data from server
//adding parameters
RequestParams params = new RequestParams();
SessionManager sessionManager = new SessionManager(this);
HashMap<String, String> user = sessionManager.getUserDetails();
if (user != null) {
String uid = user.get(SessionManager.USER_ID);
params.put("user_id", uid);
}
try{
String name = user.get(SessionManager.KEY_NAME);
username = name;
}catch (Exception e){
}
//This part is my approach
Bundle tokens = this.getIntent().getExtras();
if(tokens != null) {
final PendingRequestPojo pendingRequestPojo = new PendingRequestPojo();
responseid = tokens.getString("responseid");
requestid = tokens.getString("requestid");
//Toast.makeText(getApplicationContext(), "responseid :" + responseid + "\nrequestid : " +
//requestid, Toast.LENGTH_SHORT).show();
alert = new AlertDialog.Builder(SplashActivity.this);
alert.setTitle("ThirdWheel Payment Response");
alert.setIcon(R.drawable.thinrdwheel_alert);
alert.setMessage("Your Payment Was Successfull" + " " + username +
"Thank you, we Hope you can ride with us Again ");
alert.setCancelable(true);
alert.setPositiveButton("Thanks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
changement();
Updatepayment(pendingRequestPojo.getRide_id(), "PAID");
}
}).show();
} else {
changement();
}
}
Your code has to be as below
public void dataReceive(){
//requesting data from server
//adding parameters
RequestParams params = new RequestParams();
SessionManager sessionManager = new SessionManager(this);
HashMap<String, String> user = sessionManager.getUserDetails();
if (user != null) {
String uid = user.get(SessionManager.USER_ID);
params.put("user_id", uid);
}
try{
String name = user.get(SessionManager.KEY_NAME);
username = name;
}catch (Exception e){
}
//This part is my approach
Bundle tokens = this.getIntent().getExtras();
if(tokens != null &&
tokens.containsKey("responseid") && tokens.containsKey("requestid")) {
final PendingRequestPojo pendingRequestPojo = new PendingRequestPojo();
responseid = tokens.getString("responseid");
requestid = tokens.getString("requestid");
//Toast.makeText(getApplicationContext(), "responseid :" + responseid + "\nrequestid : " +
//requestid, Toast.LENGTH_SHORT).show();
alert = new AlertDialog.Builder(SplashActivity.this);
alert.setTitle("ThirdWheel Payment Response");
alert.setIcon(R.drawable.thinrdwheel_alert);
alert.setMessage("Your Payment Was Successfull" + " " + username +
"Thank you, we Hope you can ride with us Again ");
alert.setCancelable(true);
alert.setPositiveButton("Thanks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
changement();
Updatepayment(pendingRequestPojo.getRide_id(), "PAID");
}
}).show();
} else {
changement();
}
}
I'm a in the process of understanding CouchBase Lite for android application,as far i only know how to create a manager, database, document and view.However i want to load data from the documents and show it in the app but failed after trying several times and following some tutorials.Is there a way i can save and load this data and manipulate it in Listview? The code i used til now is the following:
public class MainActivity extends AppCompatActivity {
final String dbname = "userdils";
private String docId = "2";
private Manager manager;
private Database couchDb;
private TextView tvLogWindow;
private EditText u_id;
private EditText pwd;
Button btn_login,btn_login1;
TextView version;
private String TAG = "CouchBaseLiteLoginPage";
String email;
String password;
private UserDetails ud,udd;
private ArrayList<UserDetails> ud1;
String doc_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//tvLogWindow = (TextView) findViewById(R.id.tv_log_window);
u_id = (EditText) findViewById(R.id.user_id);
pwd = (EditText) findViewById(R.id.password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login1 = (Button) findViewById(R.id.btn_login1);
/*tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nStart Couchbase App!");
if (!Manager.isValidDatabaseName(dbname)) {
tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nBad couchbase db name!");
return;
}*/
createManager();
createCouchdb();
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d(TAG, "Create: " + 1);
login();
}
});
btn_login1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Log.d(TAG, "View: " + 2);
docView();
// retrieveMovie(manager,couchDb,docId);
}
});
//createDocument(docId);
//Document retrievedDocument = retrieveDocument();
/*updateDocument(retrievedDocument);
deleteDocument(retrievedDocument);*/
//tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nEnd the App!");
}
public void createManager() {
try {
manager = new Manager(new AndroidContext(getApplicationContext()), Manager.DEFAULT_OPTIONS);
} catch (IOException e) {
return;
}
}
public void createCouchdb() {
try {
couchDb = manager.getDatabase(dbname);
} catch (CouchbaseLiteException e) {
return;
}
}
public Document retrieveDocument(String docId) {
Document retrievedDocument = couchDb.getDocument(docId);
Log.d(TAG, "Retrieved Data:- " + String.valueOf(retrievedDocument.getProperties()));
// Let's find the documents that have conflicts so we can resolve them:
Query query = couchDb.createAllDocumentsQuery();
query.setAllDocsMode(Query.AllDocsMode.ALL_DOCS);
try {
QueryEnumerator result = query.run();
for (Iterator<QueryRow> it = result;
it.hasNext(); ) {
QueryRow row = it.next();
Object movieObj = row.getDocument().getProperties().get("user_det");
Gson gson = new Gson();
String jsonString = gson.toJson(movieObj, Map.class); //Convert the object to json string using Gson
UserDetails movie = gson.fromJson(jsonString, UserDetails.class); //convert the json string to Movie object
if(movie.getUser_pwd().equals("000000")) {
Log.i("getMovieFromDocument", "movie>>>" + movie.getUser_nm());
}
Log.d(TAG, "Document Data ID:- " + row.getDocumentId());
}
}
catch (CouchbaseLiteException e) {
}
// Log.d(TAG, "User Name:- " +(String)retrievedDocument.getProperty("user_det"));
return retrievedDocument;
}
public void login() {
Log.d(TAG, "validate: " + 4);
email = u_id.getText().toString().trim();
password = pwd.getText().toString().trim();
Log.d(TAG, "login: " + 5);
btn_login.setEnabled(false);
ud = new UserDetails();
udd = new UserDetails();
ud1 = new ArrayList<UserDetails>();
ud.setUser_nm(email);
ud.setUser_pwd(password);
udd.setUser_nm("NAME_007");
udd.setUser_pwd("PWD_007");
ud1.add(ud);
ud1.add(udd);
createDocument(docId,ud1);
}
public void createDocument(String docId,ArrayList<UserDetails> ud) {
// create some dummy data
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar calendar = GregorianCalendar.getInstance();
String currentTimeString = dateFormatter.format(calendar.getTime());
//Movie movie = new Movie("Star War", "The force awakens!", 120);
// put those dummy data together
Map<String, Object> docContent = new HashMap<String, Object>();
docContent.put("message", "Hey Couchbase Lite");
docContent.put("creationDate", currentTimeString);
docContent.put("user_det", ud);
//docContent.put("movie", movie);
Log.d(TAG, "userDetails: " + String.valueOf(docContent));
// create an empty document, add content and write it to the couchDb
//Document document = new Document(couchDb,docId);
//Document document = couchDb.createDocument();
Document document = new Document(couchDb,docId);
try {
document.putProperties(docContent);
//doc_id = document.getId();
// Document retrieveDoc = retrieveDocument(docId);
Log.d(TAG, "Document Count couchDb : " + couchDb.getDocumentCount());
} catch (CouchbaseLiteException e) {
}
}
public void docView() {
// Document retrievedDocument = retrieveDocument(docId);
Document retrievedDocument = retrieveDocument(docId);
}
private void retrieveMovie(Manager manager, Database couchDb, String docId) {
Document retrievedDocument = couchDb.getDocument(docId); // Retrieve the document by id
Object movieObj = retrievedDocument.getProperties().get("user_det");
Gson gson = new Gson();
String jsonString = gson.toJson(movieObj, Map.class); //Convert the object to json string using Gson
UserDetails movie = gson.fromJson(jsonString, UserDetails.class); //convert the json string to Movie object
Log.i("getMovieFromDocument", "jsonString>>>" + jsonString);
Log.i("getMovieFromDocument", "movie>>>" + movie.getUser_nm());
}
}
Not clear what tutorials you followed and what errors you observed. Anyways, check out this blog that discusses how you can load documents within a RecyclerView with Couchbase Lite as a data source. The recommended pattern can be easily applied to ListView or just use a RecyclerView instead of a ListView in your app.
i'm trying to make an app that can write google calendar event from user input and also read list of events from my google calendar. I have tried to look for many example but most of them only show very basic example.
I'm using alertdialog to get input from user and wanted to send the data to AsyncTask. I think where i'm wrong is when calling the createEvent() in mActivity.updateResultsText1(createEvent())
Here is my calendar_activity code.
public class CalendarActivity extends FragmentActivity implements OnClickListener {
private ListView listevent;
private Button addeventbtn;
private Button deleteeventbtn;
public String nama, tanggal, mulai, beres;
private ArrayAdapter<String> adapter;
List<String> eventlist =new ArrayList<String>();
com.google.api.services.calendar.Calendar mService;
GoogleAccountCredential credential;
private TextView mStatusText;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
static final int REQUEST_ACCOUNT_PICKER = 1000;
static final int REQUEST_AUTHORIZATION = 1001;
static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = { CalendarScopes.CALENDAR };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
listevent=(ListView)findViewById(R.id.kalenderlist);
addeventbtn=(Button) findViewById(R.id.addeventbutton);
addeventbtn.setOnClickListener(this);
deleteeventbtn=(Button)findViewById(R.id.deleteevent);
deleteeventbtn.setOnClickListener(this);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,eventlist);
mStatusText = (TextView)findViewById(R.id.statustext);
mStatusText.setTypeface(null, Typeface.BOLD);
mStatusText.setText("Retrieving data...");
// Initialize credentials and service object.
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff())
.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
mService = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential)
.setApplicationName("Google Calendar API Android")
.build();
}
public void onClick(View v) {
if (v.getId()==R.id.addeventbutton) {
AlertDialog.Builder addeventdialog = new AlertDialog.Builder(CalendarActivity.this);
View mViewaddevent = getLayoutInflater().inflate(R.layout.activity_addevent,null);
final EditText namaevent=(EditText)mViewaddevent.findViewById(eventname);
final EditText tanggalevent=(EditText)mViewaddevent.findViewById(eventdate);
final EditText mulaievent=(EditText)mViewaddevent.findViewById(R.id.eventtimestart);
final EditText beresevent=(EditText)mViewaddevent.findViewById(R.id.eventtimeend);
addeventdialog.setView(mViewaddevent);
final AlertDialog dialog = addeventdialog.create();
dialog.show();
Button addbutton=(Button)mViewaddevent.findViewById(R.id.eventsavebutton);
addbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (!namaevent.getText().toString().isEmpty()&&!tanggalevent.getText().toString().isEmpty()&&!mulaievent.getText().toString().isEmpty()&&!beresevent.getText().toString().isEmpty()){
nama = namaevent.getText().toString();
tanggal = tanggalevent.getText().toString();
mulai = mulaievent.getText().toString();
beres = beresevent.getText().toString();
dialog.dismiss();
}
else {
Toast.makeText(CalendarActivity.this,"Masukan tidak lengkap",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
});
Button cancelbtn=(Button)mViewaddevent.findViewById(R.id.eventcancelbutton);
cancelbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
if (v.getId()==R.id.deleteevent) {
}
}
public void updateResultsText(final List<String> dataStrings) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (dataStrings == null) {
mStatusText.setText("Error retrieving data!");
} else if (dataStrings.size() == 0) {
mStatusText.setText("No data found.");
} else {
mStatusText.setText("Data retrieved using" +
" the Google Calendar API:");
eventlist.addAll(dataStrings);
listevent.setAdapter(adapter);
}
}
});
}
public void updateResultsText1(final String dataStrings1) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (dataStrings1 == null) {
mStatusText.setText("Error retrieving data!");
} else if (dataStrings1 == "") {
mStatusText.setText("No data found.");
} else {
mStatusText.setText("Data retrieved using" +
" the Google Calendar API:");
}
}
});
}
And here is my AsyncTask Code.
public class ApiAsyncTask extends AsyncTask<Void, Void, String> {
private CalendarActivity mActivity;
ApiAsyncTask(CalendarActivity activity) {
this.mActivity = activity;
}
#Override
protected String doInBackground(Void... params) {
try {
mActivity.clearResultsText();
mActivity.updateResultsText(getDataFromApi());
mActivity.updateResultsText1(createEvent());
} catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
mActivity.showGooglePlayServicesAvailabilityErrorDialog(
availabilityException.getConnectionStatusCode());
} catch (UserRecoverableAuthIOException userRecoverableException) {
mActivity.startActivityForResult(
userRecoverableException.getIntent(),
CalendarActivity.REQUEST_AUTHORIZATION);
} catch (IOException e) {
mActivity.updateStatus("The following error occurred: " +
e.getMessage());
}
return null;
}
private List<String> getDataFromApi() throws IOException {
// List the next 20 events from the primary calendar.
DateTime now = new DateTime(System.currentTimeMillis());
List<String> eventStrings = new ArrayList<String>();
Events events = mActivity.mService.events().list("primary")
.setMaxResults(20)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
List<Event> items = events.getItems();
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
if (start == null) {
// All-day events don't have start times, so just use
// the start date.
start = event.getStart().getDate();
}
eventStrings.add(
String.format("%s (%s)", event.getSummary(), start));
}
return eventStrings;
}
private String createEvent() throws IOException {
Event event2 = new Event()
.setSummary(mActivity.nama);
DateTime startDateTime = new DateTime(mActivity.tanggal+"T"+mActivity.mulai+":00+07:00");
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("Asia/Jakarta");
event2.setStart(start);
DateTime endDateTime = new DateTime(mActivity.tanggal+"T"+mActivity.beres+":00+07:00");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("Asia/Jakarta");
event2.setEnd(end);
String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=1"};
event2.setRecurrence(Arrays.asList(recurrence));
String calendarId = "primary";
try {
event2 = mActivity.mService.events().insert(calendarId, event2).execute();
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("Event created: %s\n", event2.getHtmlLink());
Log.e("Event", "created : " + event2.getHtmlLink());
String eventStrings = "created : " + event2.getHtmlLink();
return eventStrings;
}
Here is what my app looks like Calendar activity and Addevent alertDialog. I also have another problem. The Listview to put event list from reading Google Calendar event only shows 1 event. If i use textview instead of Listview, and joining all event into one string, 20 events can be showed.
Thanks for reading my question and go through my bad code. Hopefully you can answer them.
I have integrated fabric digits in my android app,After successful login app will navigate to home screen ,But if i check recent apps from device hardware button ,It opens two apps one is home activity of my app and other one is enter your mobile number screen provided by digits,How to fix this.
here is my code for digits login
#Override
public void onCreate() {
super.onCreate();
authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new TwitterCore(authConfig), new Digits());
// Digits.authenticate(authCallback, R.style.AppBaseTheme);
authCallback = new AuthCallback() {
#Override
public void success(DigitsSession session, String phoneNumber) {
// Do something with the session
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
TwitterAuthToken authToken = (TwitterAuthToken) session.getAuthToken();
DigitsOAuthSigning oauthSigning = new DigitsOAuthSigning(authConfig, authToken);
Map<String, String> authHeaders = oauthSigning.getOAuthEchoHeadersForVerifyCredentials();
///call verification async
retrieveValuesFromListMethod(authHeaders);
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
// phone must begin with '+'
Phonenumber.PhoneNumber numberProto = phoneUtil.parse(phoneNumber, "");
countryCode = numberProto.getCountryCode();
phone = numberProto.getNationalNumber();
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
lookupPreference = getApplicationContext()
.getSharedPreferences("lookupPreference",
MODE_PRIVATE);
Gson gson = new Gson();
String json = lookupPreference.getString("user", "");
user = gson.fromJson(json, User.class);
user.setPhoneNumber(phone + "");
user.setCountryCode(countryCode + "");
user.setCountry("");
json = gson.toJson(user);
SharedPreferences.Editor prefsEditor = lookupPreference.edit();
prefsEditor.putString("user", json);
prefsEditor.commit();
Intent i = new Intent(getApplicationContext(), VerifyNumber.class);
Bundle b = new Bundle();
b.putString("digitHeader", new JSONObject(authHeaders).toString());
i.putExtra("values", b);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
#Override
public void failure(DigitsException exception) {
// Do something on failure
}
};
mInstance = this;
// Register LocalyticsActivityLifecycleCallbacks
registerActivityLifecycleCallbacks(new LocalyticsActivityLifecycleCallbacks(
this));
}
I've built Twitter into my android application using Twitter4j api to view the tweets of one user. However it is only bringing up 7 tweets. I want at least 20...This is strange because I have set the count to 50..Can anyone help? Thanks
public class Twitter extends Activity{
LinearLayout tweets;
Context cont;
List<Status> statuses;
String separatorText = "test";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitter);
cont = this;
statuses = new ArrayList<Status>();
tweets = (LinearLayout) findViewById(R.id.twitter_main_content);
if(Network.CheckInternet(this)){
new tweets().execute();
} else {
Toast toast = Toast.makeText(this, getResources().getString(R.string.nointernet), Toast.LENGTH_SHORT);
toast.show();
}
}
public void QueryTweets(){
ScrollView sView = new ScrollView(cont);
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);
LinearLayout layout = new LinearLayout(cont);
layout.setOrientation(1);
if(statuses.size()>0){
for(int i=0; i<statuses.size(); i++){
boolean addSeparator = false;
if(i==0){
addSeparator = true;
}
View TweetItem = LayoutInflater.from(getBaseContext()).inflate(R.layout.xmllisting_tweet, null);
TweetItem.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
TextView tweet = (TextView) TweetItem.findViewById(R.id.xmllisting_tweet_title);
tweet.setText(statuses.get(i).getText());
TextView tweet_posted = (TextView) TweetItem.findViewById(R.id.xmllisting_tweet_post_details);
tweet_posted.setText(statuses.get(i).getCreatedAt().toLocaleString());
final int IntToUse = i;
TweetItem.setOnClickListener(new OnClickListener(){
public void onClick(View v){
String url = "https://twitter.com/" + statuses.get(IntToUse).getUser().getScreenName() + "/status/" + statuses.get(IntToUse).getId();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
//load image asynchronously - background task
ImageView imgThmb = (ImageView) TweetItem.findViewById(R.id.xmllisting_image);
loadImage downloader = new loadImage(imgThmb, false);
downloader.execute(statuses.get(i).getUser().getBiggerProfileImageURL());
//compare dates of listings to check if separator needed
String dateCompare = statuses.get(i).getCreatedAt().toGMTString().substring(0, 11);
if(!dateCompare.equals(separatorText)){
separatorText = dateCompare;
addSeparator = true;
}
if(addSeparator){
View feedSep = LayoutInflater.from(getBaseContext()).inflate(R.layout.tweet_separator, null);
feedSep.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
TextView sepText = (TextView) feedSep.findViewById(R.id.tweet_separator);
sepText.setText(separatorText);
layout.addView(feedSep);
}
layout.addView(TweetItem);
}
}
sView.addView(layout);
tweets.addView(sView);
}
private class tweets extends AsyncTask<String, Void, Long>{
protected void onPostExecute(Long result) {
QueryTweets();
}
#Override
protected Long doInBackground(String... args) {
long totalSize = 0;
try {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("xxx")
.setOAuthConsumerSecret("xxx")
.setOAuthAccessToken("xxx")
.setOAuthAccessTokenSecret("xxx");
TwitterFactory tf = new TwitterFactory(cb.build());
//AccessToken accessToken = new AccessToken(SessionVariables.twitter_access_key, SessionVariables.twitter_access_secret);
//twitter4j.Twitter twitter = tf.getInstance(accessToken);
twitter4j.Twitter twitter = tf.getInstance();
String searchText = "CFABUK";
Query qry = new Query(searchText);
qry.setCount(50);
QueryResult qr;
try{
qr = twitter.search(qry);
for(int i=0; i<qr.getTweets().size(); i++){
twitter4j.Status status = qr.getTweets().get(i);
if(searchText.equals(status.getUser().getScreenName())){
statuses.add(status);
}
}
} catch(TwitterException e){
e.printStackTrace();
}
} catch (Exception e) {
Log.e("TwitterFeed", "Error: " + e.toString());
}
return totalSize;
}
}
}
You should use Paging,
take a look at:
Working with timelines, pages
or
Twitter4j Code-Examples - Paging
or
Twitter4j Paging javadoc
EDIT in your case I would use this:
and here's how Ive managed to get 100 tweets (Im writing tweets to SQLite DB, but Pagination would be the same in your case)
void fetch_timeline(){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
List<Status> statuses;
int count= 100;
try {
statuses = Constants.TwConst.getHomeTimeline(new Paging().count(count)); // HERE'S WHAT WILL PROBABLY HELP YOU
for(Status status: statuses){
// HERE I PARSE TWEETS AND WRITE THEM TO DATABASE
}
} catch (TwitterException e) {
e.printStackTrace();
}
}