Hi I'm trying to retrieve public tweets from twitter but it seems like there is no explanation for it. I have the below code but it's not working. Any idea if this is an outdated code and if you have any sample examples that I could have a look at would be much appreciated.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"", "Loading. Please wait...", true);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new
HttpGet("http://search.twitter.com/search.json?q=android");
HttpResponse rp = hc.execute(get);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweet tweet = new Tweet();
tweet.content = session.getString("text");
tweet.author = session.getString("from_user");
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new TweetListAdaptor(
MainActivity.this, R.layout.list_item, tweets));
}
}
private class TweetListAdaptor extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public TweetListAdaptor(Context context,
int textViewResourceId,
ArrayList<Tweet> items) {
super(context, textViewResourceId, items);
this.tweets = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Tweet o = tweets.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
tt.setText(o.content);
bt.setText(o.author);
return v;
}
}
}
If you visit http://search.twitter.com/search.json?q=android in a Web browser, you will see:
{"errors":[{"message":"The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.","code":64}]}
Any idea if this is an outdated code
Yes, it is, as the above error message indicates.
You can read the Twitter REST API documentation, such as the documentation on their search API.
Related
I am three days trying to solve this problem with my filter using checkbox and a ListView.
In this code I select the checkboxes the first time and they are listed correctly with the IDs of each selected category and review the IDs for another Activity called NovaActivity. OK? So far so good.
The problem is the following when I re-open the Filters Activity to make a new same unchecking checkbox with the already listed filters it keeps going to NovaAcitivty even though they are unmarked.
EX:
1st filter selects 1 and 2;
When I send it to another it goes the 1,2;
2nd filter I select 1 and uncheck checkbox 2;
When I send it to another it goes the 1,1,2;
How do I solve this?
NOTE: important the second time so said that I open the Filters activity the already selected checkboxes are already premarked because I write them to my remote MySQL database and I retrieve them.
If I was not very clear can ask questions at will, thank you any help already.
public class MainActivity extends AppCompatActivity {
Context context;
ArrayList<Category> array_list;
FavouriteCategoriesJsonParser categoryJsonParser;
String categoriesCsv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
new asyncTask_getCategories().execute();
}
public static class CategoryAdapter extends ArrayAdapter<Category> {
private final List<Category> list;
public CategoryAdapter(Context context, int resource, List<Category> list) {
super(context, resource, list);
this.list = list;
}
static class ViewHolder {
protected TextView categoryName;
protected CheckBox categoryCheckBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(getContext());
convertView = inflator.inflate(R.layout.row_category, null);
viewHolder = new ViewHolder();
viewHolder.categoryName = (TextView) convertView.findViewById(R.id.row_categoryname_textview);
viewHolder.categoryCheckBox = (CheckBox) convertView.findViewById(R.id.row_category_checkbox);
viewHolder.categoryCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
list.get(getPosition).setSelected(buttonView.isChecked());
if (buttonView.isChecked()) {
if (!FavouriteCategoriesJsonParser.selectedCategories.contains(String.valueOf(list.get(getPosition).getCateogry_id()))) {
FavouriteCategoriesJsonParser.selectedCategories.add(String.valueOf(list.get(getPosition).getCateogry_id()));
Log.i("ISIS_back"," "+"ADICONOU "+String.valueOf(list.get(getPosition).getCateogry_id()));
}
} else {
if (FavouriteCategoriesJsonParser.selectedCategories.contains(String.valueOf(list.get(getPosition).getCateogry_id()))) {
FavouriteCategoriesJsonParser.selectedCategories.remove(String.valueOf(list.get(getPosition).getCateogry_id()));
Log.i("ISIS_back"," "+"REMOVEU "+String.valueOf(list.get(getPosition).getCateogry_id()));
}
}
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.row_categoryname_textview, viewHolder.categoryName);
convertView.setTag(R.id.row_category_checkbox, viewHolder.categoryCheckBox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.categoryCheckBox.setTag(position);
viewHolder.categoryName.setText(list.get(position).getCategory_Name());
viewHolder.categoryCheckBox.setChecked(list.get(position).isSelected());
return convertView;
}
}
public static class FavouriteCategoriesJsonParser {
public static ArrayList<String> selectedCategories = new ArrayList<>();
public ArrayList<Category> getParsedCategories() {
String JsonFavouriteCategories = "";
ArrayList<Category> MyArraylist = new ArrayList<>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://pensoupediu.000webhostapp.com/api/filtro/getFavouriteCategories.php?id_usuario=1");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
JsonFavouriteCategories = EntityUtils.toString(httpResponse.getEntity());
JSONArray jsonArray = new JSONArray(JsonFavouriteCategories);
for (int i = 0; i < jsonArray.length(); i++) {
Category genres = new Category();
JSONObject MyJsonObject = jsonArray.getJSONObject(i);
genres.setCateogry_id(Integer.parseInt(MyJsonObject.getString("id")));
genres.setCategory_Name(MyJsonObject.getString("nome_cat"));
genres.setSelected(Boolean.parseBoolean(MyJsonObject.getString("selected")));
MyArraylist.add(genres);
if (MyJsonObject.getString("selected").equals("true")) {
selectedCategories.add(MyJsonObject.getString("id"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return MyArraylist;
}
}
public class asyncTask_getCategories extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(context);
#Override
protected void onPreExecute() {
dialog.setTitle("");
dialog.setMessage("Carregando...");
dialog.show();
array_list = new ArrayList<>();
categoryJsonParser = new FavouriteCategoriesJsonParser();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
array_list = categoryJsonParser.getParsedCategories();
Log.i("ISIS"," "+array_list);
return null;
}
#Override
protected void onPostExecute(Void s) {
ListView mListViewBooks = (ListView) findViewById(R.id.category_listView);
final CategoryAdapter categoryAdapter = new CategoryAdapter(context, R.layout.row_category, array_list);
mListViewBooks.setAdapter(categoryAdapter);
Button button = (Button) findViewById(R.id.selectCategoryButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
categoriesCsv = FavouriteCategoriesJsonParser.selectedCategories.toString();
categoriesCsv = categoriesCsv.substring(1, categoriesCsv.length() - 1);
if (categoriesCsv.length() > 0) {
new asyncTask_insertUpdatefavouriteCategories().execute();
} else {
Toast.makeText(context, "Por favor, selecione um filtro.", Toast.LENGTH_SHORT).show();
}
}
});
super.onPostExecute(s);
dialog.dismiss();
}
public class asyncTask_insertUpdatefavouriteCategories extends AsyncTask<Void, Void, Void> {
String response;
#Override
protected Void doInBackground(Void... params) {
response = insertUpdateCall(categoriesCsv);
return null;
}
#Override
protected void onPostExecute(Void s) {
Toast.makeText(context, categoriesCsv, Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, NovaActivity.class);
intent.putExtra("filtros", response);
startActivity(intent);
super.onPostExecute(s);
}
}
}
public static String insertUpdateCall(String categoriesCsv) {
String response = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://pensoupediu.000webhostapp.com/api/filtro/insertUpdateFavouriteCategories.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id_usuario", "1"));
nameValuePairs.add(new BasicNameValuePair("favouriteCategories", categoriesCsv));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
response = EntityUtils.toString(httpResponse.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
Use Set instead of ArrayList:
public static Set<String> selectedCategories = new HashSet<>();
This will ensure that your selectedCategories has no duplicates.
hi guys i want to sent location name and some other string values to the server...i am new in android so i dont know much about it....i pass the location and other values with url...url hits but the values are not receive by the server..help please me out...
public class SearchResult extends AppCompatActivity {
private ListView lvSearch;
private ProgressDialog dialog;
private final String URL_TO_HIT = "http://www.abcd.com/mobile_search.php";
private String location = "bathinda";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
setContentView(R.layout.activity_search_result);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Search Result");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading. Please wait...");
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvSearch = (ListView)findViewById(R.id.lvSearch);
Bundle bundle = getIntent().getExtras();
String bar = bundle.getString("bar");
String nights = bundle.getString("nights");
String nearby = bundle.getString("nearby");
String deals = bundle.getString("deals");
// To start fetching the data when app start, uncomment below line to start the async task.
new JSONTask().execute(URL_TO_HIT, location, bar, nights, nearby, deals );
}
public class JSONTask extends AsyncTask<String,String, List<SearchData> >{
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<SearchData> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("search");
List<SearchData> searchDataList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
SearchData searchData = gson.fromJson(finalObject.toString(), SearchData.class);
searchDataList.add(searchData);
}
return searchDataList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final List<SearchData> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result != null) {
SearchAdapter adapter = new SearchAdapter(getApplicationContext(), R.layout.searchresultrow, result);
lvSearch.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "Not able to fetch data from server, please check internet", Toast.LENGTH_SHORT).show();
}
}
}
public class SearchAdapter extends ArrayAdapter{
private List<SearchData> searchDataList;
private int resource;
private LayoutInflater inflater;
public SearchAdapter(Context context, int resource, List<SearchData> objects) {
super(context, resource, objects);
searchDataList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.searchimg11 = (ImageView)convertView.findViewById(R.id.searchimg1);
holder.barname1 = (TextView)convertView.findViewById(R.id.barname);
holder.address1 = (TextView)convertView.findViewById(R.id.address);
holder.offer1 = (TextView)convertView.findViewById(R.id.offer);
holder.hourtext1 = (TextView)convertView.findViewById(R.id.hourtext);
holder.coststext1 = (TextView)convertView.findViewById(R.id.coststext);
holder.textv11 = (TextView)convertView.findViewById(R.id.textv1);
holder.featuredtext1 = (TextView)convertView.findViewById(R.id.featuredtext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressBar);
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(searchDataList.get(position).getBar_image(), holder.searchimg11, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
// progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
// progressBar.setVisibility(View.GONE);
}
});
holder.barname1.setText(searchDataList.get(position).getBarname());
holder.address1.setText(searchDataList.get(position).getLocation());
holder.offer1.setText( searchDataList.get(position).getOffers());
holder.hourtext1.setText( searchDataList.get(position).getOpen_hours());
holder.coststext1.setText(searchDataList.get(position).getCost_for_two());
holder.textv11.setText(searchDataList.get(position).getFreebe());
holder.featuredtext1.setText(searchDataList.get(position).getFeaured());
return convertView;
}
class ViewHolder{
private ImageView searchimg11;
private TextView address1;
private TextView offer1;
private TextView hourtext1;
private TextView coststext1;
private TextView textv11;
private TextView barname1;
private TextView featuredtext1;
}
}
}
You are not passing any parameters to the server there . You are calling URL without any parameters
Read this solution to know how to pass parameters to HttpURLConnection using POST
How to add parameters to HttpURLConnection using POST
I did not go through your code. I suggest you to use the library to do much of the work instead of you developing on top of HTTP stack.
Use Retrofit(http://square.github.io/retrofit/) or Volley(https://developer.android.com/training/volley/index.html).
Retrofit is easy to use and manage but volley give you lot of control. Since you are new to programming on the client side, I suggest you use the Retrofit. You can't go wrong with sending JSON data, and few post using this libraries.
Every time I pull to refresh (using chrisbanes library), my ListView gets all the "new" data appended to the end of the old data, instead of replacing it. I already checked my Json parser, which returns my ArrayList, and it's definitely NOT that I'm accidentally doubling up in the list itself.
I've tried all sorts of "notifyDataSetChanged()"'s and ".invalidate()"'s and I just cannot seem to convince my ListView to fully repopulate itself. It works correctly on orientation-shift, which I realize is a clue, but I can't seem to figure out what is different in that case.
Code below, thanks for any tips!
public class VoicemailsPME extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.voicemails_pme);
listView = (PullToRefreshListView) findViewById(R.id.pulllist);
final String username = getIntent().getExtras().getString("username");
final String password = getIntent().getExtras().getString("password");
mailboxId = getIntent().getExtras().getString("mailboxId");
m_voicemails = new ArrayList<Voicemail>();
mHandlerFirst.post(new Runnable() {
#Override
public void run() {
CheckConnectionTask CCT = new CheckConnectionTask(VoicemailsPME.this);
CCT.execute(username, password);
firstTime = false;
}
});
listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> lv) {
lv.invalidate();
mHandler.post(new Runnable() {
#Override
public void run() {
CheckConnectionTask CCT = new CheckConnectionTask(VoicemailsPME.this);
CCT.execute(username, password);
}
});
}
});
this.m_adapter = new OrderAdapter(this, R.layout.voicemails_pme_row, m_voicemails);
listView.setAdapter(m_adapter);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_voicemails != null && m_voicemails.size() > 0){
for(int i=0;i<m_voicemails.size();i++)
m_adapter.add(m_voicemails.get(i));
}
}
};
private void getVoicemails(){
try{
//Log.d("Data right before Json Parse", data);
Json jsonParser = new Json(data);
m_voicemails = jsonParser.getVoicemailsPME();
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Voicemail> {
private ArrayList<Voicemail> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Voicemail> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Voicemail vm = items.get(position);
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.voicemails_pme_row, null);
}
if (vm != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView nm = (TextView) v.findViewById(R.id.length);
if (tt != null)
{
tt.setText(vm.getPhoneNumber());
if(vm.getNewStatus())
tt.setTypeface(null, Typeface.BOLD);
}
if(bt != null)
{
bt.setText(vm.getDate());
}
if(nm != null)
{
nm.setText(vm.getLength());
}
}
return v;
}
}
class CheckConnectionTask extends AsyncTask<String, Void, String> {
private VoicemailsPME activity;
private ProgressDialog dialog;
private Context context;
public CheckConnectionTask(VoicemailsPME activity)
{
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
String username, password, str;
#Override
protected void onPreExecute() {
if(firstTime)
{
this.dialog.setMessage("Loading...");
this.dialog.show();
}
}
#Override
protected String doInBackground(String...arg0)
{
username = arg0[0];
password = arg0[1];
DefaultHttpClient httpclient = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials(username, password);
httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
try{
HttpPost post = new HttpPost("https://www.my.patlive.com/api/v1.0/Mailbox/" + mailboxId + "/messages?format=json");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(post);
str = inputStreamToString(response.getEntity().getContent()).toString();
if(str.contains("\"ErrorCode\":0"))
{
//data = str;
return str;
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();}
return str;
}
#Override
protected void onPostExecute(String newData)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
data = newData;
getVoicemails();
m_adapter.notifyDataSetChanged();
listView.onRefreshComplete();
}
}
}
I think that your getVoicemail() method is the culprit.
Because of the way that the adapter works, it's using the backing array you provided originally (m_voicemails), and when you refresh it you create a new list but the original one is not cleared and then you just add on top of that.
public void run() {
//Try adding m_adapter.clear() here
if(m_voicemails != null && m_voicemails.size() > 0){
for(int i=0;i<m_voicemails.size();i++)
m_adapter.add(m_voicemails.get(i));
}
}
I've found that it's clearer to keep a list of the data separate from your adapter and then just feed that data into the adapter (using a set instead of an add).
I am building a android-based app to implement twitter search function. The button click only works for the first. If i change the search term and click the button again, it fails to refresh. Anyone can give me a hint?
`public class TwitterSActivity extends Activity implements OnClickListener{
EditText etQuery;
Button btnQuery;
class Tweet{
public String username;
public String message;
public String image_url;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etQuery = (EditText) findViewById (R.id.et);
btnQuery = (Button) findViewById (R.id.btn);
btnQuery.setOnClickListener(this);
}
#Override
public void onClick(View v){
if(v.getId() == R.id.btn){
Toast.makeText(this, "Query submitted", Toast.LENGTH_LONG).show();
Getdata getdata = new Getdata();
String returned = null;
String searchTerm = etQuery.getText().toString();
try {
returned = getdata.getInternetData(searchTerm);
} catch (Exception e) {
e.printStackTrace();
}
try{
JSONObject jo = new JSONObject(returned);
JSONArray ja = jo.getJSONArray("results");
for(int i=0; i<ja.length(); i++){
JSONObject job = ja.getJSONObject(i);
Tweet tt = new Tweet();
tt.username = job.getString("from_user");
tt.message = job.getString("text");
tt.image_url = job.getString("profile_image_url");
tweets.add(tt);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data: "+e.toString());
}
ListView lv = (ListView) findViewById(R.id.listView1);
class FancyAdapter extends ArrayAdapter<Tweet> {
public FancyAdapter() {
super(TwitterSActivity.this, android.R.layout.simple_list_item_1, tweets);
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.listitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.populatefrom(tweets.get(position));
return(convertView);
}
class ViewHolder {
public TextView username = null;
public TextView message = null;
public ImageView image = null;
ViewHolder(View listitem){
username = (TextView)listitem.findViewById(R.id.username);
message = (TextView)listitem.findViewById(R.id.message);
image = (ImageView)listitem.findViewById(R.id.avatar);
}
void populatefrom(Tweet t){
username.setText(t.username);
message.setText(t.message);
image.setImageBitmap(getBitmap(t.image_url));
}
}
}
FancyAdapter ar = new FancyAdapter();
lv.setAdapter(ar);
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch(Exception e) {return null;}
}`
Finally i figure it out, here is how I fix it:
I change ArrayList<Tweet> tweets = new ArrayList<Tweet>(); to final ArrayList<Tweet> tweets = new ArrayList<Tweet>();
and then move it under onClick() method. It works well without notifyDataSetChanged().
I have had a good look at CWAC Endless adapter and a couple of others that do the same thing, but I cannot work out how to apply them to my current method of retrieving data, which populates 2 rows and a listview. Currently the data is retrieved via httpget in an ASync background task. The url is altered slightly to get each subsequent page (page=1.html, page=2.html etc).
I would like page 2 to load and append to the end of page 1 when the end is reached - I guess it is possible using CWACs method but I cannot work out how. Below is my code, help much appreciated.
My current system works absolutely fine for displaying a single page - but I would like the endless list loading.
private class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
protected void onPreExecute() {
{progressDialog = ProgressDialog.show(TwitterPage.this,
"", "Loading. Please wait...", true);}
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences myPrefs = getPreferences(MODE_PRIVATE);
try {
String twitPlayers = getString(R.string.twit_players);
String twitClub = getString(R.string.twit_club);
String twitAndr = getString(R.string.twit_andr);
String twitMentions = getString(R.string.twit_mentions);
HttpClient hc;
HttpGet get;
HttpResponse rp;
if (myPrefs.getInt("FILTER_INT", 1) == 1){
hc = new DefaultHttpClient();
get = new
//All
HttpGet("http://search.twitter.com/search.json?q=" + twitMentions + "+OR+" + twitAndr + "+OR+from" + twitPlayers + "+OR+from" + twitClub + "&result_type=recent&rpp=15&page="+currentpage);
rp = hc.execute(get);}
else if (myPrefs.getInt("FILTER_INT", 1) == 2){
hc = new DefaultHttpClient();
get = new
........LOADS MORE IF STATEMENTS REMOVED AS NOT RELEVANT............
rp = hc.execute(get);}
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweet tweet = new Tweet();
tweet.content = session.getString("text");
tweet.author = session.getString("from_user");
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
{ progressDialog.dismiss();}
//setadapter
setListAdapter(new TweetListAdaptor(
TwitterPage.this, R.layout.list_item, tweets));
}
}
private class TweetListAdaptor extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public TweetListAdaptor(Context context,
int textViewResourceId,
ArrayList<Tweet> items) {
super(context, textViewResourceId, items);
this.tweets = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Tweet o = tweets.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
tt.setText(o.content);
bt.setText(o.author);
return v;
}
}