Android JSON Custom ListView with Webview - android

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.

Related

Android: List View load more with volley

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.

On focus or onclick button not refreshing playlist from Json parser URL

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

How to send to websites on click listview in android?

I am getting list of data from json in which a parameter named as click_url is also there I fetch data in ListView .what I want when on click ListView I want to go to website that click_url contain .how can I do that.
jsons response:-
{
"offers": [{
"offer_id": 97245,
"name": "Earn Talktime & Data Android App",
"description": "Download and install",
"requirements": null,
"credit_delay": "0",
"featured_global": 0,
"epc": "0.00",
"conversion_rate": "0.016",
"testing_status": 0,
"testing_time": "0000-00-00 00:00:00",
"creative_id": 164789,
"creative_filename": "97245-164789.gif",
"creative_url": "https:\/\/asmclk.com\/creat\/97245-164789.gif",
"payout": 0.14,
"payout_custom": 0,
"stats_pending_ce": 0,
"currency_count": 70,
"target_system": 40,
"featured_profile": 0,
"click_url": "https:\/\/asmclk.com\/click.php?aff=105639&camp=97245&from=6453&prod=4&sub1=9555517491&prod_channel=1&device=fb772712-deff-4cc6-9365-41451ed33976&xt=Cb0xo807sNVx8ARZai%2B9dbKYSSBS2XZ23KjB3UGchmL3f8zjm8TT4okSW1ypbTqJ%3A6Jncp2Gx4KZjhM3JqeDoKQ%3D%3D",
"image_url": "\/\/adscendmedia.com\/creat\/97245-164789.gif",
"category_id": [17, 18],
"matches_target_system_detected": true,
"mobile_app": {
"store_id": "info.earntalktime",
"platform": 1
}
}, {
"offer_id": 107027,
"name": "Speak Up - Share Your Thoughts",
"description": "Take part in a survey and get rewarded",
"requirements": null,
"credit_delay": "0",
"featured_global": 0,
"epc": "0.00",
"conversion_rate": "0.006",
"testing_status": 0,
"testing_time": "0000-00-00 00:00:00",
"creative_id": 176235,
"creative_filename": "106989-176199.jpg",
"creative_url": "https:\/\/asmclk.com\/creat\/106989-176199.jpg",
"payout": 0.14,
"payout_custom": 0,
"stats_pending_ce": 0,
"currency_count": 70,
"target_system": 0,
"featured_profile": 0,
"click_url": "https:\/\/asmclk.com\/click.php?aff=105639&camp=107027&from=6453&prod=4&sub1=9555517491&prod_channel=1&device=fb772712-deff-4cc6-9365-41451ed33976&xt=udTdOoT4NSeWh53J%2FJaAf8UGzlJtpd9ZqLvy3TrPf53fPSmCqhaQpWu35HmDYP4V%3Apgx2an3HDsf7Za5dwjSA2A%3D%3D",
"image_url": "\/\/adscendmedia.com\/creat\/106989-176199.jpg",
"category_id": [20],
"matches_target_system_detected": true
}, {
"offer_id": 136497,
"name": "Pockets By ICICI Bank Android App",
"description": "Install and Launch",
"requirements": null,
"credit_delay": "0",
"featured_global": 0,
"epc": "0.00",
"conversion_rate": "0.021",
"testing_status": 0,
"testing_time": "0000-00-00 00:00:00",
"creative_id": 207101,
"creative_filename": "136497-207101.png",
"creative_url": "https:\/\/asmclk.com\/creat\/136497-207101.png",
"payout": 0.14,
"payout_custom": 0,
"stats_pending_ce": 0,
"currency_count": 70,
"target_system": 40,
"featured_profile": 0,
"click_url": "https:\/\/asmclk.com\/click.php?aff=105639&camp=136497&from=6453&prod=4&sub1=9555517491&prod_channel=1&device=fb772712-deff-4cc6-9365-41451ed33976&xt=TFkQXE6w185fT4sagQsrrkcdTd5LJrFe9K2pGZgJ3reXPR0MSVpvsMrjbcd9oShQ%3AaFy%2BGFW2OkHdvEvYmcIfsw%3D%3D",
"image_url": "\/\/adscendmedia.com\/creat\/136497-207101.png",
"category_id": [17, 18],
"matches_target_system_detected": true,
"mobile_app": {
"store_id": "com.icicibank.pockets",
"platform": 1
}
}]
}
listView Code:-
public void getAdscendDeal() {
String url = "http://ads.com/adwall/api/publisher/" + pubId + "/profile/" + aswallId + "/offers.json?subid1=" + m_szMobileNumber;
JSONObject jsonObject = new JSONObject();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response::" + response);
try {
JSONArray post = response.optJSONArray("offers");
for (int i = 0; i < post.length(); i++) {
JSONObject obj = post.getJSONObject(i);
m_Item = new CAdscenMediaDealStorage();
m_Item.setM_szHeaderText(obj.getString("name"));
m_Item.setM_szsubHeaderText(obj.getString("description"));
m_Item.setM_szDealValue(obj.getString("currency_count"));
m_Item.setM_szImageView(obj.getString("creative_url"));
m_Item.setM_Link(obj.getString("click_url"));
s_oDataset.add(m_Item);
}
if (!s_oDataset.isEmpty()) {
m_oAdapter = new CADscendDealAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error::" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
}
ListView Adapter
private class CADscendDealAdapter extends ArrayAdapter {
private final Context m_Context;// declaring context variable
private final ArrayList<CAdscenMediaDealStorage> s_oDataset;// declaring array list ariable
public CADscendDealAdapter(Context m_Context, ArrayList<CAdscenMediaDealStorage> mDataList) {
this.m_Context = m_Context;
s_oDataset = mDataList;
}
#Override
public int getCount() {// get total arraylist size
return s_oDataset.size();
}
#Override
public Object getItem(int position) {// get item position in array list
return s_oDataset.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("SetTextI18n")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = View.inflate(m_Context, R.layout.sooper_sonic, null);
viewHolder.m_Header = (TextView) convertView.findViewById(R.id.headingText);
viewHolder.m_Subheader = (TextView) convertView.findViewById(R.id.subHeaderText);
viewHolder.m_logoImage = (ImageView) convertView.findViewById(R.id.appImage);
viewHolder.m_getBtn = (Button) convertView.findViewById(R.id.getDealBtn);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.m_getBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn
#Override
public void onClick(View v) {//send to deal detail page onclick getDeal Btn
Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
i.putExtra("DealCode", s_oDataset.get(position).getM_szsubHeaderText());// get deal code from deal data storage
i.putExtra("headerText", s_oDataset.get(position).getM_szHeaderText());// get deal name from deal dta storage
v.getContext().startActivity(i);
}
});
CAdscenMediaDealStorage m = s_oDataset.get(position);
viewHolder.m_Header.setText(m.getM_szHeaderText());
viewHolder.m_Subheader.setText(m.getM_szsubHeaderText());
viewHolder.m_getBtn.setText("GET " + m.getM_szDealValue() + " POINTS");// set deal button text
Picasso.with(m_Context).load(m.getM_szImageView()).placeholder(R.drawable.placeholder).into(viewHolder.m_logoImage);
Picasso.with(m_Context).load(m.getM_szImageView()).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
width = width * 2;
height = height * 2;
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
viewHolder.m_logoImage.setImageBitmap(bitmap);
viewHolder.m_logoImage.requestLayout();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
// set deal logo
return convertView;
}
private class ViewHolder {
public TextView m_Header, m_Subheader, m_DummyText;
public ImageView m_logoImage;
public Button m_getBtn;
}
}
Set an OnItemClickListener on the ListView. The link will open in a browser if it is installed.
Try this code in your Activity,
m_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
String url = s_oDataset.get(position).getM_Link();
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(About.this, "No application can handle this request."
+ " Please install a webbrowser", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});

Not getting data from JSON Call Android

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"
}
]

Pass position of the item of recycler view to open up a new acitivity

How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);

Categories

Resources