I want when i scroll up to my list view load more data using volley, i created PHP webservice and result
{
"error": false,
"status_code": 200,
"total_items": 2,
"last_page": 1,
"current_page": 1,
"per_page": 10,
"result": [
{
"id": 1,
"title": "here title one",
"city": "city",
"zone": "zone",
"type": "type",
"service": "service",
"space": "545",
"date": "2016-08-28 12:24:34",
"image": "http:\/\/localhost\/my_cms\/public\/assets\/media\/ad-pic.png"
}, {
"id": 2,
"title": "here title two",
"city": "city",
"zone": "zone",
"type": "type",
"service": "service",
"space": "545",
"date": "2016-08-28 12:24:34",
"image": "http:\/\/localhost\/my_cms\/public\/assets\/media\/ad-pic.png"
}]
}
My RecentActivity.Java Class
public class RecentActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, AbsListView.OnScrollListener {
private SwipeRefreshLayout swipeRefreshLayout;
// Log tag
private static final String TAG = HomeActivity.class.getSimpleName();
// RealstateDataModel json url
private static final String homeAdsurl = "http://192.168.43.74/my_cms/public/api/realstate/latest?page=";
private ProgressDialog pDialog;
private List<RealstateDataModel> realstateData = new ArrayList<RealstateDataModel>();
private ListView listView;
private HomeListAdapter homaAdapter;
int current_page = 0;
boolean loading;
RecentActivity activity = null;
View loadMoreView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recent);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.Recent_View);
String home= getResources().getString(R.string.recient_offers);
setTitle(home);
activity = this;
//List View
setListAdapter();
listView.setOnScrollListener(this);
}
public void setListAdapter(){
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_recent_layout);
homaAdapter = new HomeListAdapter(this, realstateData);
listView.setAdapter(homaAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchRealStateList();
}
}
);
}
#Override
public void onRefresh() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
fetchRealStateList();
}
private void fetchRealStateList() {
// Creating volley request obj
JsonObjectRequest homeListReq = new JsonObjectRequest(Request.Method.GET,
homeAdsurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
if (response.length() > 0) {
try {
JSONArray ResultArray = response.getJSONArray("result");
if(realstateData!=null) {
realstateData.clear();
}
// Parsing json
for (int i = 0; i < ResultArray.length(); i++) {
try {
JSONObject obj = ResultArray.getJSONObject(i);
RealstateDataModel realstateDataBeans = new RealstateDataModel();
realstateDataBeans.setTitle(obj.getString("title"));
realstateDataBeans.setCity(obj.getString("city"));
realstateDataBeans.setZone(obj.getString("zone"));
realstateDataBeans.setType(obj.getString("type"));
realstateDataBeans.setService(obj.getString("service"));
realstateDataBeans.setSpace(obj.getString("space"));
realstateDataBeans.setCreated_at(obj.getString("date"));
realstateDataBeans.setImage(obj.getString("image"));
// adding movie to movies array
realstateData.add(0,realstateDataBeans);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
homaAdapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(homeListReq);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
}
It tried and searched more but when it try to scroll not effect, i make f
onScrollStateChanged and onScroll empty to fill it your helpful code
For example load 10 item at first. When user reach the bottom load 10 more item. How can you understand it is bottom?
The last item's bottom == scroll position
means end of the list. Load more.
Related
I'm working on a simple news app.
I need to fetch data from a remote server in JSON format then put it in view. I use TabLayout and recyclerView to display data categories and Volley for the query no API here.
The TabLayout is set automatically depending on data from JSON where I extract tabs title and the content of every tab is being displayed on recyclerView (Article title, image, content, links...) and rendered inside a fragment
I spent several hours trying to debug it without success., but whatever I do, no data is being displayed. Not sure what I'm doing wrong.
I know this is not the right place to ask for such things, but I'm a bit of a desperate and would need some experienced developer than me look at my problem.
How it works:
Activity launches BaseArticleFragment which calls a method that loads contents categories and bind the data to the views:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.fm = getSupportFragmentManager();
this.baseArticleFragment = new BaseArticleFragment();
FragmentTransaction ft = this.fm.beginTransaction();
ft.add(R.id.fragment_container, this.baseArticleFragment, TAB_LAYOUT_FRAGMENT_TAG);
ft.commit();
}
When launched, baseArticleFragment calls loadCategories() method inside its onActivityCreated() method:
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
loadCategories();
}
here is the loadCategories() method:
private void loadCategories(){
String url = "http://somesite.com/categories"; //link to grab the json data
ApplicationController.getInstance().addToRequestQueue(
new JsonObjectRequest(0, url, null, new Listener<JSONObject>() { //0 is the Volley code for GET method
#Override
public void onResponse(JSONObject jsonObject) {
BaseArticleFragment.categories = JSONParser.parseCategories(jsonObject);
BaseArticleFragment.this.mViewPager.setAdapter(
new RecyclerViewFragmentPagerAdapter(BaseArticleFragment.this.getChildFragmentManager(),
BaseArticleFragment.categories));
BaseArticleFragment.this.mTabLayout.setupWithViewPager(BaseArticleFragment.this.mViewPager);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError vError){
Log.d("BaseArticleFragment", "---Volley Error---");
Snackbar.make(BaseArticleFragment.this.mTabLayout, R.string.error_load_categories, Snackbar.LENGTH_SHORT)
.setAction(R.string.action_retry, new View.OnClickListener() {
#Override
public void onClick(View v) {
BaseArticleFragment.this.loadCategories();
}
}).show();
}
}));
}
I guess the problem may be with the query but not sure cause I think my logic here is good
EDIT :
Here is the JSON data I need to fetch:
[
{
"name": "Topic 1",
"tid": "2",
},
{
"name": "Topic 2",
"tid": "3",
},
{
"name": "Topic 3",
"tid": "4",
},
{
"name": "Topic 4",
"tid": "5",
},
{
"name": "Topic 5",
"tid": "6",
},
{
"name": "Topic 6",
"tid": "1415",
},
{
"name": "Topic 7",
"tid": "1414",
},
{
"name": "Topic 8",
"tid": "1298",
},
{
"name": "Topic 9",
"tid": "1301",
},
{
"name": "Topic 10",
"tid": "1299",
},
{
"name": "Topic 11",
"tid": "1302",
},
{
"name": "Topic 12",
"tid": "1300",
},
{
"name": "Topic 13",
"tid": "1297",
}
]
Edit 2:
I forget to paste the code for parseCategories() in my JSONPArser class
public static ArrayList<Category> parseCategories(JSONObject jsonObject) {
ArrayList<Category> categoryArrayList = new ArrayList<>();
try {
JSONArray categories = jsonObject.getJSONArray("categories");
Category all = new Category();
all.setTid("0");
all.setName(ApplicationController.getInstance().getString(R.string.tab_all));
categoryArrayList.add(all);
for (int i = 0; i < categories.length(); i++) {
JSONObject catObject = categories.getJSONObject(i);
Category category = new Category();
category.setTid(catObject.getString("tid"));
category.setName(catObject.getString("name"));
categoryArrayList.add(category);
}
return categoryArrayList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
Try this #esQmo_,
StringRequest stringRequest = new StringRequest(url , new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
ArrayList<Hashmap<String,String>> arraylist = new
ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> hashMap = new HashMap<>();
String name =
jsonArray.getJSONObject(i).getString("name");
String tid =
jsonArray.getJSONObject(i).getString("tid");
hashMap.put("name", name);
hashMap.put("tid ", tid );
arraylist.add(hashMap);
Log.e("response",name + "\n" + tid);
}
attachAdapter(arraylist);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
//setting adapter data to the RecyclerView
private void attachAdapter(ArrayList<HashMap<String, String>>
arrayList) {
ExampleAdapter adapter = new ExampleAdapter(arrayList,this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
This is the adapter class
public class ExampleAdpater extends RecyclerView.Adapter<ExampleAdpater.ExampleViewHolder>{
public ArrayList<HashMap<String,String>> arraylist;
public Context context;
public ExampleAdpater(ArrayList<HashMap<String, String>> arraylist, Context context) {
this.arraylist= arraylist;
this.context = context;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.textLayout,viewGroup,false);
return new ExampleViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder viewHolder, int i) {
HashMap<String,String> hashMap = arraylist.get(i);
viewHolder.name.setText(hashMap.get("name"));
viewHolder.tid.setText(hashMap.get("tid"));
}
#Override
public int getItemCount() {
return arraylist.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder{
TextView name,tid;
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
tid = itemView.findViewById(R.id.tid);
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), ""+name.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
textLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tid"
/>
</LinearLayout>
You forgot to add this thing at the end of the "load" method:
Volley.newRequestQueue(this).add(jsonRequest);
Try to add it...
Instead of using new RequestQueue, please use RequestQueue jsonQueue = new RequestQueue
Like this:
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "https://someurl.com/api";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray ja = new JSONArray(response);
for(int i = 0; i < ja.length(); i++)
{
JSONObject jo = ja.get(i);
String name = jo.getString("name");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG", error.toString());
}
});
requestQueue.add(jsonObjectRequest);
Just check if you have set LayoutManager for recyclerView
recyclerView.setLayoutManager(new LinearLayoutManager(MyActivity.this));
Can we have your code and JSON data too? Since we can't read what's on your mind or on your computer... Plase make some edits to your post, add code and json data so we may help you.
Since you are getting a timeout error you can change the timeout value so that it will be willing to wait longer.
Try something like this:
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
where MY_SOCKET_TIMEOUT_MS is amount of time (in milliseconds) you want to wait before a timeout. Start with 5000 (5 seconds) and play around with it.
Do this before
requestQueue.add(jsonObjectRequest);
How to achieve this guys?
I have two buttons om my app.
Button1 fetch/retrieve All Videos playlist from Json file on URL called VideoAll.js
Button2 fetch/retrieve UK Videos playlist from Json file on URL called VideoUK.js
My code is working and its fetching the playlist when I click All (VideoAll.js) button, but when I click UK button its not refreshing and I get the same list from VideoAll.js I have to close the app and open to click UK button first to get the correct playlist from VideoUK.js, but again I cant get the list from All. Basically its not refreshing or updating onclick or even onfocus. its calling Json every time I click so I am sure this is not the way is done and I am doing it wrong.
MyActivity
public class VideoPlayerActivity extends Activity implements MediaPlayer.OnPreparedListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
//private Toolbar toolbar;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private RelativeLayout mDrawerRelativeLayout;
public static final String EXTRA_INDEX = "EXTRA_INDEX";
public static final int PLAYLIST_ID = 6; //Arbitrary, for the example (different from audio)
protected EMVideoView emVideoView;
protected PlaylistManager playlistManager;
protected int selectedIndex = 2;//Auto play first video
private final String VIDEO_URL1 = "http://satdoc.dyndns.info/all.js";
private final String VIDEO_URL2 = "http://satdoc.dyndns.info/uk.js";
private String TAG = "VideoPlayerActivity";
List<VideoItem> videoList = new ArrayList<>();
private FullScreenListener fullScreenListener;
//private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_player_activity);
setVolumeControlStream(3);
mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.selection_activity_list);
mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
emVideoView = (EMVideoView) findViewById(R.id.video_play_activity_video_view);
emVideoView.setOnPreparedListener(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
fullScreenListener = new FullScreenListener();
}
goFullscreen();
emVideoView.setVideoViewControlsCallback(new DefaultControlsCallback());
initDrawer();
Button btn = (Button) findViewById(R.id.button);
Button btn2 = (Button) findViewById(R.id.button2);
btn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus) {
fetchVideos1();
}
}
});
btn2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus) {
fetchVideos2();
}
}
});
}
/**
* Fetch for videos online.
*/
public void fetchVideos1() {
if (NetworkConnectionStatus.isOnline(this)) {//If there is internet connection, load reviews through a http request.
final ProgressDialog progressDialog = new ProgressDialog(this);
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(20_000);
client.get(VIDEO_URL1, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {// called when response HTTP status is "200 OK"
String jsonResponse = new String(response);
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
JSONObject jsonObject;
String videoTitle, videoUrl;
int videoNum;
int length = jsonArray.length();
for (int i = 0; i < length; ++i) {
jsonObject = (JSONObject) jsonArray.get(i);
videoTitle = jsonObject.getString("chname");
videoUrl = jsonObject.getString("chlink");
videoNum = jsonObject.getInt("chid");
VideoItem videoItem = new VideoItem(videoTitle, videoUrl, videoNum);
videoList.add(videoItem);
}
setTitle(mDrawerTitle);
init();
mDrawerList.setAdapter(new VideoSelectionListAdapter(VideoPlayerActivity.this, videoList));
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
progressDialog.dismiss();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Toast.makeText(VideoPlayerActivity.this, "A server error occured, Try again later", Toast.LENGTH_LONG).show();
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
} else {
Toast.makeText(VideoPlayerActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
}
public void fetchVideos2() {
if (NetworkConnectionStatus.isOnline(this)) {//If there is internet connection, load reviews through a http request.
final ProgressDialog progressDialog = new ProgressDialog(this);
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(20_000);
client.get(VIDEO_URL2, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {// called when response HTTP status is "200 OK"
String jsonResponse = new String(response);
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
JSONObject jsonObject;
String videoTitle, videoUrl;
int videoNum;
int length = jsonArray.length();
for (int i = 0; i < length; ++i) {
jsonObject = (JSONObject) jsonArray.get(i);
videoTitle = jsonObject.getString("chname");
videoUrl = jsonObject.getString("chlink");
videoNum = jsonObject.getInt("chid");
VideoItem videoItem = new VideoItem(videoTitle, videoUrl, videoNum);
videoList.add(videoItem);
}
setTitle(mDrawerTitle);
init();
mDrawerList.setAdapter(new VideoSelectionListAdapter(VideoPlayerActivity.this, videoList));
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
progressDialog.dismiss();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Toast.makeText(VideoPlayerActivity.this, "A server error occured, Try again later", Toast.LENGTH_LONG).show();
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
} else {
Toast.makeText(VideoPlayerActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
}
And here is my 2nd Json file on the server (VideoUK.js)
[
{
"chid": 1,
"chname": "UK1",
"chlogo": "",
"chlink": "http://samplevideoUK1.mp4",
"chenable": "",
"chnote": ""
},
{
"chid": 2,
"chname": "UK 2",
"chlogo": "",
"chlink": "http://samplevideoUK2.mp4",
"chenable": "",
"chnote": ""
},
{
"chid": 3,
"chname": "UK 3",
"chlogo": "",
"chlink": "http://samplevideoUK3.mp4",
"chenable": "",
"chnote":
}
]
and here is (VideoAll.js)
[
{
"chid": 1,
"chname": "Video 1",
"chlogo": "",
"chlink": "http://samplevideo1.mp4",
"chenable": "",
"chnote": ""
},
{
"chid": 2,
"chname": "Video 2",
"chlogo": "",
"chlink": "http://samplevideo2.mp4",
"chenable": "",
"chnote": ""
},
{
"chid": 3,
"chname": "RO 3",
"chlogo": "",
"chlink": "http://samplevideo3.mp4",
"chenable": "",
"chnote":
}
]
and finally my buttons in my layout
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="All"
android:id="#+id/button1"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/uk"
android:id="#+id/button2"
android:choiceMode="none"
android:focusable="true"
android:fadeScrollbars="false"
android:layout_weight="1" />
</LinearLayout>
Can someone please at least show an example of how to call json and get the list every time we click the button refreshed?. Only the button that is clicked first works but after that nothing changes when I click. sorry for repeating but its driving me mad.
Screenshot of my ap
firstly clear video list on button click
btn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus) {
videoList.clear();
fetchVideos1();
}
}
});
btn2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus) {
videoList.clear();
fetchVideos2();
}
}
});
and notify data set chenge after setting adapter in webservices like:
mDrawerList.notifyDataSetChanged();
Please Use this After This lines in your code :
setTitle(mDrawerTitle);
init();
mDrawerList.setAdapter(new VideoSelectionListAdapter(VideoPlayerActivity.this, videoList));
notifyDataSetChanged();
it is used to refresh adapter
also clear list on vutton click
I'm using this tutorial .I'm trying to get image from Json .Listview works Well , When i click Listview (example: second line) i want to see image2 in webview , but i have problem possition.
private static final String TAG = Jsonlol.class.getSimpleName();
private String url;
private List<ListItem> listItem = new ArrayList<ListItem>();
private ListView listView;
private CustomListAdapter adapter;
private Dialog webViewDialog;
private WebView webView;
private Button btClose;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.json_main);
url = getString(R.string.hellojson);
listView = (ListView) findViewById(R.id.listview);
adapter = new CustomListAdapter(this, listItem);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position == 0)
{
webView.loadUrl(" Image 1 HERE ");
webViewDialog = new Dialog(Jsonlol.this);
webViewDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
webViewDialog.setContentView(R.layout.wepbas);
webView = (WebView) webViewDialog.findViewById(R.id.wb_webview);
webViewDialog.show();
}
if(position == 1)
{
webView.loadUrl(" Image 2 HERE ");
webViewDialog = new Dialog(Jsonlol.this);
webViewDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
webViewDialog.setContentView(R.layout.wepbas);
webView = (WebView) webViewDialog.findViewById(R.id.wb_webview);
webViewDialog.show();
}
} });
JsonArrayPostRequest itemReq = new JsonArrayPostRequest(url,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ListItem item = new ListItem();
item.setTitle(obj.getString("title"));
item.setThumbnailUrl(obj.getString("image"));
item.setrlevel(obj.getString("rlevel"));
listItem.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(itemReq);
}
#Override
public void onDestroy() {
super.onDestroy();
}
here Json
[{
"id": "1",
"title": "Test 1",
"image": "http://api.androidhive.info/json/movies/1.jpg",
"image2": "http://api.androidhive.info/json/movies/1.jpg",
"rlevel": "Test 1"
},
{
"id": "2",
"title": "Test 2",
"image": "http://api.androidhive.info/json/movies/2.jpg",
"image2": "http://api.androidhive.info/json/movies/2.jpg",
"rlevel": "Test 2"
}]
you are calling webView at wrong place,
if(position == 0)
{
webViewDialog = new Dialog(Jsonlol.this);
webViewDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
webViewDialog.setContentView(R.layout.wepbas);
webView = (WebView) webViewDialog.findViewById(R.id.wb_webview);
webView.loadUrl(listItem.get(0).getThumbnailUrl());
webViewDialog.show();
}
if(position == 1)
{
webViewDialog = new Dialog(Jsonlol.this);
webViewDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
webViewDialog.setContentView(R.layout.wepbas);
webView = (WebView) webViewDialog.findViewById(R.id.wb_webview);
webView.loadUrl(listItem.get(1).getThumbnailUrl());
webViewDialog.show();
}
But if your aim is only showing image when users clicked to your list item, you can try to show your image to an ImageView with picasso , ion and this kind of libraries.
This is my java file where I'm trying to call Json, but I'm not getting any data. Also I'm not getting any error, so I couldn't find where the problem is.
Here is my code and the Json looks like this:
[
{
"title": "Quest",
"description": "Description Quest",
"district": "District Quest";
}
]
AND THE CODE:
public class Quests extends Fragment {
// Log tag
private static final String TAG = Quests.class.getSimpleName();
// Quest Json url
private static final String url = "http://my-ip-adress-of-computer/project/quests.txt";
private ProgressDialog pDialog;
private List<com.dusandimitrijevic.model.Quests> questList = new ArrayList<com.dusandimitrijevic.model.Quests>();
private ListView listView;
private QuestListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quests, container, false);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
listView = (ListView) rootView.findViewById(R.id.list);
adapter = new QuestListAdapter(getActivity(), questList);
listView.setAdapter(adapter);
fetchQuests();
return rootView;
}
private void fetchQuests() {
// Creating volley request obj
JsonArrayRequest questReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
com.dusandimitrijevic.model.Quests q = new com.dusandimitrijevic.model.Quests();
q.setTitle(obj.getString("title"));
q.setDescription(obj.getString("description"));
q.setDistrict(obj.getString("district"));
// adding quests to quest array
questList.add(q);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
// stopping swipe refresh
//swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
// stopping swipe refresh
//swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(questReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Semicolon ; is no a valid field separator. Also you can't use a field separator after the last field at all. Valid JSON should look like this:
[
{
"title": "Quest",
"description": "Description Quest",
"district": "District Quest"
}
]
This is my MainActivity, I really need help on creating a function that will autorefresh the listview every minute
In my MainActivity I have this code:
//This method is called when swipe refresh is pulled down
#Override
public void onRefresh() {
fetchOrders();
}
I've read a few articles about the handler, I gotta say I have no idea where to put the handler's code, therefore if you can give me a hand and post my full MainActivity with that additional desired code, it would be more than appreciated
Thanks in advance!
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private String TAG = MainActivity.class.getSimpleName();
private String URL = "http://troyka.esy.es/troyka/orders.php";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Order> orderList;
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
//RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(50,10);
//Rl.setLayoutParams(layout_description);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
orderList = new ArrayList<>();
adapter = new SwipeListAdapter(this, orderList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchOrders();
}
}
);
mHandler = new Handler();
startRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
//updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
/**
* This method is called when swipe refresh is pulled down
*/
#Override
public void onRefresh() {
fetchOrders();
}
/**
* Fetching movies json by making http call
*/
private void fetchOrders() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to order list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject orderObj = response.getJSONObject(i);
int rank = orderObj.getInt("rank");
String title = orderObj.getString("title");
Order m = new Order(rank, title);
orderList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
}
You can do that by added a delayed task to Handler. Here is the full code:
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private String TAG = MainActivity.class.getSimpleName();
private String URL = "http://troyka.esy.es/troyka/orders.php";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Order> orderList;
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
//RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(50,10);
//Rl.setLayoutParams(layout_description);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
orderList = new ArrayList<>();
adapter = new SwipeListAdapter(this, orderList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchOrders();
}
}
);
mHandler = new Handler();
startRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
//updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
//added code start here
Runnable mAutoRefreshRunnable = new Runnable() {
#Override
public void run() {
fetchOrders()
mHandler.postDelayed(mAutoRefreshRunnable, 1000);
}
};
#Override
protected void onResume() {
mHandler.postDelayed(mAutoRefreshRunnable, 1000);
}
#Override
protected void onPause() {
mHandler.removeCallbacks(mAutoRefreshRunnable);
}
//added code ends here
/**
* This method is called when swipe refresh is pulled down
*/
#Override
public void onRefresh() {
fetchOrders();
}
/**
* Fetching movies json by making http call
*/
private void fetchOrders() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to order list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject orderObj = response.getJSONObject(i);
int rank = orderObj.getInt("rank");
String title = orderObj.getString("title");
Order m = new Order(rank, title);
orderList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
}