Populate data into listview using json parsom with restful api - android

I have to run json format which is shown in below
and have to parse this data into listview
and for this i tried following code
MainActivity
swipeRefreshLayout.setOnRefreshListener(this);
// swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
}
);
notification_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String postloadid = actorsList.get(position).gettitle();
String source_addoc=actorsList.get(position).gettitle();
Constants.vCountry=actorsList.get(position).gettitle();
Toast.makeText(getApplicationContext(),"Selecting "+ Constants.vCountry+" State ", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void init()
{
norecord=(LinearLayout)findViewById(R.id.norecord);
notification_listview=(ListView)findViewById(R.id.listView_notification);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
}
#Override
public void onRefresh()
{
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
private static String pad(int c)
{
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
#Override
public void onResume()
{
super.onResume();
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
public void SyncMethod(final String GetUrl)
{
Log.i("Url.............", GetUrl);
final Thread background = new Thread(new Runnable() {
// After call for background.start this run method call
public void run() {
try {
String url = GetUrl;
String SetServerString = "";
// document all_stuff = null;
SetServerString = fetchResult(url);
threadMsg(SetServerString);
} catch (Throwable t) {
Log.e("Animation", "Thread exception " + t);
}
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler11.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler11.sendMessage(msgObj);
}
}
// Define the Handler that receives messages from the thread and update the progress
private final Handler handler11 = new Handler() {
public void handleMessage(Message msg) {
try {
String aResponse = msg.getData().getString("message");
Log.e("Exam", "screen>>" + aResponse);
swipeRefreshLayout.setRefreshing(false);
JSONObject jobj = new JSONObject(aResponse);
Log.e("Home Get draft--", jobj.toString());
String status = jobj.getString("status");
Log.e("Myorder Homestatusdraft",status);
Log.e("--------------------", "----------------------------------");
if (status.equalsIgnoreCase("true"))
{
actorsList = new ArrayList<Doctortype_method>();
JSONArray array = new JSONArray();
array = jobj.getJSONArray("response");
if(actorsList.size()>0){
actorsList.clear();
}
for(int i=0;i<array.length();i++)
{
JSONObject jsonChildNode = array.getJSONObject(i);
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new Doctortype_Adapter(getApplicationContext(),actorsList);
notification_listview.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
if(actorsList.size()==0)
{
norecord.setVisibility(View.VISIBLE);
}
}
else
{
swipeRefreshLayout.setRefreshing(false);
norecord.setVisibility(View.VISIBLE);
// UF.msg(message + "");
}
} catch (Exception e) {
}
}
};
});
// Start Thread
background.start();
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
}
For this i also add adapter as well as arraylist.
but when i run this application api is not called perfectly..
hope anyone a]can help me..
here i add adapter and arraylist
Adapter
public Doctortype_Adapter(Context context, ArrayList<Doctortype_method> objects) {
super(context, R.layout.list_doctortype, objects);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.list_doctortype, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (ViewHolder) rowView.getTag();
vh.title.setText(Html.fromHtml(actorList.get(position).gettitle()));
vh.subtitle.setText(Html.fromHtml(actorList.get(position).getsubtitle()));
/* String image=actorList.get(position).getid();
UrlImageViewHelper.setUrlDrawable(vh.dimage, image.toString(), R.drawable.no_img);*/
return rowView;
}
static class ViewHolder {
public TextView title, subtitle;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.title = (TextView) rowView.findViewById(R.id.tvProfileName);
vh.subtitle = (TextView) rowView.findViewById(R.id.tvDesc);
}
}
arraylist
public Doctortype_method( String title, String subtitle) {
super();
this.title = title;
this.subtitle = subtitle;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getsubtitle()
{
return subtitle;
}
public void setsubtitle(String subtitle) {
this.subtitle = subtitle;
}
there is no error but when i run this code api is not called and i didnt get the output i want.
Thnx in advance..

if (status.equalsIgnoreCase("true")) is wrong because you getting status:1 so it is if (status.equalsIgnoreCase("1")) try this and then change this array = jobj.getJSONArray("response"); to array = jobj.getJSONArray("data"); your JSONArray key is "data"
And replace this also
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
with
actorsList.add(new Doctortype_method(jsonChildNode.optString("countryID"),jsonChildNode.optString("vCountry")));
hope this helps. if this doesn't help feel free to ask
EDIT:
I cant understand what you want but have a look at this
-> you need to create baseAdapter for listview and set that adapter into the listview with your arraylist
FOR FETCHING YOUR ABOVE DATA YOU NEED TO DO BELOW CODE:
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject json1 = dataArray.getJSONObject(i);
String countryID = json1.getString("countryID");
String vCountry = json1.getString("vCountry");
}
} catch (JSONException e) {
e.printStackTrace();
}
Now if you want to show this vCountry in listview you have to add vCountry in ArrayList and then in listview.setAdapter you have to pass this ArrayList which is filled by vCountry. Hope you understand now. If you want adapter and listview code please check this link http://www.vogella.com/tutorials/AndroidListView/article.html

Finally i got the right answer.
May anyone get help from this in future.
ActivityClass.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list_item);
lv_city = (ListView)findViewById(R.id.listView_city);
Bundle b=getIntent().getExtras();
city_stateid = b.getString("stateid");
city_statename=b.getString("stateName");
city_countryid=b.getString("country");
lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
page_cityname = cityist.get(position).getCityName();
SharedPreferences sp=getSharedPreferences("abc",MODE_WORLD_WRITEABLE);
SharedPreferences.Editor edit=sp.edit();
edit.putString("city_name", page_cityname);
edit.commit();
Toast.makeText(getApplicationContext(),"Selected city & State"+page_cityname + "-" +city_statename, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), NextActivity.class);
/*i.putExtra("cityname", page_cityname);*/
startActivity(i);
}
});
}
#Override
public void onResume() {
super.onResume();
params12 = new ArrayList<NameValuePair>();
params12.add(new BasicNameValuePair("type", city_type));
params12.add(new BasicNameValuePair("stateID", city_stateid));
params12.add(new BasicNameValuePair("countryID", city_countryid));
new Sync().execute();
}
class Sync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
// obj=getJSONFromUrl("Your posting path", params11);
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/country-state-city", params12);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result of geting data", "" + result);
try {
Log.e("Exam", "screen>>" + result);
JSONObject get_res = new JSONObject(result);
String status = get_res.getString("status");
Log.e("Exam", "screen33333>>" + status);
if (status.equalsIgnoreCase("1")) {
cityist = new ArrayList<city_method>();
JSONArray array = new JSONArray();
array = get_res.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
cityist.add(new city_method(array.getJSONObject(i).getString("cityID"),array.getJSONObject(i).getString("cityName")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new city_Adapter(getApplicationContext(),cityist);
lv_city.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
} catch (Exception e) {
}
}
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Adapterclass.java
public class city_Adapter extends ArrayAdapter<city_method> {
ArrayList<city_method> citylist;
LayoutInflater vi;
Context context;
public city_Adapter(Context context, ArrayList<city_method> items) {
super(context, R.layout.list_doctortype, items);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.citylist = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
city_Adapter.ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.program_list, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (city_Adapter.ViewHolder) rowView.getTag();
vh.cityid.setText((citylist.get(position).getCityID()));
vh.cityname.setText((citylist.get(position).getCityName()));
return rowView;
}
static class ViewHolder {
private TextView cityid,cityname;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.cityid = (TextView) rowView.findViewById(R.id.cityid);
vh.cityname = (TextView) rowView.findViewById(R.id.cityname);
rowView.setTag(vh);
}
}
Methodclass.java
public class city_method {
private String cityID,cityName;
public String getCityID() {
return cityID;
}
public void setCityID(String cityID) {
this.cityID = cityID;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public city_method(String cityID, String cityName) {
this.cityID = cityID;
this.cityName = cityName;
}
}

Related

Why is it not showing all the data?

I am creating this app which shows the latest news, which gets data from
https://newsapi.org/s/india-health-news-api
but it doesn't fetch all the data. Sometimes it just shows all but sometimes it just shows 2 or 3 news. Also, I don't see any log error message. What is the problem?
HealthNews.java
public class HealthNews extends AppCompatActivity {
private ArrayList urlList;
private NewsAdapter mNewsAdapter;
private static final String REQUEST_URL ="https://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=3f7d99cdbb004766892bd239a4c099be";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_news);
Intent intent = getIntent();
HealthNews.NewsAsyncTask task = new HealthNews.NewsAsyncTask();
task.execute(REQUEST_URL);
urlList = QueryUtils.m;
ListView listView = (ListView)findViewById(R.id.listViewHealthNews);
mNewsAdapter = new NewsAdapter(this, new ArrayList<News>());
listView.setAdapter(mNewsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), ""+ a.get(position), Toast.LENGTH_SHORT).show();
Object url = urlList.get(position);
Uri uri = (Uri) Uri.parse((String) url); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
private class NewsAsyncTask extends AsyncTask<String, Void, ArrayList<News>> {
ProgressDialog p;
#Override
protected ArrayList<News> doInBackground(String... urls) {
if (urls.length < 1 || urls[0] == null) {
return null;
}
ArrayList<News> result = QueryUtils.fetchEarthquakeData(urls[0]);
return result;
//return null;
}
#Override
protected void onPostExecute(ArrayList<News> data) {
mNewsAdapter.clear();
if (data != null && !data.isEmpty()) {
p.hide();
mNewsAdapter.addAll(data);
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(HealthNews.this);
p.setMessage("Latest News...");
p.setIndeterminate(false);
p.show();
}
}
}
QueryUtils.java
private static final String LOG_TAG = "";
private QueryUtils(){
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(30000 /* milliseconds */);
urlConnection.setConnectTimeout(60000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
static ArrayList<String> m = new ArrayList<String>();
public static ArrayList<News> extractNews(String SAMPLE_JSON){
if (TextUtils.isEmpty(SAMPLE_JSON)) {
return null;
}
ArrayList<News> news = new ArrayList<News>();
try {
JSONObject jsonObject1 = new JSONObject(SAMPLE_JSON);
JSONArray baseJSONArray = jsonObject1.getJSONArray("articles");
for (int i = 0; i < baseJSONArray.length(); i++) {
JSONObject jsonObject = baseJSONArray.getJSONObject(i);
JSONObject source = jsonObject.getJSONObject("source");
String name = source.getString("name");
String article = jsonObject.getString("title");
String url1 = jsonObject.getString("url");
String img = jsonObject.getString("urlToImage");
URL url = new URL(img);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
News a = new News(image, article);
news.add(a);
m.add(url1);
}
} catch (JSONException j) {
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return news;
}
public static ArrayList<News> fetchEarthquakeData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
ArrayList<News> news = extractNews(jsonResponse);
return news;
}
I went though your code and found some issues.
Some bad practices i found in your code are:
You are adding your urls in separate list with static specifier. Instead of this you should add the url variable in your News model directly. And you can directly retrieve the whole News model inside ListView > setOnItemClickListener.
You are creating Bitmap for all your images. It may cause OOM Exception. You should use any Image loading library instead.
I have fixed that all issues and created working code. Please do required changes which you want at your end.
HealthNews.java
public class HealthNews extends AppCompatActivity {
private Context context;
private NewsAdapter mNewsAdapter;
private ArrayList<News> listNews;
private static final String REQUEST_URL = "https://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=3f7d99cdbb004766892bd239a4c099be";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.health_news);
context = this;
ListView list_news = findViewById(R.id.list_news);
listNews = new ArrayList<>();
mNewsAdapter = new NewsAdapter(context, listNews);
list_news.setAdapter(mNewsAdapter);
list_news.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
News selNews = (News) parent.getAdapter().getItem(position);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(selNews.getUrl())));
} catch (Exception e) {
// Missing 'http://' or 'https://' will cause crash
e.printStackTrace();
}
}
});
new NewsAsyncTask().execute(REQUEST_URL);
}
private class NewsAsyncTask extends AsyncTask<String, Void, ArrayList<News>> {
private ProgressDialog p;
#Override
public void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(context);
p.setMessage("Latest News...");
p.setIndeterminate(false);
p.show();
}
#Override
public ArrayList<News> doInBackground(String... urls) {
return QueryUtils.fetchEarthquakeData(urls[0]);
}
#Override
public void onPostExecute(ArrayList<News> newsList) {
super.onPostExecute(newsList);
listNews.addAll(newsList);
p.hide();
mNewsAdapter.notifyDataSetChanged();
}
}
}
QueryUtils.java
public class QueryUtils {
public static ArrayList<News> fetchEarthquakeData(String apiUrl) {
ArrayList<News> listNews = new ArrayList<>();
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(30000);
conn.setConnectTimeout(60000);
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
InputStream iStream;
if (responseCode == HttpURLConnection.HTTP_OK)
iStream = conn.getInputStream();
else
iStream = conn.getErrorStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
String jsonResponse = response.toString();
if (TextUtils.isEmpty(jsonResponse))
return null;
JSONObject jsonObject1 = new JSONObject(jsonResponse);
JSONArray baseJSONArray = jsonObject1.getJSONArray("articles");
for (int i = 0; i < baseJSONArray.length(); i++) {
JSONObject jsonObject = baseJSONArray.getJSONObject(i);
JSONObject source = jsonObject.getJSONObject("source");
News news = new News();
news.setArticle(jsonObject.optString("title"));
news.setUrl(jsonObject.optString("url"));
news.setUrlToImage(jsonObject.optString("urlToImage"));
listNews.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return listNews;
}
}
News.java (Model)
public class News {
private String article;
private String url;
private String urlToImage;
public News() {
this.article = "";
this.url = "";
this.urlToImage = "";
}
public String getArticle() {
return article;
}
public void setArticle(String article) {
this.article = article;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
}
NewsAdapter.java (Change your item layout as per your code)
public class NewsAdapter extends BaseAdapter {
private Context context;
private LayoutInflater mInflater;
private List<News> listNews;
public NewsAdapter(Context context, List<News> listNews) {
this.context = context;
this.listNews = listNews;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listNews.size();
}
#Override
public News getItem(int position) {
return listNews.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private ImageView item_img_news;
private TextView item_txt_article;
}
#SuppressLint("InflateParams")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_news, null);
holder = new ViewHolder();
holder.item_img_news = convertView.findViewById(R.id.item_img_news);
holder.item_txt_article = convertView.findViewById(R.id.item_txt_article);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final News news = getItem(position);
holder.item_txt_article.setText(news.getArticle());
Glide.with(context).load(news.getUrlToImage()).into(holder.item_img_news);
return convertView;
}
}
app > build.gradle
implementation 'com.github.bumptech.glide:glide:4.9.0'

unable set list row status in a variable

I am very new in android.I my app I retrieve data from mysql database to list view. In my database table has a status column I also retrieve that value but I can not save into a variable. my concept to save status is if status value=0 a green image show side of that row.when status value change that colour will change.
Data Retrieve class
private class bookingList extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
#Override
protected void onPreExecute() {
findViewById(R.id.clientloadingPanel).setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.mybusket.com/webapi/carrental/booking/get_client_bookings.php?vclientid="+Clientid; //this clientid comes from global variable class
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpGet.setURI(new URI(url_select));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
try {
lv5 = (ListView)findViewById(R.id.lv5);
lv5.setAdapter(customClientBookingList);
JSONObject object = new JSONObject(result);
JSONArray jsonArray = object.getJSONArray("booking");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
Log.d("data",""+obj);
ClientBookingData clientBookingData = new ClientBookingData();
clientBookingData.setBdate(obj.getString("bdate"));
clientBookingData.setBrand(obj.getString("brand"));
clientBookingData.setCarno(obj.getString("carno"));
clientBookingData.setBfees(obj.getString("bfees"));
clientBookingData.setAdvance(obj.getString("advance"));
clientBookingData.setDue(obj.getString("due"));
clientBookingData.setBookingid(obj.getInt("bookingid"));
clientBookingData.setStatus(obj.getInt("status"));
clientBookingLists.add(clientBookingData);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
findViewById(R.id.clientloadingPanel).setVisibility(View.GONE);
}
}
Data set Class
private int bookingid,status;
private String bdate,carno,brand,bfees,advance,due;
public ClientBookingData(){}
public int getBookingid() {
return bookingid;
}
public void setBookingid(int bookingid) {
this.bookingid = bookingid;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getBdate() {
return bdate;
}
public void setBdate(String bdate) {
this.bdate = bdate;
}
public String getCarno() {
return carno;
}
public void setCarno(String carno) {
this.carno = carno;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getBfees() {
return bfees;
}
public void setBfees(String bfees) {
this.bfees = bfees;
}
public String getAdvance() {
return advance;
}
public void setAdvance(String advance) {
this.advance = advance;
}
public String getDue() {
return due;
}
public void setDue(String due) {
this.due = due;
}
public ClientBookingData(int bookingid, int status, String bdate, String carno, String brand, String bfees, String advance, String due) {
this.bookingid = bookingid;
this.status = status;
this.bdate = bdate;
this.carno = carno;
this.brand = brand;
this.bfees = bfees;
this.advance = advance;
this.due = due;
}
Adapter class
private Activity activity;
private LayoutInflater inflater;
private List<ClientBookingData> Items;
public CustomClientBookingList(){}
public CustomClientBookingList(Activity activity, List<ClientBookingData> Items) {
this.activity = activity;
this.Items = Items;
}
#Override
public int getCount() {
return Items.size();
}
#Override
public Object getItem(int location) {
return Items.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_custom_client_booking_list, null,true);
TextView bdate = (TextView)convertView.findViewById(R.id.bdate);
TextView brand = (TextView)convertView.findViewById(R.id.brand);
TextView carno = (TextView)convertView.findViewById(R.id.carno);
TextView advance = (TextView)convertView.findViewById(R.id.advance);
TextView due = (TextView)convertView.findViewById(R.id.due);
TextView bfees = (TextView)convertView.findViewById(R.id.bfees);
// getting data for the row
ClientBookingData m = Items.get(position);
// set data
bdate.setText(m.getBdate());
brand.setText(m.getBrand());
carno.setText(m.getCarno());
advance.setText(m.getAdvance());
due.setText(m.getDue());
bfees.setText(m.getBfees());
return convertView;
}
Right side of each row have a image view with different colour. According to status value colour show.please help me.
You can simply do it like below
inside your getView()
ClientBookingData m = Items.get(position);
if(m.getStatus()==0)
//Your code to set Image Background
else
//Your code to set Image Background

Call BaseAdapter In Fragment Close Application

Call BaseAdapter In Fragment Close Application
Comment in line spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
Work
Error Log
Class FragmentNews
public class FragmentNews extends Fragment {
ArrayList<Category> categorylist = new ArrayList<Category>();
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
return rootView;
}
class fechPosts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
ringProgressDialog = new ProgressDialog(getActivity());
ringProgressDialog.setMessage("در حال ارسال پیام");
ringProgressDialog.setCancelable(true);
ringProgressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = fetch(params[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Activity myActivity = getActivity();
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
ringProgressDialog.dismiss();
}
}
public String fetch(String titel) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = null;
httppost = new HttpGet(
"http://mynikan.ir/paliz/mobile/GetAllProduct.php");
String r = "ok";
String result = null;
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONArray array = null;
try {
array = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject json_data;
try {
json_data = array.getJSONObject(i);
Category obj = new Category();
obj.Image = json_data.getString("Product_Image");
obj.Title = json_data.getString("Price");
categorylist.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return r;
}
Class Adapter
public class Category_Adapter extends BaseAdapter {
public String[] items;
public LayoutInflater myinflater;
Context context;
static class ViewHolder
{
TextView text;
TextView price;
ImageView im;
}
public int[] picmenu;
ArrayList<Category> categorylist = new ArrayList<Category>();
public Category_Adapter(Context c, ArrayList<Category> pthemop) {
myinflater = LayoutInflater.from(c);
context = c;
categorylist = pthemop;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return categorylist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
// /////
if (convertView == null) {
convertView = myinflater.inflate(R.layout.snipper_single, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.im = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(categorylist.get(position).Title);
Picasso.with(context).load(categorylist.get(position).Image)
.into(holder.im);
return convertView;
}}
Class Category
public class Category {
String Title;
String Image;
}
Here:
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
line causing issue because spinner object of Spinner is null.
In onCreateView method creating new object instead of initializing object which is using in spinner.
Change onCreateView method as:
spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");

How to list mssql records in onPostExecute using custom arrayAdapter. I wrote the following codes, but when I execute the app is stopped

I want to list my mssql records in android listview. Here is my codes;
activity;
public class YoneticiMenuActivity extends Activity {
JSONObject jsonObject = null;
//JSONArray jsonArray = null;
//public Is isler = new Is();
//public ArrayList<Is> arrayIsler = new ArrayList<Is>();
ListView lvTumIsler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yonetici_menu);
Intent iAl = getIntent();
String mesaj = iAl.getStringExtra(LoginActivity.m);
int mode = Activity.MODE_PRIVATE;
SharedPreferences mSP;
mSP = getSharedPreferences(mesaj, mode);
String baslik = mSP.getString("name", "") + " " + mSP.getString("surname", "") + ", Hoşgeldiniz";
setTitle(baslik);
lvTumIsler = (ListView)findViewById(R.id.lvTumIsler);
new AsyncTaskYonetici("Veriler yükleniyor...").execute();
}
private class AsyncTaskYonetici extends AsyncTask<Void, Void, Void> {
String modalMesaj;
ProgressDialog dialog;
JSONArray jsonArray = null;
JSONObject jsonObject = null;
public Is isler = new Is();
public ArrayList<Is> arrayIsler = new ArrayList<Is>();
//private ListView lvTumIsler;
public AsyncTaskYonetici(String mMesaj) {
this.modalMesaj = mMesaj;
this.dialog = new ProgressDialog(YoneticiMenuActivity.this);
}
#Override
protected void onPreExecute() {
dialog.setMessage(modalMesaj);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://www.saklambacjeans.com/skbos/webServiceTumIsler.aspx";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
String line = null;
try {
if ((line = reader.readLine()) != null) {
jsonArray = new JSONArray(line);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (ClientProtocolException e) {
Mesaj(e.getMessage());
} catch (IOException e) {
Mesaj(e.getMessage());
} /*catch (JSONException e) {
Mesaj(e.getMessage());
}*/
return null;
}
#Override
protected void onPostExecute(Void str) {
try {
for (int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
isler.setP(Integer.parseInt(jsonObject.getString("urunId").toString()),
Integer.parseInt(jsonObject.getString("modelNo").toString()),
jsonObject.getString("modelAd").toString(),
jsonObject.getString("bedenAd").toString(),
Integer.parseInt(jsonObject.getString("adet").toString()),
jsonObject.getString("aciklama").toString(),
jsonObject.getString("kesmeTalimat").toString(),
jsonObject.getString("atolyeTalimat").toString(),
jsonObject.getString("yıkamaTalimat").toString(),
jsonObject.getString("utuTalimat").toString(),
jsonObject.getString("kesimci").toString(),
jsonObject.getString("atolyeci").toString(),
jsonObject.getString("yıkamacı").toString(),
jsonObject.getString("utucu").toString(), jsonObject.getString("kontrolcu").toString());
arrayIsler.add(isler);
}
} catch (JSONException e) {
e.printStackTrace();
}
IsAdapter adapter = new IsAdapter(YoneticiMenuActivity.this, R.layout.layouttumisler, arrayIsler);
lvTumIsler.setAdapter(adapter);
if (dialog.isShowing())
dialog.dismiss();
}
}
private void Mesaj(String s) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
my adapter;
public class IsAdapter extends ArrayAdapter<Is> {
private ArrayList<Is> arrayIsler;
Context context;
public IsAdapter(Context context, int layoutResourceId, ArrayList<Is> a) {
super(context, layoutResourceId, a);
this.arrayIsler = a;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.layouttumisler, null);
}
Is is = arrayIsler.get(position);
if (is != null) {
TextView tvId = (TextView) row.findViewById(R.id.tvId);
TextView tvModel = (TextView) row.findViewById(R.id.tvModel);
TextView tvAtolye = (TextView) row.findViewById(R.id.tvAtolye);
TextView tvUrunId = (TextView) row.findViewById(R.id.tvUrunId);
TextView tvUrunModel = (TextView) row.findViewById(R.id.tvUrunModel);
TextView tvUrunAtolye = (TextView) row.findViewById(R.id.tvUrunAtolye);
if (tvId != null){
tvId.setText("Ürün No: ");
}
if (tvUrunId != null){
tvUrunId.setText(is.getId());
}
if (tvModel != null){
tvModel.setText("Model: ");
}
if (tvUrunModel != null){
tvUrunModel.setText(is.getModel());
}
if (tvAtolye != null){
tvAtolye.setText("Atolye: ");
}
if (tvUrunAtolye != null){
tvUrunAtolye.setText(is.getAtolye());
}
}
return row;
}
}
my Is class;
public class Is {
public int urunId;
public int modelNo;
public String modelAd;
public String bedenAd;
public int adet;
public String aciklama;
public String kesmeTalimat;
public String atolyeTalimat;
public String yikamaTalimat;
public String utuTalimat;
public String kesimci;
public String atolyeci;
public String yikamaci;
public String utucu;
public String kontrolcu;
public int getId() {return urunId;}
public String getModel() {return modelAd;}
public String getAtolye() {return atolyeci;}
public void setP(int u, int mN, String mA, String bA, int a, String ac, String kT, String aT, String yT, String uT,
String k, String at, String y, String utu, String ko)
{
urunId = u;
modelNo = mN;
modelAd = mA;
bedenAd = bA;
adet = a;
aciklama = ac;
kesmeTalimat = kT;
atolyeTalimat = aT;
yikamaTalimat = yT;
utuTalimat = uT;
kesimci = k;
atolyeci = at;
yikamaci = y;
utucu = utu;
kontrolcu = ko;
}
}
I use listview in main layout and there is 6 textview in layouttumısler. I use IsAdapter in onPostExecute in myAsyncTask but when I execute the app it is stopped.
The mssql records come from web service truely, But I can not list. I take error in IsAdapter getView, in
tvUrunId.setText(is.getId());
please help me...
I made a bad mistake, when I change
public int getId() {return urunId;}
as
public String getId()
{
String s = Integer.toString(urunId);
return s;
}
the code works.

Show data on Listview is duplication

I'm doing a app can update data every 1 minutes, data will from database mysql on server to show on listview of my app android. My problem is when show data the first is ok but when show data the second on listview, data of the first and the second is duplication.Can you help me!
Source code:
public class Hoadon extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<String> al3 = new ArrayList<String>();
ArrayList<String> al1a = new ArrayList<String>();
String date;
String name;
String address;
String url;
String code;
int responseCode;
private String IDinvoice;
private TimerTask mTimerTask;
private Timer t=new Timer();
private final Handler handler=new Handler();
private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hoadon);
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
try {
URL url = new URL("http://longvansolution.tk/monthlytarget.php");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
responseCode = httpConnection.getResponseCode();
} catch (Exception e) {
}
try {
if (isNetworkAvailable() == true
//&& responseCode == HttpURLConnection.HTTP_OK
) {
//new LoadData().execute();
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
doTimerTask();
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("No Internet Connection available!!!");
ad.show();
}
} catch (Exception e) {
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
IDinvoice = extras.getString("IDinvoice");
}
}
public void doTimerTask(){
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
new LoadData().execute();
Log.d("TIMER", "TimerTask run");
}
});
}};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask, 500, 10000); //
}
#Override
public void onBackPressed() {
//do something with bitmap
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(
Hoadon.this, "", " Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try {
listview = (ListView) findViewById(R.id.listView1);
this.progressDialog.dismiss();
listview.setAdapter(new DataAdapter(Hoadon.this,
al.toArray(new String[al.size()]), al1a
.toArray(new String[al1a.size()]), al1
.toArray(new String[al1.size()]), al2
.toArray(new String[al2.size()])));
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String t = al3.get(position);
Intent i = new Intent(Hoadon.this,
Signature.class);
i.putExtra("url", t);
startActivity(i);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://longvansolution.tk/monthlytarget.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
// buffered reader
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
// Log.i("net status:", "Online...!!!");
return true;
}
// Log.i("net status:", "offline...!!!");
return false;
}
}
Source DataAdapter
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String[] date;
String[] code;
String[] address;
String[] name;
public DataAdapter(Context c, String[] date,String[] code, String[] name, String[] address) {
this.date = date;
this.code=code;
this.name = name;
this.address = address;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public void clearData() {
// clear the data
Arrays.fill(date, null);
Arrays.fill(code, null);
Arrays.fill(address, null);
Arrays.fill(name, null);
}
public int getCount() {
return date.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customgrid, parent, false);
holder = new ViewHolder();
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.code=(TextView)convertView.findViewById(R.id.mahd);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.address = (TextView) convertView.findViewById(R.id.address);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.date.setText(date[position]);
holder.code.setText(code[position]);
holder.name.setText(name[position]);
holder.address.setText(address[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView date,code;
TextView name, address;
}
}
you should clear your arralist every LoadData task.
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}

Categories

Resources