i want to read from json on url address to list view but there is noting to show.
this is my code.
main activity.
package customlistviewvolley;
import com.example.customlistviewvolley.R;
/*import java.io.IOException;
import java.io.InputStream;*/
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import customlistviewvolleyadater.CustomListAdapter;
import customlistviewvolleyapp.AppController;
import customlistviewvolleymodel.App;
public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://192.168.1.5/public_html/android/new.json";
private ProgressDialog pDialog;
private List<App> appList = new ArrayList<App>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, appList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest appReq = 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);
App app = new App();
app.setAppTitle(obj.getString("app_title"));
app.setAppImageUrl(obj.getString("app_image"));
app.setRatingBar(((Number) obj.get("app_rating"))
.doubleValue());
app.setAppCreator(obj.getString("app_creator"));
app.setAppCase(obj.getString("app_case"));
// adding app to app array
appList.add(app);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(appReq);
}
/* JSONObject obj1 = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj1.getJSONArray("apps");
//ArrayList<HashMap<String, String>> formList= new ArrayList<HashMap<String, String>>();
// HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++) {
try {
JSONObject obj = m_jArry.getJSONObject(i);
App app = new App();
app.setAppTitle(obj.getString("app_title"));
app.setAppImageUrl(obj.getString("app_image"));
app.setRatingBar(((Number) obj.get("rating_bar"))
.doubleValue());
app.setAppCreator(obj.getString("app_creator"));
app.setAppCase(obj.getString("app_case"));
// adding movie to movies array
appList.add(app);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Same way for other value...
}*/
/*public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("jsonfile.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
} */
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
custom adapter.
package customlistviewvolleyadater;
import com.example.customlistviewvolley.R;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import customlistviewvolleyapp.AppController;
import customlistviewvolleymodel.App;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<App> appItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<App> appItems) {
this.activity = activity;
this.appItems = appItems;
}
#Override
public int getCount() {
return appItems.size();
}
#Override
public Object getItem(int location) {
return appItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.top_new_free, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView appImage = (NetworkImageView) convertView
.findViewById(R.id.app_image);
TextView appTitle = (TextView) convertView.findViewById(R.id.app_title);
TextView appCase = (TextView) convertView.findViewById(R.id.app_case);
TextView appCreator = (TextView) convertView.findViewById(R.id.app_creator);
RatingBar ratingBar = (RatingBar) convertView.findViewById(R.id.app_rating_bar);
// getting app data for the row
App app = appItems.get(position);
// app image
appImage.setImageUrl(app.getAppImageUrl(), imageLoader);
// title
appTitle.setText(app.getAppTitle());
// app creator
appCreator.setText( app.getAppCreator());
// appCase
appCase.setText(app.getAppCase());
// rating bar
ratingBar.setNumStars((int) app.getRatingBar());
return convertView;
}
}
app controller.
package customlistviewvolleyapp;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import customlistviewvolleyutil.LruBitmapCache;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
app.
package customlistviewvolleymodel;
public class App {
private String appTitle, appImageUrl, appCreator;
private double ratingBar;
private String appCase;
public App() {
}
public App(String appName, String appImageUrl, String appCreator, double ratingBar,
String appCase) {
this.appTitle = appName;
this.appImageUrl = appImageUrl;
this.appCreator = appCreator;
this.ratingBar = ratingBar;
this.appCase = appCase;
}
public String getAppTitle() {
return appTitle;
}
public void setAppTitle(String name) {
this.appTitle = name;
}
public String getAppImageUrl() {
return appImageUrl;
}
public void setAppImageUrl(String appImageUrl) {
this.appImageUrl = appImageUrl;
}
public String getAppCreator() {
return appCreator;
}
public void setAppCreator(String appCreator) {
this.appCreator = appCreator;
}
public double getRatingBar() {
return ratingBar;
}
public void setRatingBar(double ratingBar) {
this.ratingBar = ratingBar;
}
public String getAppCase() {
return appCase;
}
public void setAppCase(String appCase) {
this.appCase = appCase;
}
}
here is my cache code .
` `package customlistviewvolleyutil;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
my main activity xml .
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:padding="5dip"
android:clipToPadding="false"
android:listSelector="#drawable/list_row_selector" />
</RelativeLayout>
my rows here .
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp" >
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/app_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp" />
<!-- App(movie) Title -->
<TextView
android:id="#+id/app_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/app_image"
android:layout_toLeftOf="#+id/app_image"
android:textSize="#dimen/title"
android:textStyle="bold" />
<!-- App Creator -->
<TextView
android:id="#+id/app_creator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/app_image"
android:layout_toLeftOf="#+id/app_image"
android:textSize="#dimen/creator"
android:layout_marginTop="1dip"
android:textStyle="bold" />
<!-- Type Free or NotFree or Installed -->
<TextView
android:id="#+id/app_case"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:textColor="#color/year"
android:textSize="#dimen/type" />
<!-- Rating Bar -->
<RatingBar
android:id="#+id/app_rating_bar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_toLeftOf="#+id/app_image"
android:layout_below="#+id/app_creator"
android:stepSize="0.5" />
</RelativeLayout>
plz help me to fix it.
You should access localhost sites in such a way:
http://localhost:8080/MyTestPage.html
Read this to get further information:
http://www.androidref.com//index.html#LocalBrowser
Related
I'm using volley to load data using JSON Parsing in to a recycler view. I've used recylcer view before, but somehow, the downloaded data is persistent this time, meaning its still there after the app is closed, maybe stays in cache. I'm not sure, what I'm doing wrong here. Any help is appreciated, thanks.
Edit: The application is storing downloaded data after the app is closed, which doesn't happen when using recycler view.
This is my Activity Class:
package com.example.recyclerview;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity implements
OnItemClick{
private ArrayList<PostData> posts = new ArrayList<>();
private PostRecycleViewAdapter viewAdapter;
private String listingJsonUrl = "https://jsonplaceholder.typicode.com/posts/";
Toolbar toolbar;
private ProgressDialog progressDialog;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
final RecyclerView.LayoutManager viewLayoutManager = new LinearLayoutManager(getApplicationContext());
viewAdapter = new PostRecycleViewAdapter(posts);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(viewLayoutManager);
recyclerView.setAdapter(viewAdapter);
viewAdapter.setClickListener(this);
new DownloadData().execute(listingJsonUrl);
}
#Override
public void onClick(View view, int position) {
final PostData data = posts.get(position);
String title;
int id;
Intent commentIntent = new Intent(this, CommentsActivity.class);
id = data.getId();
title = data.getTitle();
if(title.length() > 25){
title = title.substring(0,25);
title = title.concat("..");
}
commentIntent.putExtra("title",title) ;
commentIntent.putExtra("id", id);
startActivity(commentIntent);
}
class DownloadData extends AsyncTask<String, String, String>{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... url) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url[0], new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PostData postData = new PostData(jsonObject.getInt("id"),jsonObject.getString("title"), jsonObject.getString("body"));
posts.add(postData);
viewAdapter.notifyDataSetChanged();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JsonError", error.getMessage());
}
});
getRequestQueue().add(jsonArrayRequest);
return null;
}
}
public RequestQueue getRequestQueue()
{
if (requestQueue == null)
{
requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
}
This is my RecyclerView Adapter Class:
package com.example.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostRecycleViewAdapter extends RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>
{
private List<PostData> postData;
private OnItemClick itemClick;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView title, body;
public ViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.title);
body = (TextView) view.findViewById(R.id.body);
view.setTag(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(itemClick != null) itemClick.onClick(view, getAdapterPosition());
}
}
public PostRecycleViewAdapter(List<PostData> postData)
{
this.postData = postData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_recycler_view,parent,false);
return new ViewHolder(itemLayout);
}
#Override
public void onBindViewHolder(PostRecycleViewAdapter.ViewHolder holder, int position) {
PostData data = postData.get(position);
holder.title.setText(data.getTitle());
holder.body.setText(data.getBody());
}
#Override
public int getItemCount() {
return postData.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);}
public void setClickListener(OnItemClick itemClick) {
this.itemClick = itemClick;
}
}
And this is the data item class:
package com.example.recyclerview;
public class PostData {
private String title, body;
private int id;
public PostData(int id, String title, String body)
{
this.id = id;
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getId() {
return id;
}
}
i want to use google api when i enter keyword it must give me city names with that keyword i want to use this by using StartActivityForResult()
here is my code i have reached so far: but i don't know what to do next, i have the api key and i have used the key in my manifest file i just want to complete the coding part!
case R.id.linearPlace:{ startActivityForResult(new Intent(this,Location.class),CITY);
}break;
}
}
public void onActivityResult(int requestcode,int resultcode,Intent intent ){
super.onActivityResult(requestcode,resultcode,intent);
String geoName = intent.getStringExtra("");
}
here i am putting my code for simple search address on edittext change event
Layout File : activity_demo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context="com.skandinaviske.elevkalender.DemoActivity">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/actLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Key word" />
<EditText
android:id="#+id/edtCountryCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Country Name" />
</LinearLayout>
<ListView
android:id="#+id/lstAddress"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linearLayout2"></ListView>
</RelativeLayout>
Class File : DemoActivity.java
package com.demo.pack;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class DemoActivity extends Activity {
private RequestQueue mRequestQueue;
private EditText actLocation;
public ArrayList<HashMap<String, String>> listofAddress;
private ListView lstAddress;
private EditText edtCountryCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
mRequestQueue = Volley.newRequestQueue(this);
actLocation = (EditText) findViewById(R.id.actLocation);
edtCountryCode = (EditText) findViewById(R.id.edtCountryCode);
lstAddress = (ListView) findViewById(R.id.lstAddress);
actLocation.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (actLocation.getText().toString().length() > 3) {
String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + actLocation.getText().toString().trim() + "%20" + edtCountryCode.getText().toString() + "&key=API_KEY&language=en_us";
fetchJsonResponse(url);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void fetchJsonResponse(String s) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(s, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//String result = "Your IP Address is " + response.getString("ip");
Log.d("response==>", response.toString());
calldisplayList(response);
//Toast.makeText(EditProfileActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage() + "");
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private void calldisplayList(JSONObject response) {
String city = "", state = "", country = "";
if (response != null) {
try {
if (response.getString("status").toString().equals("OK")) {
JSONArray adddressArray = response.getJSONArray("results");
if (adddressArray.length() != 0) {
if (listofAddress == null) {
listofAddress = new ArrayList<>();
}
listofAddress.clear();
for (int i = 0; i < adddressArray.length(); i++) {
JSONObject jsonObject = adddressArray.getJSONObject(i);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("address", jsonObject.getString("formatted_address").toString());
listofAddress.add(hashMap);
}
if (listofAddress.size() != 0 && actLocation.getText().length() != 0) {
AddressListAdapter addressListAdapter = new AddressListAdapter(DemoActivity.this, listofAddress);
lstAddress.setAdapter(addressListAdapter);
lstAddress.setVisibility(View.VISIBLE);
} else {
lstAddress.setVisibility(View.GONE);
}
} else {
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
}
public class AddressListAdapter extends BaseAdapter {
private final Activity context;
private final ArrayList<HashMap<String, String>> listOfAddress;
private class ViewHolder {
TextView txtAddress;
}
public AddressListAdapter(Activity context1, ArrayList<HashMap<String, String>> listOfAddress) {
this.context = context1;
this.listOfAddress = listOfAddress;
}
#Override
public int getCount() {
return listOfAddress.size();
}
#Override
public Object getItem(int position) {
return listOfAddress.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder viewHolder;
View converView = view;
if (converView == null) {
LayoutInflater infalInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
converView = infalInflater.inflate(R.layout.address_list_item, null);
viewHolder = new ViewHolder();
viewHolder.txtAddress = (TextView) converView.findViewById(R.id.txtAddress);
converView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) converView.getTag();
}
viewHolder.txtAddress.setText(listOfAddress.get(position).get("address") + "");
return converView;
}
}
}
Layout File for Adapter : address_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtAddress"
android:layout_width="match_parent"
android:background="#color/white"
android:textColor="#color/black"
android:text="temp data"
android:gravity="center_vertical"
android:layout_height="wrap_content"
android:padding="5dp" />
</LinearLayout>
Don't miss to put API_KEY (Hear is the url from where you can get API key : https://developers.google.com/maps/documentation/geocoding/get-api-key#get-an-api-key )
I'm making a parse json app and i've got an issue !
I've got these codes :
Temps.java :
package model;
public class Temps {
private String direction;
private String ligne;
private String temps;
public Temps() {
}
public Temps(String direction, String ligne, String temps) {
this.direction = direction;
this.ligne = ligne;
this.temps = temps;
}
public String getDirection() {
return direction;
}
public void setDirection(String thumbnailUrl) {
this.direction = thumbnailUrl;
}
public String getTemps() {
return temps;
}
public void setTemps(String temps) {
this.temps = temps;
}
public String getLigne() {
return ligne;
}
public void setLigne(String ligne) {
this.ligne = ligne;
}
}
TempsActivity.java :
package activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.pierre.tan.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import adapter.CustomListAdapterTemps;
import app.AppController;
import model.Temps;
public class TempsActivity extends ActionBarActivity {
private Toolbar mToolbar;
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private List<Temps> directionList = new ArrayList<Temps>();
private ListView listView2;
private CustomListAdapterTemps adapter;
private SwipeRefreshLayout swipeLayout;
private Menu menu;
private MenuInflater inflater;
HashMap<String, String> lieumap = new HashMap<String, String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_temps, container, false);
// Inflate the layout for this fragment
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
System.out.println(intent.getExtras().getString("text") + " Test Test ");
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(getParent(), directionList);
listView2.setAdapter(adapter);
// Showing progress dialog before making http request
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Toast.makeText(getApplication(), "Rechargement...", Toast.LENGTH_SHORT).show();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
swipeLayout.setRefreshing(false);
}
});
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_search) {
String title = getString(R.string.app_name);
Fragment fragment = null;
fragment = new ArretsFragment();
title = "Rechercher";
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temps);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(this, directionList);
listView2.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
}
And CustomListViewAdapterTemps.java :
package adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.example.pierre.tan.R;
import java.util.List;
import app.AppController;
import model.Temps;
public class CustomListAdapterTemps extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Temps> directionItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterTemps(Activity activity, List<Temps> directionItems) {
this.activity = activity;
this.directionItems = directionItems;
}
#Override
public int getCount() {
return directionItems.size();
}
#Override
public Object getItem(int location) {
return directionItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rowtemps, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView direction = (TextView) convertView.findViewById(R.id.direction);
TextView ligne = (TextView) convertView.findViewById(R.id.ligne);
TextView temps = (TextView) convertView.findViewById(R.id.temps);
// getting movie data for the row
Temps m = directionItems.get(position);
// title
direction.setText(m.getDirection());
ligne.setText(m.getLigne());
temps.setText(m.getTemps());
return convertView;
}
}
I don't understand why I get a Blank ListView because the url json work and in the console we can see just the json Request with the data. If someone can help me it would be very nice!
That's because your directionList is empty. In your loops, where you parse JSON, you're creating your Temps object:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
but you're not adding them to your directionsList. Add this line just after the above:
directionList.add(temps);
Hi i think that you are not adding your response to the list, please try this:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
directionList.add(temps);
//this is JOBListAdapter class
package com.example.hellotest.adapters;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.hellotest.R;
import com.example.hellotest.model.Job;
public class JobListAdapter extends BaseAdapter {
private LayoutInflater mInflater ;
private List<Job> mJobs;
private SimpleDateFormat mDateFormat;
private SimpleDateFormat mInputFormat;
private String mPosterPrefix;
public JobListAdapter(Context context) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
mInputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US);
mPosterPrefix = context.getString(R.string.job_posted_by);
}
public void setJobList(List<Job> jobs) {
mJobs = jobs;
}
#Override
public int getCount() {
if(null != mJobs) {
return mJobs.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return mJobs.get(position);
}
#Override
public long getItemId(int position) {
return mJobs.get(position).getId();
}
//this is the method where I think that the problem is please somebody tell me.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(null == convertView) {
convertView = mInflater.inflate(R.layout.job_list_row, null);
holder = new ViewHolder();
holder.created = (TextView) convertView.findViewById(R.id.job_listing_date);
holder.location = (TextView) convertView.findViewById(R.id.job_listing_location);
holder.title = (TextView) convertView.findViewById(R.id.job_listing_title);
holder.experience = (TextView) convertView.findViewById(R.id.job_listing_experience);
holder.poster = (TextView) convertView.findViewById(R.id.job_listing_posted_by);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
updateRow(holder, mJobs.get(position));
return convertView;
}
private void updateRow(ViewHolder holder, Job job) {
holder.title.setText(job.getTitle());
int id = job.isPremium() ? R.drawable.icon_premium : 0;
holder.created.setText(getDate(job.getCreated()));
holder.created.setCompoundDrawablesWithIntrinsicBounds(0, 0, id, 0);
holder.experience.setText(job.getExperience());
holder.location.setText(job.getLocation());
holder.poster.setText(mPosterPrefix + job.getPoster());
}
private CharSequence getDate(String created) {
try {
return mDateFormat.format(mInputFormat.parse(created));
} catch (ParseException e) {
e.printStackTrace();
}
return created;
}
private static class ViewHolder {
TextView created;
TextView title;
TextView location;
TextView experience;
TextView poster;
}
}
// layout for fragmentjob_listing even I make the listview height to fill_parent as suggested when I googled the solution for the issue.
<?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" >
<LinearLayout
android:id="#+id/job_listing_filter_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/job_listing_tab_bg"
android:gravity="center_vertical"
android:minHeight="48dp" >
<TextView
android:id="#+id/job_listing_experience"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/selector_job_listing_tab"
android:clickable="true"
android:gravity="center"
android:text="#string/job_listing_experience" />
<ImageView
android:id="#+id/space2"
android:layout_width="1dp"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/job_listing_horizontal_divider" />
<TextView
android:id="#+id/job_listing_location"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/selector_job_listing_tab"
android:clickable="true"
android:gravity="center"
android:text="#string/job_listing_location" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/job_listing_divider" />
<TextView
android:id="#+id/job_listing_message"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:visibility="gone"/>
<ListView
android:id="#+id/job_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
// JobListingFragment Class where the joblistAdapter class called up
package com.example.hellotest;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.example.hellotest.R;
import com.example.hellotest.adapters.JobListAdapter;
import com.example.hellotest.config.Constant;
import com.example.hellotest.io.CookieStringRequest;
import com.example.hellotest.io.json.JobsProcessor;
import com.example.hellotest.model.Job;
import com.example.hellotest.model.JobList;
import com.example.hellotest.model.Pagination;
import com.example.hellotest.tasks.JsonParserTask;
import com.example.hellotest.tasks.JsonParsingListener;
import com.example.hellotest.util.AccountUtils;
import com.example.hellotest.util.Log;
public class JobListingFragment extends Fragment {
public static final String ARG_URL = "argument_url";
public static final String ARG_IS_FILTER_ON = "argument_is_filtered";
public static final String ARG_IS_DEFAULT_JOB_LIST = "argument_is_default_job_list";
public static final String ARG_EMPTY_MESSAGE = "argument_empty_message";
protected static final int REQUEST_EXPERIENCE = 0x11;
protected static final int REQUEST_LOCATION = 0x12;
private ListView mJobsList;
private TextView mMessageView;
private JobListAdapter mAdapter;
private List<Job> mJobs;
private Pagination mPagination;
private boolean mIsFetching;
private boolean mIsDefaultList;
private boolean mIsFilterOn;
private String mUrl;
private String mLocId;
private int mExperienceId = -1;
private ProgressBar mFooterProgress;
private Log mLogger = new Log(JobListingFragment.class);
private Object mRequestTag = new Object();
private RequestQueue mRequestQueue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new JobListAdapter(getActivity());
if (null != savedInstanceState) {
getState(savedInstanceState);
} else {
getState(getArguments());
}
// init();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mRequestQueue = Volley.newRequestQueue(getActivity());
}
#Override
public void onDetach() {
mRequestQueue.cancelAll(mRequestTag);
super.onDetach();
}
#Override
public void onResume() {
init();
super.onResume();
}
private void getState(Bundle bundle) {
mUrl = bundle.getString(ARG_URL);
mIsFilterOn = bundle.getBoolean(ARG_IS_FILTER_ON);
mIsDefaultList = bundle.getBoolean(ARG_IS_DEFAULT_JOB_LIST);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_job_listing, null);
mJobsList = (ListView) view.findViewById(R.id.job_list);
mMessageView = (TextView) view.findViewById(R.id.job_listing_message);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
View footer = getLayoutInflater(savedInstanceState).inflate(R.layout.paginated_list_footer, null);
mFooterProgress = (ProgressBar) footer.findViewById(R.id.footer_progress);
if (!mIsFilterOn) {
view.findViewById(R.id.job_listing_filter_container).setVisibility(View.GONE);
} else {
view.findViewById(R.id.job_listing_experience).setOnClickListener(mOnClickListener);
view.findViewById(R.id.job_listing_location).setOnClickListener(mOnClickListener);
}
mJobsList.addFooterView(footer);
mJobsList.setAdapter(mAdapter);
mJobsList.setOnScrollListener(mOnScrollListener);
mJobsList.setOnItemClickListener(mOnItemClickListener);
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_URL, mUrl);
outState.putBoolean(ARG_IS_FILTER_ON, mIsFilterOn);
outState.putBoolean(ARG_IS_DEFAULT_JOB_LIST, mIsDefaultList);
super.onSaveInstanceState(outState);
}
public void startAfresh(String url, boolean isPaginated) {
mLogger.d("old fragment reused");
mIsFilterOn = true;
mUrl = url;
reset();
init();
}
private void init() {
mLocId = AccountUtils.getLocationFilter();
mExperienceId = AccountUtils.getExperienceFilter();
String url = getUrl(1);
fetchJobs(url);
}
private void reset() {
mJobs = null;
mPagination = null;
mAdapter.setJobList(null);
mAdapter.notifyDataSetChanged();
}
private String getUrl(int pageNumber) {
String appender = "";
if (mIsFilterOn) {
if (null != mLocId || -1 < mExperienceId) {
if (null != mLocId) {
appender += "/loc-" + mLocId;
} else {
appender += "/loc-" + 0;
}
if (-1 < mExperienceId) {
appender += "/exp-" + mExperienceId;
} else {
appender += "/exp-" + 0;
}
}
}
String url = mUrl + appender + "/pg-" + pageNumber;
if (mIsDefaultList && AccountUtils.isLoggedIn()) {
url += "?" + Constant.MAP_COOKIE_KEY + "=" + AccountUtils.getCookie();
}
return url;
}
private void fetchJobs(String url) {
mIsFetching = true;
mLogger.d("url :" + url);
int method = mIsDefaultList ? Method.GET : Method.POST;
CookieStringRequest request = new CookieStringRequest(method, url, mListener, mErrorListener);
request.setTag(mRequestTag);
mRequestQueue.add(request);
}
private Response.Listener<String> mListener = new Listener<String>() {
#Override
public void onResponse(String response) {
mLogger.d("response :" + response);
JsonParserTask<JobList> jsonTask = new JsonParserTask<JobList>(new JobsProcessor());
jsonTask.setListener(mJsonListener);
jsonTask.execute(response);
}
};
private Response.ErrorListener mErrorListener = new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mIsFetching = false;
Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_LONG).show();
}
};
private JsonParsingListener<JobList> mJsonListener = new JsonParsingListener<JobList>() {
#Override
public void onSuccess(JobList result) {
if (null == mPagination) {
mPagination = result.getPagination();
mPagination.setCurrentPage(0);
if(null == result.getJobs() || 0 == result.getJobs().size()) {
mMessageView.setText(getArguments().getString(ARG_EMPTY_MESSAGE));
mMessageView.setVisibility(View.VISIBLE);
} else {
mMessageView.setVisibility(View.GONE);
}
} else {
mPagination.updateData(result.getPagination());
}
if (null != mJobs) {
mJobs.addAll(result.getJobs());
} else {
mJobs = result.getJobs();
}
mAdapter.setJobList(mJobs);
mAdapter.notifyDataSetChanged();
mIsFetching = false;
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getActivity(), "Unable to process response", Toast.LENGTH_LONG).show();
mIsFetching = false;
}
};
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Job job = (Job) mAdapter.getItem(position);
Intent intent = new Intent(getActivity(), JobDetailsActivity.class);
intent.putExtra(JobDetailsActivity.EXTRA_JOB, job);
startActivity(intent);
}
};
// this is the function where I also found that might cause some problem because when I scrolls down the items in the list repeated.
private OnScrollListener mOnScrollListener = new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;
if (loadMore && totalItemCount > 0 && null != mPagination) {
boolean isLastPage = mPagination.getCurrentPage() >= mPagination.getTotalPages();
if (isLastPage) {
mFooterProgress.setVisibility(View.GONE);
}
if (!mIsFetching && !isLastPage) {
fetchJobs(getUrl(mPagination.getCurrentPage()+1));
}
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Activity.RESULT_OK == resultCode) {
switch (requestCode) {
case REQUEST_EXPERIENCE:
onExperienceSelection(data);
break;
case REQUEST_LOCATION:
onLocationSelection(data);
break;
}
}
}
add one more line in your function:
mjob.clear();
private JsonParsingListener<JobList> mJsonListener = new JsonParsingListener<JobList>() {
#Override
public void onSuccess(JobList result) {
if (null == mPagination) {
mPagination = result.getPagination();
mPagination.setCurrentPage(0);
if(null == result.getJobs() || 0 == result.getJobs().size()) {
mMessageView.setText(getArguments().getString(ARG_EMPTY_MESSAGE));
mMessageView.setVisibility(View.VISIBLE);
} else {
mMessageView.setVisibility(View.GONE);
}
} else {
mPagination.updateData(result.getPagination());
}
if (null != mJobs) {
mJobs.clear();
mJobs.addAll(result.getJobs());
} else {
mJobs = result.getJobs();
}
mAdapter.setJobList(mJobs);
mAdapter.notifyDataSetChanged();
mIsFetching = false;
}
I'm developing an app that grabs a list of clients of an API, and I need to show it in a listview, I'm using volley and what I tried to do is the following, but it's not working:
public ListView txtDisplay;
#Override
protected Boolean doInBackground(Void... params) {
try {
txtDisplay = (Listview) findViewById(R.id.listView);
String url = "http://192.168.1.1/rep-mais-api/api";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
})
The ActivityMain.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager" />
<TextView
android:id="#+id/txtDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true" android:layout_alignParentLeft="true"/>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Using this example, solved my case
import android.app.ProgressDialog;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends Activity {
private String TAG = this.getClass().getSimpleName();
private ListView lstView;
private RequestQueue mRequestQueue;
private ArrayList<NewsModel> arrNews ;
private LayoutInflater lf;
private VolleyAdapter va;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lf = LayoutInflater.from(this);
arrNews = new ArrayList<NewsModel>();
va = new VolleyAdapter();
lstView = (ListView) findViewById(R.id.listView);
lstView.setAdapter(va);
mRequestQueue = Volley.newRequestQueue(this);
String url = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json";
pd = ProgressDialog.show(this,"Please Wait...","Please Wait...");
try{
Thread.sleep(2000);
}catch(Exception e){
}
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
parseJSON(response);
va.notifyDataSetChanged();
pd.dismiss();
; }
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.getMessage());
}
});
mRequestQueue.add(jr);
}
private void parseJSON(JSONObject json){
try{
JSONObject value = json.getJSONObject("value");
JSONArray items = value.getJSONArray("items");
for(int i=0;i<items.length();i++){
JSONObject item = items.getJSONObject(i);
NewsModel nm = new NewsModel();
nm.setTitle(item.optString("title"));
nm.setDescription(item.optString("description"));
nm.setLink(item.optString("link"));
nm.setPubDate(item.optString("pubDate"));
arrNews.add(nm);
}
}
catch(Exception e){
e.printStackTrace();
}
}
class NewsModel{
private String title;
private String link;
private String description;
private String pubDate;
void setTitle(String title) {
this.title = title;
}
void setLink(String link) {
this.link = link;
}
void setDescription(String description) {
this.description = description;
}
void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
String getLink() {
return link;
}
String getDescription() {
return description;
}
String getPubDate() {
return pubDate;
}
String getTitle() {
return title;
}
}
class VolleyAdapter extends BaseAdapter{
#Override
public int getCount() {
return arrNews.size();
}
#Override
public Object getItem(int i) {
return arrNews.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh ;
if(view == null){
vh = new ViewHolder();
view = lf.inflate(R.layout.row_listview,null);
vh.tvTitle = (TextView) view.findViewById(R.id.txtTitle);
vh.tvDesc = (TextView) view.findViewById(R.id.txtDesc);
vh.tvDate = (TextView) view.findViewById(R.id.txtDate);
view.setTag(vh);
}
else{
vh = (ViewHolder) view.getTag();
}
NewsModel nm = arrNews.get(i);
vh.tvTitle.setText(nm.getTitle());
vh.tvDesc.setText(nm.getDescription());
vh.tvDate.setText(nm.getPubDate());
return view;
}
class ViewHolder{
TextView tvTitle;
TextView tvDesc;
TextView tvDate;
}
}
}
Source