Here's my code under the name of my class VideoList.java. I did change
the version of the APIs - even the Android version - but still have this
problem:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.youtubekids.cartoons.pojo.VideoPojo;
public class VideoList extends ActionBarActivity {
RequestQueue mRequestQueue;
ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
ImageLoader imageLoader;
ListView lvvideos;
String CHANNEL_ID;
String YOUTUBE_URL = "", YOUTUBEAPIKEY = DataManager.YOUTUBE_API_KEY;
String NEXT_PAGE_TOKEN = "";
ProgressDialog progress;
int total = 0;
ArrayList<VideoPojo> videolist = new ArrayList<VideoPojo>();
Custom_Adapter adapter;
boolean loadmore = false;
TextView txtfooter;
private AdView adView;
private static final String AD_UNIT_ID = DataManager.ADMOB_BANNER;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_list);
lvvideos = (ListView) findViewById(R.id.lvvideos);
CHANNEL_ID = DataManager.selectedchannelid;
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
LinearLayout ll = (LinearLayout) findViewById(R.id.ad);
ll.addView(adView);
txtfooter = (TextView) findViewById(R.id.txtfooter);
txtfooter.setVisibility(View.GONE);
new loadvideos().execute();
lvvideos.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (lvvideos.getLastVisiblePosition() >= lvvideos.getCount() - 1) {
if (loadmore) {
new loadvideos().execute();
txtfooter.setText(" Loading more videos...");
txtfooter.setVisibility(View.VISIBLE);
} else {
txtfooter.setText("No More Videos");
txtfooter.setVisibility(View.GONE);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
lvvideos.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
DataManager.selectedvideoid = videolist.get(position).getVideoid();
Intent i = new Intent(VideoList.this, YouTubePlayerActivity.class);
startActivity(i);
overridePendingTransition(0, 0);
}
});
getSupportActionBar().setTitle(DataManager.channelname);
// Begin loading your interstitial.
AdRequest adRequest1 = new AdRequest.Builder().build();
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(DataManager.ADMOB_INTERSTIAL);
interstitial.loadAd(adRequest1);
AdListener adListener = new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
}
#Override
public void onAdClosed() {
super.onAdClosed();
}
};
interstitial.setAdListener(adListener);
}
public void nointernet()
{
new AlertDialog.Builder(this)
.setTitle("Connection Error")
.setMessage("Try Again")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
new loadvideos().execute();
}
}).create().show();
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
public void onBackPressed() {
Intent i = new Intent(VideoList.this, MainActivity.class);
finish();
startActivity(i);
overridePendingTransition(0,0);
}
private class loadvideos extends AsyncTask<Void, Void, Void> {
boolean isconnect = false;
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request.
if (!loadmore)
{
progress = GoogleProgress.Progressshow(VideoList.this);
progress.show();
}
}
protected Void doInBackground(Void... unused) {
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
if (!loadmore) {
YOUTUBE_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId="
+ CHANNEL_ID
+ "&maxResults="
+ DataManager.maxResults + "&key=" + YOUTUBEAPIKEY+"&order=date";
} else {
YOUTUBE_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&pageToken="
+ NEXT_PAGE_TOKEN
+ "&channelId="
+ CHANNEL_ID
+ "&maxResults="
+ DataManager.maxResults
+ "&key="
+ YOUTUBEAPIKEY+"&order=date";
}
HttpUriRequest request = new HttpGet(YOUTUBE_URL);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
System.out.println("url---" + str);
JSONObject json = new JSONObject(str);
JSONArray items = json.getJSONArray("items");
total = json.getJSONObject("pageInfo").getInt("totalResults");
if (total > 20) {
loadmore = true;
NEXT_PAGE_TOKEN = json.getString("nextPageToken");
}
for (int i = 0; i < items.length(); i++) {
VideoPojo video = new VideoPojo();
JSONObject youtubeObject = items.getJSONObject(i)
.getJSONObject("snippet");
video.setVideoid(items.getJSONObject(i).getJSONObject("id")
.getString("videoId"));
video.setTitle(youtubeObject.getString("title"));
video.setThumbnail(youtubeObject
.getJSONObject("thumbnails").getJSONObject("high")
.getString("url"));
videolist.add(video);
}
isconnect = true;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
isconnect = false;
System.out.println("1exception---" + e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
isconnect = false;
System.out.println("2exception---" + e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("3exception---" + e.getMessage());
e.printStackTrace();
}
return (null);
}
protected void onPostExecute(Void unused) {
// Closing progress dialog.
progress.dismiss();
if (isconnect) {
if (videolist.size() > 0) {
displayInterstitial();
adapter = new Custom_Adapter(getApplicationContext());
lvvideos.setAdapter(adapter);
if (loadmore)
lvvideos.setSelection(((videolist.size() - DataManager.maxResults)-1));
else
lvvideos.setSelection(0);
if (total > videolist.size()) {
loadmore = true;
}else
{
loadmore = false;
}
}
} else {
nointernet();
}
}
}
public class Custom_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
public Custom_Adapter(Context c) {
mInflater = LayoutInflater.from(c);
imageLoader = getImageLoader(c);
}
#Override
public int getCount() {
return videolist.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_video_list, null);
holder = new ViewHolder();
holder.txttitle = (TextView) convertView
.findViewById(R.id.txttitle);
holder.img = (FeedImageView) convertView.findViewById(R.id.img);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txttitle.setText("" + videolist.get(position).getTitle());
holder.img.setImageUrl(videolist.get(position).getThumbnail(),
imageLoader);
return convertView;
}
class ViewHolder {
TextView txttitle;
FeedImageView img;
}
}
public RequestQueue getRequestQueue(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
public ImageLoader getImageLoader(Context context) {
getRequestQueue(context);
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
}
So this is my code.
And when I try to build my apk or debug the project I see the following error:
build failed 1m 1s 703ms Run build 59s 306ms Load build 4s 974ms Run
init scripts 4s 952ms Apply script sync.local.repo293.gradle 4s 951ms
Evaluate settings 6ms Configure build 13s 725ms Calculate task
graph 25s 469ms Run tasks 15s 117ms null
/Users/ismailtaibi/Downloads/fortinvideoappyt-3.1/codecanyon-11481105-fortin-video-channel-app-youtube-api-v3/FortinYoutubeChannelV3AndroidSource app/src/main/java com/youtubekids/cartoons/VideoList.java error:
package org.apache.http does not exist error: package
org.apache.http.client.methods does not exist error: package
org.apache.http.impl.client does not exist error: cannot find symbol
class DefaultHttpClient error: cannot find symbol class HttpGet
You need to add HttpClient as project's dependency. Here you will have details on Grade/Maven dependency that you will have to add to your .build or .pom file
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5
Related
I am trying to use if else in a spinner layout in android. But the if condition is never accepted with a given condition.
Id of spinner is stateView.
stateView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State = String.valueOf(stateView.getSelectedItem());
try {
if(obj.getString("state").equals(State)){
Log.d("error",State);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The same code works everywhere else in the block.
I assume the problem is in
if(obj.getString("state").equals(State))
If it is used if(true) the block works correctly, that means code is reaching there but there is a problem in the condition applied int the if statement.
even the below code is not working
if(obj.getString("state").equals("Delhi"))
this code is working outside the listener
private void stateData(final String stateName, final String cityName) {
final RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, arrayResponse -> {
try {
for (int i = 0; i < arrayResponse.length(); i++) {
JSONObject obj = arrayResponse.getJSONObject(i);
if (obj.getString("state").equals(stateName)){
Log.d("error","working");
}
The whole code for reference
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.VoiceInteractor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView stateActiveCases, stateConfirmed, stateDeceased, stateRecovered, cChanges, rChanges, dChanges;
String State;
Spinner stateView;
FusedLocationProviderClient fusedLocationProviderClient;
RecyclerView recyclerView;
RecyclerView.Adapter<DistrictAdapter.ViewHolder> mAdapter;
RecyclerView.LayoutManager layoutManager;
List<Districts> districtsList;
ArrayList<String> States;
#SuppressLint("SourceLockedOrientationActivity")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
districtsList = new ArrayList<>();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
final TextView Total = findViewById(R.id.textView4);
final TextView Recovered = findViewById(R.id.textView5);
final TextView Death = findViewById(R.id.textView6);
final TextView TodayCases = findViewById(R.id.textView7);
final TextView TodayDeath = findViewById(R.id.textView8);
final TextView ActiveCases = findViewById(R.id.textView10);
stateActiveCases = findViewById(R.id.textView29);
stateView = findViewById(R.id.spinner);
stateConfirmed = findViewById(R.id.textView26);
stateRecovered = findViewById(R.id.textView27);
stateDeceased = findViewById(R.id.textView28);
cChanges = findViewById(R.id.textView14);
rChanges = findViewById(R.id.textView15);
dChanges = findViewById(R.id.textView16);
States = new ArrayList<>();
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://coronavirus-19-api.herokuapp.com/countries/india", null, objectResponse -> {
try {
int cases = objectResponse.getInt("cases");
int recovered = objectResponse.getInt("recovered");
int deaths = objectResponse.getInt("deaths");
int todayCases = objectResponse.getInt("todayCases");
int todayDeaths = objectResponse.getInt("todayDeaths");
int activeCases = objectResponse.getInt("active");
Total.setText(String.valueOf(cases));
Death.setText(String.valueOf(deaths));
Recovered.setText(String.valueOf(recovered));
String tc = ("+" + todayCases);
String td = ("+" + todayDeaths);
TodayCases.setText(tc);
TodayDeath.setText(td);
ActiveCases.setText(String.valueOf(activeCases));
} catch (JSONException ex) {
ex.printStackTrace();
}
}, error -> Log.d("error", "something fishy " + error));
requestQueue.add(jsonObjectRequest);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2199);
} else {
getLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 2199) {
getLocation();
}
}
private void getLocation() {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(task -> {
Location location = task.getResult();
if (location != null) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1
);
stateData(addresses.get(0).getAdminArea(), addresses.get(0).getLocality());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void stateData(final String stateName, final String cityName) {
final RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "https://api.covidindiatracker.com/state_data.json", null, arrayResponse -> {
try {
for (int i = 0; i < arrayResponse.length(); i++) {
JSONObject obj = arrayResponse.getJSONObject(i);
if (obj.getString("state").equals(stateName)) {
stateActiveCases.setText(String.valueOf(obj.getInt("active")));
stateConfirmed.setText(String.valueOf(obj.getInt("confirmed")));
stateRecovered.setText(String.valueOf(obj.getInt("recovered")));
stateDeceased.setText((String.valueOf(obj.getInt("deaths"))));
String stateCChanges, stateRChanges, stateDChanges;
stateCChanges = "+" + obj.getInt("cChanges");
stateRChanges = "+" + obj.getInt("rChanges");
stateDChanges = "+" + obj.getInt("dChanges");
cChanges.setText(stateCChanges);
rChanges.setText(stateRChanges);
dChanges.setText(stateDChanges);
JSONArray array = obj.getJSONArray("districtData");
for (int j = 0; j < array.length(); j++) {
Districts districts = new Districts();
JSONObject obj1 = array.getJSONObject(j);
if (obj1.getString("name").equals(cityName)) {
districts.setName(obj1.getString("name"));
districts.setConfirmed((obj1.getInt("confirmed")));
districtsList.add(districts);
}
}
for (int k = 0; k < array.length(); k++) {
Districts districts = new Districts();
JSONObject obj1 = array.getJSONObject(k);
if (obj1.getString("name").equals(cityName)) {
continue;
}
districts.setName(obj1.getString("name"));
districts.setConfirmed(obj1.getInt("confirmed"));
districtsList.add(districts);
}
}
String state=obj.getString("state");
States.add(state);
stateView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State = String.valueOf(stateView.getSelectedItem());
((TextView )parent.getChildAt(0)).setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.colorAccent));
((TextView)parent.getChildAt(0)).setTextSize(16);
try {
if(obj.getString("state").equals(State)){
Log.d("error",State);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, States);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stateView.setAdapter(arrayAdapter);
int spinner = arrayAdapter.getPosition(stateName);
stateView.setSelection(spinner);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter = new DistrictAdapter(districtsList);
recyclerView.setAdapter(mAdapter);
}, error -> Log.d("error", "something fishy " + error));
requestQueue.add(jsonArrayRequest);
}
}
I want to move the if statement inside the listener such that when I select a state the data for that state is displayed. right now I am getting state data from the parameter which fetches data from GPS location.
Check the whole project on
Github
Any other suggestions are welcome.
Thanks in advance.
I am working on a news app and I want to update the ListView every time by swiping down in the MainActivity
This is the code of my MainActivity below:
package com.infinitystone.mani.news;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<News>> {
public static final String LOG_TAG = MainActivity.class.getName();
private static final int NEWS_LOADER_ID = 1;
private TextView mEmptyView;
private NewsAdapter mAdapter;
private static final String GUARDIAN_REQUEST_URL = "http://content.guardianapis.com/search?order-by=newest&show-fields=thumbnail&page-size=20&api-key=2f3badbb-4a58-44b8-9800-9ee2a0f445f9";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newsList = (ListView) findViewById(R.id.list);
mEmptyView = (TextView) findViewById(R.id.empty_view);
newsList.setEmptyView(mEmptyView);
mAdapter = new NewsAdapter(this, new ArrayList<News>());
newsList.setAdapter(mAdapter);
newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News currentNews = mAdapter.getItem(position);
Uri uri = Uri.parse(currentNews.getUrl());
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
builder.setSecondaryToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimaryDark));
builder.setShowTitle(true);
final Bitmap backButton = BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back_white_24dp);
builder.setCloseButtonIcon(backButton);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(MainActivity.this, uri);
}
});
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
}
else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyView.setText(R.string.no_internet);
}
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
// Create a new loader for the given URL
return new NewsLoader(this, GUARDIAN_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyView.setText(R.string.no_news);
mAdapter.clear();
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader<List<News>> loader) {
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
}
I have already added the android.support.v4.widget.SwipeRefreshLayout in my activity_main.xml file
How can I implement the SwipeRefreshLayout in java code ?
Code for fetching the news data:
package com.infinitystone.mani.news;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import static com.infinitystone.mani.news.MainActivity.LOG_TAG;
public class QueryUtils {
private QueryUtils() {
}
public static List<News> fetchNewsData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<News> news = extractFeaturesFromJson(jsonResponse);
return news;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<News> extractFeaturesFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject rootObject = new JSONObject(newsJSON);
JSONObject responseObject = rootObject.getJSONObject("response");
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject currentNews = resultsArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String titleUrl = currentNews.getString("webUrl");
String date = currentNews.getString("webPublicationDate");
JSONObject fields = currentNews.getJSONObject("fields");
String thumbnail = fields.getString("thumbnail");
News news1 = new News(title, thumbnail, date, titleUrl);
news.add(news1);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
return news;
}
}
Get a reference to your swipe to refresh layout.
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
swipeRefreshLayout.setOnRefreshListener(this);
// ... your other codes...
}
Now, make your activity implement the listener.
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<News>>, SwipeRefreshLayout.OnRefreshListener {
// ...
}
Finally implement those methods
#Override
public void onRefresh(){
swipeRefreshLayout.setRefreshing(true);
newsList = fetchNewsData(GUARDIAN_REQUEST_URL);
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
EDIT:
Here is the complete code for MainActivity. Please use this and let me know if this works.
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<News>>, SwipeRefreshLayout.OnRefreshListener {
public static final String LOG_TAG = MainActivity.class.getName();
private static final int NEWS_LOADER_ID = 1;
private TextView mEmptyView;
private NewsAdapter mAdapter;
private static final String GUARDIAN_REQUEST_URL = "http://content.guardianapis.com/search?order-by=newest&show-fields=thumbnail&page-size=20&api-key=2f3badbb-4a58-44b8-9800-9ee2a0f445f9";
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newsList = (ListView) findViewById(R.id.list);
mEmptyView = (TextView) findViewById(R.id.empty_view);
newsList.setEmptyView(mEmptyView);
mAdapter = new NewsAdapter(this, new ArrayList<News>());
newsList.setAdapter(mAdapter);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
swipeRefreshLayout.setOnRefreshListener(this);
newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News currentNews = mAdapter.getItem(position);
Uri uri = Uri.parse(currentNews.getUrl());
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
builder.setSecondaryToolbarColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimaryDark));
builder.setShowTitle(true);
final Bitmap backButton = BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back_white_24dp);
builder.setCloseButtonIcon(backButton);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(MainActivity.this, uri);
}
});
updateNewsList();
}
private void updateNewsList(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
}
else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyView.setText(R.string.no_internet);
}
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
// Create a new loader for the given URL
return new NewsLoader(this, GUARDIAN_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyView.setText(R.string.no_news);
mAdapter.clear();
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader<List<News>> loader) {
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
updateNewsList();
swipeRefreshLayout.setRefreshing(false);
}
}
Try this Respond to the Refresh Gesture, it should help.
as per my above comment use SwipeRefreshLayout
The SwipeRefreshLayout should be used whenever the user can refresh the contents of a view via a vertical swipe gesture. The activity that instantiates this view should add an OnRefreshListener to be notified whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout will notify the listener each and every time the gesture is completed again;
than set setOnRefreshListener to your SwipeRefreshLayout
void setOnRefreshListener (SwipeRefreshLayout.OnRefreshListener listener)
Set the listener to be notified when a refresh is triggered via the swipe gesture.
sample code
SwipeRefreshLayout mSwipeRefreshView;
mSwipeRefreshView = (SwipeRefreshLayout) findViewById(R.id.homeScreenSwipeRefreshView);
mSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// make your api request here
}
});
when your api request complted than use setRefreshing(false)
setRefreshing(boolean refreshing)
Notify the widget that refresh state has changed.
mSwipeRefreshView.setRefreshing(false);
I tried to implement for adding more items to my adapter but its refreshing every time instead of adding new items to bottom of the list.I searched through the internet but i didn't get the solution Here is my code:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private DataListAdapter dataListAdapter;
Activity _activity;
ArrayList<DataObject> dataArrayList;
private ListView lv;
private String jsonResult;
boolean loadingMore = false;
private DataObject dataObject;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
lv = (ListView) findViewById(R.id.listView1);
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
this.lv.addFooterView(footerView);
if (isOnline(_activity)) {
new LoadJsonData().execute();
scrollNotifyChange();
}
}
private void scrollNotifyChange() {
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already? Load more!
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
// //start a new thread for loading the items in the list
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
}
private Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
//Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
jsonResult = doInBackground();
runOnUiThread(returnRes);
}
};
private Runnable returnRes = new Runnable() {
#Override
public void run() {
onPostExecute(jsonResult);
loadingMore = false;
}
};
public String doInBackground() {
String jsonResult = "";
// jsonResult=get("https://datatables.net/examples/server_side/scripts/server_processing.php");
// return jsonResult;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
public void onPostExecute(String result) {
try {
// progress.dismiss();
dataArrayList = new ArrayList<DataObject>();
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
dataListAdapter = new DataListAdapter(dataArrayList);
dataListAdapter.add(dataObject);
// lv.setAdapter(dataListAdapter);
// dataListAdapter.add(dataObject);
dataListAdapter.notifyDataSetChanged();
lv.setAdapter(dataListAdapter);
lv.smoothScrollToPosition(dataListAdapter.getCount());
} catch (JSONException e) {
e.printStackTrace();
}
}
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class LoadJsonData extends AsyncTask<Void, Void, String> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(_activity, "Progress",
"Please wait", true);
}
#Override
protected String doInBackground(Void... params) {
String jsonResult = "";
// jsonResult=get("https://datatables.net/examples/server_side/scripts/server_processing.php");
// return jsonResult;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
progress.dismiss();
if(loadingMore)
{
// listViwe.removeFooterView(loadingFooter);
loadingMore = false;
}
dataArrayList = new ArrayList<DataObject>();
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
DataObject dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
dataListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
if(loadingMore)
{
// listViwe.removeFooterView(loadingFooter);
loadingMore = false;
}
}
}
}
public class DataListAdapter extends BaseAdapter {
ArrayList<DataObject> dataListObject = new ArrayList<DataObject>();
public DataListAdapter(ArrayList<DataObject> dataListObject) {
this.dataListObject = dataListObject;
}
#Override
public int getCount() {
return dataListObject.size();
}
#Override
public Object getItem(int position) {
return dataListObject.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void add(DataObject dataObject){
// Log.v("AddView", country.getCode());
this.dataListObject.add(dataObject);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(_activity);
convertView = inflater.inflate(R.layout.single_row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.type = (TextView) convertView.findViewById(R.id.type);
holder.profession = (TextView) convertView.findViewById(R.id.profession);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.currency = (TextView) convertView.findViewById(R.id.currecy);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final DataObject current = dataListObject.get(position);
holder.name.setText("Name--" + current.getName());
holder.type.setText("Type--" + current.getType());
holder.profession.setText("Professoion--" + current.getProfession());
holder.country.setText("Country--" + current.getCountry());
holder.currency.setText("Currency--" + current.getCurrency());
return convertView;
}
}
static class ViewHolder {
TextView name;
TextView type;
TextView profession;
TextView country;
TextView currency;
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
return result;
}
}
you need to create an adapter inside onCreate method
like this:
ArrayList<DataObject> list;
onCreate() {
list=new ArrayList();
ListAdapter dataListAdapter =new ListAdapter(list) // creating an adapter with empty list of data
listView.setAdpater(adpater);
}
then, in onPostExceute() method :
add data to the ArrayList and notifythe adapter
like this:
onPostExecute(){
....
.....
list.add(dataObject); //here you can add 'n' number of object to the list
dataListAdapter.notifyDataSetChanged(); // notify the adapter to update the listview
.....
}
EDIT : I updated this answer as per #user3422948 request
DataListAdapter dataListAdapter;
ArrayList<DataObject> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
//edit: declare your arraylist and adapter here
dataArrayList = new ArrayList<DataObject>();
dataListAdapter = new DataListAdapter(dataArrayList);
lv = (ListView) findViewById(R.id.listView1);
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
this.lv.addFooterView(footerView);
if (isOnline(_activity)) {
new LoadJsonData().execute();
scrollNotifyChange();
}
}
......
.......
public void onPostExecute(String result) {
try {
// progress.dismiss();
//dataArrayList = new ArrayList<DataObject>(); //edit
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
//edit: your creating new adapter for every execution
//dataListAdapter = new DataListAdapter(dataArrayList);
//dataListAdapter.add(dataObject);
// lv.setAdapter(dataListAdapter);
// dataListAdapter.add(dataObject);
dataListAdapter.notifyDataSetChanged();
//lv.setAdapter(dataListAdapter);
lv.smoothScrollToPosition(dataListAdapter.getCount());
} catch (JSONException e) {
e.printStackTrace();
}
}
the problem is for every execution you are creating new Adapter
you should see this link how to use notifyDataSetChanged in listView
AsyncTask spawns a new intelligent thread on its own, runs things in background and also posts results of UI thread in onPostExecute method.
You should not call the methods of AsyncTask on your own. Android does it by itself. Instead of calling a new thread in scrollchangelistener,like:
Thread thread = new Thread(null, loadMoreListItems);
call
new LoadJsonData().execute();
you don't need two Runnable threads to do the same thing your asyncTask does.
The problem is this code of yours:
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
Every time your scrolling reaches the end, it eventually calls the onPostExecute method to post results on the UI. But here you are making a new Adapter eveytime with a new dataset which is why it always refreshes the whole list.
Remove this part and set it inside onCreate of your Activity.Add new values to your adapter's datalist in onPostExecute.
Then just do a notifyDataSetChanged inside onPostExecute of your AsyncTask.
I have a Recycler View which uses AsyncTask to populate UI.
Currently it retrieves all the data from the DB and displays it in one shot, but
I want to retrieve only 15 records in one go and after the scroll ends I want to load more 15 records and so on...can anybody please help. I have pasted the code below:
FeedActivity.java
package com.bbau.ankit.test_splash;
import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Window;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ankit on 8/14/2015.
*/
public class FeedListActivity extends Activity {
private static final String TAG = "RecyclerViewExample";
private List<FeedItem> feedItemList = new ArrayList<FeedItem>();
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Allow activity to show indeterminate progressbar */
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.news);
/* Initialize recyclerview */
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(Color.BLACK).build());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
/*Downloading data from below url*/
final String url = "http://192.168.170.72/bbau_news.php?before=1&after=5";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapter(FeedListActivity.this, feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("NEWS");
/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedItem>();
}
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("news_desc"));
item.setDescription(post.optString("Date"));
item.setUrl(post.optString("News"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
MyRecyclerAdapter.java
package com.bbau.ankit.test_splash;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.style.AlignmentSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by Ankit on 8/14/2015.
*/
public class MyRecyclerAdapter extends RecyclerView.Adapter<FeedListRowHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public FeedListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
FeedListRowHolder mh = new FeedListRowHolder(v);
mh.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("List Size", Integer.toString(getItemCount()));
TextView redditUrl = (TextView) v.findViewById(R.id.url);
String postUrl = redditUrl.getText().toString();
Log.d("The URL:", postUrl);
Intent intent = new Intent(mContext, WebViewActivity.class);
intent.putExtra("url", postUrl);
mContext.startActivity(intent);
}
});
return mh;
}
#Override
public void onBindViewHolder(FeedListRowHolder feedListRowHolder, int i) {
final FeedItem feedItem = feedItemList.get(i);
feedListRowHolder.title.setText(Html.fromHtml(feedItem.getTitle()));
feedListRowHolder.description.setText(feedItem.getDescription());
feedListRowHolder.url.setText(feedItem.getUrl());
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}
Of course you can use Recycler view and EndlessScrool as a combination like this..
Here is a sample
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loading = false;
Log.v("...", "Last Item Wow !");
}
}
}
});
Don't forget to add
LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
Here is a Github example: EndlessRecyclerOnScrollListener
This is the MainActivity.java
package com.test.webservertest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.ActionBarActivity;
import android.util.AndroidRuntimeException;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.content.Context;
import android.view.View.OnClickListener;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private final String[] ipaddresses = new String[2];
private final Integer[] ipports = new Integer[2];
private TextView text;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(new SingleTouchEventView(this, null));
/*ipaddresses[0] = "10.0.0.3";
ipaddresses[1] = "10.0.0.2";
ipports[0] = 8098;
ipports[1] = 8088;*/
//addListenerOnButton();
currentActivity = this;
initTTS();
}
public void addListenerOnButton() {
/*btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
try
{
} catch (Exception e)
{
text.setText("Connection Failed");
}
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Dispatch onStart() to all fragments. Ensure any created loaders are
* now started.
*/
#Override
protected void onStart()
{
super.onStart();
TextToSpeechServer.main(null);
}
#Override
protected void onStop() {
super.onStop();
}
public void initTTS() {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == MY_DATA_CHECK_CODE) {
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
mTts = new TextToSpeech(getApplicationContext(), new OnInitListener() {
#Override
public void onInit(int i) {
if(i == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if(result == TextToSpeech.LANG_AVAILABLE
|| result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
mTts.setPitch(1);
mTts.speak(textforthespeacch, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
});
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public static String textforthespeacch = "";
public static void TextToSpeak(String text) {
textforthespeacch = text;
}
private boolean is_start = true;
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
private Path path = new Path();
private Path circlePath = new Path();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
canvas.drawPath(circlePath, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (is_start == true)
{
response = Get("http://10.0.0.2:8098/?cmd=start");
is_start = false;
}
else
{
response = Get("http://10.0.0.2:8098/?cmd=stop");
is_start = true;
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
textforthespeacch = a;
MainActivity.currentActivity.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
circlePath.reset();
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
}
It was working fine. Maybe I need to enable something on my Android device?
My Android device is connected now to the PC via USB and working fine.
When I'm running my program in debug mode and touch the screen it never stop on:
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
I added a break point on the line: float eventX = event.getX();
But touching the screen does nothing.
You are not at all registering the OnTouchListener. First register OnTouchListener using anonymousclass or just implements it in your class
From your code you need the listener for this SingleTouchEventView view. Just add "implements View.OnTouchListenter" for the class. Because you have already overridden onTouch method in your code.
You have to change your style.xml when you remove "Extends ActionbarActivity"!
Check this change appTheme