Twitter4j--only bringing up few tweets from user - Android - android

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();
}
}

Related

Loading listview Activity takes long and show black screen before appear

I created app that takes JSON with AsyncTask from server. When User click a button app starts new Activity and download data from server and show it as a items in ListView. The Problem is when I open new Activity it takes too long to load. When button is pressed app freeze on about one or two seconds and then show black screen for another 2/3 seconds. After that activity is displayed but it is very slow. It freeze every time user is scrolling or pressing button to display more options of custom adapter. Is there any way to make app more smooth? Json data that is downloaded is just simple JSONArray with JSONObjects that has 2 string values and one HTML format. This 3 values is display to user.
Part of Custom Adapter class
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
SuggestionList suggestionList = getItem(position);
int actualPosition = 0;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.sugestion_list, parent, false);
}
final Button suggestionsButton = (Button) convertView.findViewById(R.id.suggestionsMore);
final TextView suggestionNumber = (TextView) convertView.findViewById(R.id.sugestionNumber);
final TextView suggestionDescription = (TextView) convertView.findViewById(R.id.suggestionDescription);
final ImageView bio = convertView.findViewById(R.id.sugestionBio);
final ImageView block = convertView.findViewById(R.id.sugestionBlock);
final ImageView call = convertView.findViewById(R.id.sugestionCall);
...
final Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slideup);
final Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slidedown);
final Handler handler = new Handler();
suggestionsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (bioSuggestions.getVisibility() == View.GONE) {
bio.setVisibility(View.VISIBLE);
block.setVisibility(View.VISIBLE);
call.setVisibility(View.VISIBLE);
bioSuggestions.startAnimation(slideUp);
blockSuggestions.startAnimation(slideUp);
callSuggestions.startAnimation(slideUp);
} else if (bioSuggestions.getVisibility() == View.VISIBLE) {
bioSuggestions.startAnimation(slideDown);
blockSuggestions.startAnimation(slideDown);
callSuggestions.startAnimation(slideDown);
handler.postDelayed(new Runnable() {
#Override
public void run() {
bio.setVisibility(View.GONE);
block.setVisibility(View.GONE);
call.setVisibility(View.GONE);
}
}, 300);
}
}
});
if (actualPosition != position) {
if (bio.getVisibility() == View.VISIBLE) {
bio.setVisibility(View.GONE);
block.setVisibility(View.GONE);
call.setVisibility(View.GONE);
}
actualPosition = position;
}
JSONObject jsonValSuggestions = new getSugestions().sugestionsDetails(position, "suggestions");
try {
final String name = jsonValSuggestions.getString("client_name");
final String num = jsonValSuggestions.getString("client_number");
final String description = jsonValSuggestions.getString("client_description");
bio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionsDetails = new Intent(view.getContext(), SuggestionsDetails.class);
suggestionsDetails.putExtra("client_number", num);
suggestionsDetails.putExtra("client_name", name);
suggestionsDetails.putExtra("client_description", description);
activity.startActivityForResult(suggestionsDetails, position);
}
});
block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionBlock = new Intent(view.getContext(), BlockSuggestionsActivity.class);
activity.startActivity(suggestionBlock);
}
});
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionCall = new Intent(view.getContext(), CallSuggestionActivity.class);
suggestionCall.putExtra("client_number", num);
suggestionCall.putExtra("client_name", name);
activity.startActivity(suggestionCall);
}
});
} catch (Exception e) {
e.printStackTrace();
}
try {
if (suggestionList.suggestionName.equals("null") || suggestionList.suggestionName.equals("")) {
suggestionNumber.setText(suggestionList.suggestionNumber);
} else {
suggestionNumber.setText(suggestionList.suggestionName);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
suggestionDescription.setText(Html.fromHtml(suggestionList.suggestionDescription, Html.FROM_HTML_MODE_LEGACY));
} else {
suggestionDescription.setText(Html.fromHtml(suggestionList.suggestionDescription));
}
} catch (Exception e) {
Log.i("exception", e.getMessage());
}
return convertView;
}
Part of AsyncTask class
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String clientUrl = params[0];
String result;
String inputLine;
JSONObject obj;
String data;
String message;
try {
URL myUrl = new URL(clientUrl);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
result = null;
}
return result;
}
public String[] getSuggestionsList() {
String[] suggestionList = new String[5];
String result;
String status;
JSONObject listObj;
String suggestionsData;
JSONObject suggestionsDataObj;
JSONArray suggestionsDataArr;
String ClientsSugestionsUrl = "https://example.com/token=" + authToken;
getApiClientSugestions getSugestionsFromApi = new getApiClientSugestions();
try {
result = getSugestionsFromApi.execute(ClientsSugestionsUrl).get();
try {
listObj = new JSONObject(result);
status = listObj.getString("result");
suggestionsData = listObj.getString("suggestions");
suggestionsDataArr = new JSONArray(suggestionsData);
} catch (Exception e) {
e.printStackTrace();
suggestionsDataArr = null;
status = null;
}
suggestionList[3] = status;
suggestionList[4] = suggestionsDataArr.toString();
} catch (Exception e) {
e.printStackTrace();
}
return suggestionList;
}
Activity
public class CallsSuggestionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calls_suggestions);
Slidr.attach(this);
getSupportActionBar().setTitle("Skontaktuj się");
}
#Override
protected void onResume() {
super.onResume();
CallsSuggestionList();
}
public void CallsSuggestionList() {
final ListView suggestionList = findViewById(R.id.sugestionList);
final ArrayList<SuggestionList> suggestionArray = new ArrayList<SuggestionList>();
SuggestionListAdapter suggestionListAdapter = new SuggestionListAdapter(getContext(), suggestionArray, this);
String[] suggestionListArray = new getSugestions().getSuggestionsList();
String suggStat = suggestionListArray[3];
String arrayList = suggestionListArray[4];
String clientName;
String clientNumber;
String clientDescription;
try {
JSONArray jsonArray = new JSONArray(arrayList);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
clientName = explrObject.getString("client_name");
clientNumber = explrObject.getString("client_number");
clientDescription = explrObject.getString("client_description");
if (suggStat.equals("true")) {
SuggestionList suggestionList1 = new SuggestionList(clientName, clientDescription, clientNumber);
suggestionListAdapter.addAll(suggestionList1);
suggestionListAdapter.notifyDataSetChanged();
suggestionList.setAdapter(suggestionListAdapter);
}
}
} catch (Exception e) {
Log.i("exception", e.getMessage());
e.printStackTrace();
clientName = null;
clientDescription = null;
clientNumber = null;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SuggestionList
public class SuggestionList {
public String suggestionNumber;
public String suggestionDescription;
public String suggestionCallType;
public String suggestionName;
public SuggestionList(
// String suggestionCallType,
String suggestionName, String suggestionDescription, String suggestionNumber) {
this.suggestionNumber = suggestionNumber;
// this.suggestionCallType = suggestionCallType;
this.suggestionName = suggestionName;
this.suggestionDescription = suggestionDescription;
}
}
Adapter are custom with custom view displayed to user. I use similar custom adapter to show content from sqlite that is on phone and there app isn't so slow. But when I open this activity it slow down dramatically. Also I noticed when I press back button it take very long to back to previous screen.
The problem is in the getSuggestionsList function. in this function, you are calling getSugestionsFromApi.execute(ClientsSugestionsUrl).get(); which make your code sync again. I mean your code is waiting this code to be executed.
One way (not right way, but easy way): you can call new getSugestions().getSuggestionsList(); in a new thread.
Second way, call getSugestionsFromApi.execute(ClientsSugestionsUrl) without get() function. But to get result of the code, you need to give an interface.
To get right usage: https://xelsoft.wordpress.com/2014/11/28/asynctask-implementation-using-callback-interface/

onclick button not getting edit text string for api

I'm developing a Calorie app using an API Database. When the user clicks the search button it gets the string and then searches the database. For some reason the user edit text "string" is not being retrieved therefore not being able to search the api database. When I did the debug I noticed that the string is "" meaning empty.
Thanks again so much, New to api and android studio.
public class AddEntry extends Fragment implements View.OnClickListener {
EditText FoodET,CalorieET;
ImageButton Savebtn, Cancelbtn;
Button searchbutton;
String foodET,calorieET;
//database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry, container,
false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
foodET = ((EditText)
view.findViewById(R.id.foodEditText)).getText().toString();
foodET.isEmpty();
FoodET.setText("");
CalorieET.setText("");
calorieET = ((EditText)
view.findViewById(R.id.caloriesEditText)).getText().toString();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
FoodSearch search = new FoodSearch(foodET, CalorieET );
search.execute();
break;
case R.id.SaveBtn:
if (FoodET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("") ||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
AlertDialog NotFound = new
AlertDialog.Builder(getContext()).create();
NotFound.setTitle("Error");
NotFound.setMessage("Food not found :(");
NotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
else
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
private class FoodSearch extends AsyncTask<Void, Void, String> {
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food +
"&max=1&offset=0&sort=r&api_
key=xMJV33vSmKsquFqcBwZ23oJ7DlL2abmfsrDUUx1l");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
ndbno=" + ndbno +
"&type=b&format=JSON&api_
key=xMJV33vSmKsquFqcBwZ23oJ7DlL2abmfsrDUUx1l");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
}
}
}
Try this
case R.id.SearchButton:
String foodEtString=FoodET.getText().toString();
FoodSearch search = new FoodSearch(foodEtString, CalorieET );
search.execute();
break;
And Add this in onCreate as well
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
Use these values instead when you go to execute the AsyncTask
String FoodName = FoodET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
The following values are always empty when the view is created (and are not necessary in your code).
foodET = ((EditText) view.findViewById(R.id.foodEditText)).getText().toString();
calorieET = ((EditText) view.findViewById(R.id.caloriesEditText)).getText().toString();
So that explains why this didn't work
FoodSearch search = new FoodSearch(foodET, CalorieET );
You should always try to call getText in response to a user event in order to get the most recent value(s) of the input fields
I'd also suggest that you learn how to properly parse JSON data (don't use indexOf), or go so far as look into the Retrofit library

Parsing JSON data and storing into a listview

I'm currently developing a small android weather app. That passes through 3 strings to display three weather elements from the open source weatherAPI. I'm trying to display this in a listview. I got it working when passing in 1 string. But I'm having trouble passing in multiple strings. Any advice would be appreciated
ArrayList<Weather> weatherData = new ArrayList<Weather>();
private ListView listView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1 = (ListView) findViewById(R.id.listView1);
String[] city = {
new String("dublin,ire"),
new String("London,uk")
};
for (int i = 0; i < city.length; ++i) {
listView1.add(city[i]);
}
//String city2 = "Dublin,ire";
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
Log.d("MR.bool", "Button1 was clicked ");
startActivity(new Intent(MainActivity.this, WebViewActivity.class));
}
});
cityText = (TextView) findViewById(R.id.cityText);
condDescr = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.temp);
hum = (TextView) findViewById(R.id.hum);
press = (TextView) findViewById(R.id.press);
windSpeed = (TextView) findViewById(R.id.windSpeed);
windDeg = (TextView) findViewById(R.id.windDeg);
imgView = (ImageView) findViewById(R.id.condIcon);
imgView2 = (ImageView) findViewById(R.id.imageView1);
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[]{city});
if (city.contains("uk")) {
imgView2.setImageResource(R.drawable.uk);
} else if (city.contains("ire")) {
imgView2.setImageResource(R.drawable.ireland);
} else if (city.contains("de")) {
imgView2.setImageResource(R.drawable.germany);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params) {
Weather weather = new Weather();
String data = ((new WeatherHttpClient()).getWeatherData(params[0]));
try {
weather = JSONWeatherParser.getWeather(data);
// Let's retrieve the icon
weather.iconData = ((new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
imgView.setImageBitmap(img);
}
else if(weatherData.size() > 0)
{
ArrayAdapter<Weather> adapter = new ArrayAdapter<Weather>(MainActivity.this,
android.R.layout.activity_list_item, weatherData);
listView1.setAdapter(adapter);
// here you can also define your custom adapter and set it to listView
//according to your own defined layout as items
}
cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
condDescr.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");
hum.setText("" + weather.currentCondition.getHumidity() + "%");
press.setText("" + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText("" + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "�");
}
}
}
You can use Gson to parse the json.
I'm assuming that you are receiving a jsonArray. So, you can do something like this:
ArrayList<Weather> weatherArrayList = new ArrayList<Weather>();
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray jArray = jsonParser.parse(responseStr).getAsJsonArray();
for (JsonElement obj : jArray) {
Weather weatherModel = gson.fromJson(response, Weather.class);
weatherArrayList.add(weatherModel);
}
The code above parse the data in your json and adds them into your "weatherArrayList" this ArrayList you should place it in your adapter and just set in your listview.
This might be your custom adapter
public class WeatherAdapter extends ArrayAdapter<Weather> {
public WeatherAdapter(Context context) {
super(context, 0);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
// here you should set up the custom view. That is the view of each Item of your ListView
}
}
I hope I helped you :)

Twitter fabric get tweets with hashtag

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

can't show the thumbnail from youtube?

this app should show thumbnail , title, and the duration of each video in the playlist selected , but thumbnail remain white
the application works but It don't show the thumbnail of the video in the playlist
how can I do ? you have any solution?
THIS IS MY CODE
public class MainActivity extends Activity {
ImageView mainThumb;
TextView mainTitle;
TextView mainTime;
LinearLayout videos;
ArrayList<String> links;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.videos);
new ParseVideoDataTask().execute();
mainThumb = (ImageView) findViewById(R.id.mainThumb);
mainTitle = (TextView) findViewById(R.id.mainTitle);
mainTime = (TextView) findViewById(R.id.mainTime);
videos = (LinearLayout) findViewById(R.id.videos);
}
private class ParseVideoDataTask extends AsyncTask<String, String, String> {
int count = 0;
#Override
protected String doInBackground(String... params) {
URL jsonURL;
URLConnection jc;
links = new ArrayList<String>();
try {
jsonURL = new URL("http://gdata.youtube.com/feeds/api/playlists/" +
"PL-7t9DoIELCRF7F7bZvvBwO1yvHRFsJiu" +
"?v=2&alt=jsonc");
//PL_VGbflD64WSR1MBcpWlNwsY0lRNVuJ3r
jc = jsonURL.openConnection();
InputStream is = jc.getInputStream();
String jsonTxt = IOUtils.toString(is);
JSONObject jj = new JSONObject(jsonTxt);
JSONObject jdata = jj.getJSONObject("data");
JSONArray aitems = jdata.getJSONArray("items");
for (int i=0;i<aitems.length();i++) {
JSONObject item = aitems.getJSONObject(i);
JSONObject video = item.getJSONObject("video");
String title = video.getString("title");
JSONObject player = video.getJSONObject("player");
String link = player.getString("default");
String length = video.getString("duration");
JSONObject thumbnail = video.getJSONObject("thumbnail");
String thumbnailUrl = thumbnail.getString("hqDefault");
String[] deets = new String[4];
deets[0] = title;
deets[1] = thumbnailUrl;
deets[2] = length;
links.add(link);
publishProgress(deets);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(final String... deets) {
count++;
if (count == 1) {
MainActivity.setImageFromUrl(deets[1], mainThumb, MainActivity.this);
mainTitle.setText(deets[0]);
mainTime.setText(formatLength(deets[2]));
mainThumb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(1)));
startActivity(i);
}
});
} else {
LayoutInflater layoutInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View video = layoutInflater.inflate(R.layout.video, null);
ImageView thumb = (ImageView) video.findViewById(R.id.thumb);
TextView title = (TextView) video.findViewById(R.id.title);
TextView time = (TextView) video.findViewById(R.id.time);
MainActivity.setImageFromUrl(deets[1], thumb, MainActivity.this);
title.setText(deets[0]);
time.setText(formatLength(deets[2]));
video.setPadding(20, 20, 20, 20);
videos.addView(video);
video.setId(count-1);
video.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(v.getId())));
startActivity(i);
}
});
}
}
}
private CharSequence formatLength(String secs) {
int secsIn = Integer.parseInt(secs);
int hours = secsIn / 3600,
remainder = secsIn % 3600,
minutes = remainder / 60,
seconds = remainder % 60;
return ((minutes < 10 ? "0" : "") + minutes
+ ":" + (seconds< 10 ? "0" : "") + seconds );
}
public static void setImageFromUrl(String string, ImageView mainThumb2,
MainActivity mainActivity) {
}
#Override
public void onDestroy() {
super.onDestroy();
for (int i=0;i<videos.getChildCount();i++) {
View v = videos.getChildAt(i);
if (v instanceof ImageView) {
ImageView iv = (ImageView) v;
((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
}
}
}
}
Use Picasso to set the image url like so:
Picasso.withContext(this).load(thumbnailUrl).into(myImageView);
To do this you'll need to return the JSON object in the doInBackground method, or use something like Retrofit (as I mentioned in the comment above) to get a nice POJO and return that. Then in the postExecute you can use the thumbnail url in the JSON (or POJO) and set it using Picasso above. Picasso will take care of downloading and caching the image for you and loading it into the image view.

Categories

Resources