Implementing Endless scrolling in Recycler View - java

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

Related

How to use If Else in spinner layout populated by JSON data url?

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.

Package file doesn't exist

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

My Listview is not refresh after update database row

My ListView is not refreshing after i am using notifyDataSetChanged();
but i dont know what is wrong in my code please help me how to update my listview when my database is update.
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Toast;
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.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class EventsView extends Fragment {
ListView list4;
String json_string;
String JSON_STRING;
JSONObject JO;
JSONObject jsonObject;
JSONArray jsonArray;
int count = 0;
HashMap<String, Object> obj;
String topic,description,event_date,event_id;
private Context mContext;
private PopupWindow mPopupWindow;
private LinearLayout linearLayout;
private Activity mActivity;
ProgressDialog pDialog;
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
HttpParse httpParse = new HttpParse();
String HttpURL = "http://192.168.1.10:8081/sms/update_event.php";
String HttpURLDelete = "http://192.168.1.10:8081/sms/delete_event.php";
SimpleAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.events_view, container, false);
mContext = getContext();
mActivity = getActivity();
linearLayout = (LinearLayout) view.findViewById(R.id.r2);
list4=(ListView)view.findViewById(R.id.list4);
new show_event().execute();
list4.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
obj = (HashMap<String, Object>) list4.getAdapter().getItem(position);
new show_list().execute();
}
});
return view;
}
class show_event extends AsyncTask<String,String,String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://192.168.1.10:8081/sms/select_event.php";
pdLoading.setMessage("\tLoading...");
pdLoading.isIndeterminate();
pdLoading.setIndeterminate(true);
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()).equals("null")) ;
{
stringBuilder.append(JSON_STRING +"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
List<Map<String, String>> data2 = null;
data2 = new ArrayList<Map<String, String>>();
json_string = result;
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
if (jsonArray.length() != 0) {
for (count = 0; count < jsonArray.length(); count++) {
JO = jsonArray.getJSONObject(count);
HashMap<String, String> datanum = new HashMap<String, String>();
datanum.put("A",JO.getString("Id"));
datanum.put("B",JO.getString("Topic"));
datanum.put("C",JO.getString("Description"));
datanum.put("D",JO.getString("Event_Date"));
data2.add(datanum);
}
adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
list4.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
pdLoading.dismiss();
}
}
class show_list extends AsyncTask<String,String,String> {
private int mYear, mMonth, mDay;
ProgressDialog pdLoading = new ProgressDialog(getActivity());
#Override
protected String doInBackground(String... strings) {
event_id=(String)obj.get("A");
topic = (String) obj.get("B");
description=(String)obj.get("C");
event_date=(String)obj.get("D");
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.isIndeterminate();
pdLoading.setIndeterminate(true);
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
final View customView = inflater.inflate(R.layout.edit_event,null);
mPopupWindow = new PopupWindow(customView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
mPopupWindow.setOutsideTouchable(true);
if(Build.VERSION.SDK_INT>=21){
mPopupWindow.setElevation(5.0f);
}
final EditText edit_topic=(EditText)customView.findViewById(R.id.edit_topic);
final EditText edit_description=(EditText)customView.findViewById(R.id.edit_description);
final EditText edit_date=(EditText)customView.findViewById(R.id.edit_Date);
Button delete_btn=(Button)customView.findViewById(R.id.delete);
Button update_btn=(Button)customView.findViewById(R.id.update);
edit_topic.setText(topic);
edit_description.setText(description);
edit_date.setText(event_date);
final String id=String.valueOf(event_id);
edit_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
edit_date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String topic= edit_topic.getText().toString();
String description= edit_description.getText().toString();
String edit_event_date=edit_date.getText().toString();
StudentRecordUpdate(id,topic,description,edit_event_date);
mPopupWindow.dismiss();
}
});
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StudentDelete(id);
}
});
mPopupWindow.showAtLocation(linearLayout, Gravity.CENTER,0,0);
mPopupWindow.setFocusable(true);
mPopupWindow.update();
pdLoading.dismiss();
}
}
public void StudentRecordUpdate(final String id, final String topic, final String description, final String event_date){
class StudentRecordUpdateClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
Toast.makeText(getActivity(),httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
hashMap.put("Id",params[0]);
hashMap.put("Topic",params[1]);
hashMap.put("Description",params[2]);
hashMap.put("Event_Date",params[3]);
finalResult = httpParse.postRequest(hashMap, HttpURL);
return finalResult;
}
}
StudentRecordUpdateClass studentRecordUpdateClass = new StudentRecordUpdateClass();
studentRecordUpdateClass.execute(id,topic,description,event_date);
}
// Method to Delete Student Record
public void StudentDelete(final String ID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(), "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
Toast.makeText(getContext(), httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
getActivity().finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("Id", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpURLDelete);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(ID);
}
}
Try this set Adapter with empty list as soon as you initialize your ListView, then just add data to list and call notifyDataSetChanged() on adapter
Make list global
List<Map<String, String>> data2 = new ArrayList<Map<String, String>>();
Then in onCreateView, add below code under listview initialization
list4=(ListView)view.findViewById(R.id.list4);
adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
list4.setAdapter(adapter);
Then in onPostExecute of your AsyncTask, clear the existing list and new data,then just call notifyDataSetChanged() as in
#Override
protected void onPostExecute(String result) {
data2.clear(); //< --add this
json_string = result;
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
if (jsonArray.length() != 0) {
for (count = 0; count < jsonArray.length(); count++) {
JO = jsonArray.getJSONObject(count);
HashMap<String, String> datanum = new HashMap<String, String>();
datanum.put("A",JO.getString("Id"));
datanum.put("B",JO.getString("Topic"));
datanum.put("C",JO.getString("Description"));
datanum.put("D",JO.getString("Event_Date"));
data2.add(datanum);
}
adapter.notifyDataSetChanged(); //< --- call this
}
} catch (JSONException e) {
e.printStackTrace();
}
pdLoading.dismiss();
}

How to add swipe-to-refresh in a list view

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

Custom List View Adapter Syntax for images

I am new to Android development and am in the process of creating my first app. The app takes a picture, previews that picture, randomly selects a picture from the database to upload to the server and displays JSON text information in listview.
I am trying to use a custom list view adapter to allow the JSON information's corresponding picture to be in the LISTVIEW and NOT imageview.
I have thoroughly researched listview adapters to understand the syntax and where to place the code to implement the listview with a picture properly. However, I am receiving four error messages which prevent the code from compiling. I realize that there are other posts about similar topics on this website, but I have dug around them and tried to implement the states solutions with no success.
Below is my code:
public class JSONBuilderActivity extends ListActivity {
private ProgressDialog pDialog;
//URL to get JSON
private static String url = ".........";
//JSON Node names
private static final String TAG_CARS = "cars"; //root
private static final String TAG_CARID = "CarID";
private static final String TAG_CARVIN = "CarVIN";
private static final String TAG_IMG = "CarMainImage";
CustomListViewAdapter adapter;
JSONArray carid = null; //Initializes JSON array
private CustomListViewAdapter clva = null;
ListView lv;
List<Item> item = new ArrayList<JSONBuilderActivity.Item>();
static String response = null;
//Hashmap for ListView
ArrayList<HashMap<String, Object>> caridList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = getListView();
//ArrayList<Item> item;
lv.setAdapter(adapter);
lv = (ListView) findViewById(R.id.list_item);
adapter = new CustomListViewAdapter(this,item);
lv.setAdapter(adapter);
//Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Gets values from selected ListItem
String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
String car_vin = ((TextView) view.findViewById(R.id.car_vin)).getText().toString();
String model_img = ((ImageView) view.findViewById(R.id.model_img)).getTag().toString();
Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
//Sends data to MainActivity
in.putExtra("TAG_CARS", cars);
in.putExtra("TAG_CARID", car_id);
in.putExtra("TAG_CarVin", car_vin);
in.putExtra("TAG_IMG", model_img);
startActivity(in);
}
});
//Calls async task to get json
new GetCars().execute();
}
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Makes service call
*
* #url - url to make request
* #method - http request method
*/
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Makes service call
*
* #url - url to make request
* #method - http request method
* #params - http request params
*/
public String makeServiceCall(String url, int method, ArrayList<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//Checks http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
//Adds post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//Appends params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "CarMainImage", null);
return Uri.parse(path);
}
public void saveBmpToFile(File filename, Bitmap bmp) {
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean renameFileExtension(String source, String newExtension) {
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals("")) {
target = source + "." + newExtension;
} else {
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
public String getFileExtension(String f) {
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1) {
ext = f.substring(i + 1);
}
return ext;
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, Object>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String car_vin = c.getString(TAG_CARVIN);
Log.d("car_vin", car_vin);
String model_img = c.getString(TAG_IMG);
Log.d("model_img", model_img);
//CustomListViewAdapter adapter = new CustomListViewAdapter(this, R.layout.list_item, item);
// String model_img = c.getString(TAG_IMG);
//Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_CARVIN, car_vin);
matchGetCars.put(TAG_IMG, model_img);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
//ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
// new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
// setListAdapter(adapter);
ListView lv = (ListView)findViewById(R.id.list_item);
clva = new CustomListViewAdapter();
lv.setAdapter(clva);
}
}
public class CustomListViewAdapter extends ArrayAdapter<Item> {
private ArrayList<Item> objitem;
Activity context;
public CustomListViewAdapter(ArrayList<Item> item, int ResourceId, Activity context){
super(context, ResourceId, item);
this.context = context;
this.objitem = item;
}
private class ViewHolder {
ImageView model_img;
TextView car_id;
TextView car_vin;
}
public View getView ( int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
final Item item = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder.car_id = (TextView) convertView.findViewById(R.id.car_id);
holder.car_vin = (TextView) convertView.findViewById(R.id.car_vin);
holder.model_img = (ImageView) convertView.findViewById(R.id.model_img);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.car_id.setText(item.getVin());
holder.car_vin.setText(item.getId());
holder.model_img.setImageResource(item.getmodelimg());
return convertView;
}
}
public class Item {
private int model_img;
private String car_id;
private String car_vin;
public Item(int model_img, String car_id, String car_vin) {
this.model_img = model_img;
this.car_id = car_id;
this.car_vin = car_vin;
}
/* Getters
*/
public int getmodelimg() {
return model_img;
}
public String getVin() {
return car_vin;
}
public String getId() {
return car_id;
}
/* Setters
*/
public void setmodelimg(int model_img) {
this.model_img = model_img;
}
public void setVin(String car_vin) {
this.car_vin = car_vin;
}
public void setId(String car_id) {
this.car_id = car_id;
}
}
}
Error:
CustomListViewAdapter() cannot be applied to CustomListViewAdapter for:
adapter = new CustomListViewAdapter(this,item); in onCreate
Update:
adapter = new CustomListViewAdapter(this, R.id.list_view, item); in onCreate.'
I still receive the same (above) error.
Imports:
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
I am having trouble understanding what I am doing so incorrect. I appreciate any input. Thank you.
You're trying to instantiate the adapter which has this constructor
public CustomListViewAdapter(ArrayList<Item> item, int ResourceId, Activity context)
although you're calling it like this
adapter = new CustomListViewAdapter(this,item);
problem: the arguments don't match
It should be something like
adapter = new CustomListViewAdapter(item, R.layout.list_row, this);
note that list_row is something I made up and should be an actual layout file in your app or in the android sdk

Categories