I am developing app just like YOUTUBE. I am getting data from the server and showing it in listview. Because data is too big so i want to restrict list view to 5 items and then when I scroll down to the bottom of listview it should add 5 more item.
I am calling ASyncTask from fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(R.layout.tab_fragment_2, container, false);
listView = (ListView) view.findViewById(R.id.myList);
New.jsonAsyncTask.execute("my url select_video.php?");
}
Now I have separate JsonAsyncTask Class because I am calling it from 3 fragments just like above mentioned way..
public class JSONAsyncTask extends AsyncTask<String, String, List<SetDatails>> {
ListView listView1;
Context context1;
List<SetDatails> videoLiast1;
private static int tab_id;
public JSONAsyncTask(ListView listView, List<SetDatails> videoLiast,Context context,int id) {
this.listView1 = listView;
this.context1 = context;
this.videoLiast1 = videoLiast;
tab_id=id;
}
#Override
protected List<SetDatails> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader myReader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream myInputStream = connection.getInputStream();
myReader = new BufferedReader(new InputStreamReader(myInputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = myReader.readLine()) != null) {
buffer.append(line);
}
String Json_data = buffer.toString();
videoLiast1 = new ArrayList<>();
JSONObject parentObj = new JSONObject(Json_data);
JSONArray dataArray = parentObj.getJSONArray("data");
JSONObject tabObject = dataArray.getJSONObject(tab_id);
JSONArray videoArray = tabObject.getJSONArray("videos");
for (int i = 0; i < videoArray.length(); i++) {
int len=dataArray.length();
SetDatails setDatails = new SetDatails();
JSONObject arrayChild = videoArray.getJSONObject(i);
String vid_ID = arrayChild.getString("id");
setDatails.setVidID(vid_ID);
String movie_title = arrayChild.getString("name");
setDatails.setTitle(movie_title);
String movie_catagory = arrayChild.getString("category_name");
setDatails.setGenre(movie_catagory);
videoLiast1.add(setDatails);
}
return videoLiast1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (myReader != null) {
myReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(List<SetDatails> videoList) {
super.onPostExecute(videoList);
if(videoList!=null) {
try {
MyListAdapter myListAdapter = new MyListAdapter(context1, videoList);
listView1.setAdapter(myListAdapter);
}catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
I have created an Array adapter to fill list view.
public class MyListAdapter extends ArrayAdapter<SetDatails>{
public static int count =5;
List<SetDatails> videoList;
MyListAdapter(Context context,List<SetDatails> object){
super(context,R.layout.tab2_bookchilds,object);
videoList = object;
}
/**
* {#inheritDoc}
*/
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater=LayoutInflater.from(getContext());
View view = layoutInflater.inflate(R.layout.tab2_bookchilds, parent, false);
TextView title = (TextView)view.findViewById(R.id.txt_title);
title.setText(videoList.get(position).getTitle());
ImageView imgV_Thumbnail = (ImageView) view.findViewById(R.id.imgV_thumbnail);
Picasso.with(getContext())
.load(videoList.get(position).getThumbnail())
.error(R.drawable.icon_white)
.into(imgV_Thumbnail);
return view;
}
}
I have searched a lot and many people suggest getCount() method although I tried a lot to use this method but don't know how to do that.
Please guys help me because my app is ready to upload but I can't solve this one issue.
Related
OnPost Execute method how can I pass image from one Fragment to other activity. Able to pass the image from drawable folder using Bundle. Loding product details from server and able to other information except Image to other Activity.
package sanjay.apackage.torcente.com.torcentemotors;
public class HomeFragment extends Fragment {
FragmentTransaction fragmentTransaction;
//private TextView tvData;
private ListView lvMovies;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
//Image loader
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()) //getApplicationContext()
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvMovies = (ListView)view.findViewById(R.id.lvMovies);
new JSONTask().execute("http://torcentemotors.com/app_001/productsInfoNew.php");
return view;
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel> > {
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null ) {
buffer.append(line);
}
//return buffer.toString();
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
for(int i = 0; i< parentArray.length() ;i++ ) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setProduct_name(finalObject.getString("product_name"));
movieModel.setProduct_price(finalObject.getInt("product_price"));
movieModel.setProduct_image(finalObject.getString("product_image"));
movieModel.setProduct_color(finalObject.getString("product_color"));
movieModel.setCover_image(finalObject.getString("cover_image"));
movieModel.setOriginal_price(finalObject.getInt("original_price"));
movieModel.setApp_desc(finalObject.getString("app_desc"));
//adding the final object to the list
movieModelList.add(movieModel);
}
//return finalBufferedData.toString();
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if( connection != null){
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
final MovieAdapter adapter = new MovieAdapter( getActivity().getApplicationContext(), R.layout.rownew, result );
//// getApplicationContext() // getActivity is added by me
lvMovies.setAdapter(adapter);
//set data to list
lvMovies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getActivity().getBaseContext(),parent.getItemIdAtPosition(position)+" is selected",Toast.LENGTH_LONG).show();
MovieModel movieModel = (MovieModel) adapter.getItem(position);
Intent intent = new Intent("sanjay.apackage.torcente.com.torcentemotors.product_details");
//intent.putExtra("product_image", movieModel.getProduct_image());
//sanjay //
intent.putExtra("id",position);
intent.putExtra("product_name",movieModel.getProduct_name());
intent.putExtra("product_price", movieModel.getProduct_price());
intent.putExtra("product_color", movieModel.getProduct_color());
intent.putExtra("original_price", movieModel.getOriginal_price());
intent.putExtra("app_desc", movieModel.getApp_desc());
Bundle bundle=new Bundle();
bundle.putInt("image",R.drawable.ban);
bundle.putInt("image2",R.drawable.fz25);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
public class MovieAdapter extends ArrayAdapter{
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater ;
public MovieAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource ;
inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE); // context is added by me.
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
viewHolder holder = null;
if (convertView == null ) {
holder = new viewHolder();
convertView = inflater.inflate(resource, null);
holder.tvIcon = (ImageView)convertView.findViewById(R.id.tvIcon);
holder.tvcover = (ImageView)convertView.findViewById(R.id.tvcover);
holder.tvproduct_name = (TextView)convertView.findViewById((R.id.tvproduct_name));
holder.tvproduct_price = (TextView)convertView.findViewById((R.id.tvproduct_price));
holder.tvproduct_color = (TextView)convertView.findViewById((R.id.tvproduct_color));
holder.tvoriginal_price = (TextView)convertView.findViewById((R.id.tvoriginal_price));
holder.tvapp_desc = (TextView)convertView.findViewById((R.id.tvapp_desc));
convertView.setTag(holder);
} else{
holder = (viewHolder)convertView.getTag();
}
ImageLoader.getInstance().displayImage(movieModelList.get(position).getProduct_image(), holder.tvIcon);
ImageLoader.getInstance().displayImage(movieModelList.get(position).getCover_image(), holder.tvcover);
//holder.tvproduct_id.setText(" Product ID : " +movieModelList.get( position ).getProduct_id());
//holder.tvcategory_id.setText("Category ID : " +movieModelList.get(position).getCategory_id());
//holder.tvsub_category_id.setText("Sub Category ID : " +movieModelList.get(position).getSub_category_id());
holder.tvproduct_name.setText(movieModelList.get(position).getProduct_name());
//holder.tvproduct_code.setText(movieModelList.get(position).getProduct_code());
holder.tvproduct_price.setText("BookingPrice : "+movieModelList.get(position).getProduct_price());
holder.tvproduct_color.setText(movieModelList.get(position).getProduct_color());
holder.tvoriginal_price.setText("Price : "+movieModelList.get(position).getOriginal_price());
//holder.tvapp_desc.setText(movieModelList.get(position).getApp_desc());
return convertView;
}
class viewHolder{
private ImageView tvIcon ;
private ImageView tvcover ;
private TextView tvproduct_id;
private TextView tvcategory_id;
private TextView tvsub_category_id;
private TextView tvproduct_name;
private TextView tvproduct_code;
private TextView tvproduct_color;
private TextView tvproduct_price;
private TextView tvoriginal_price;
private TextView tvapp_desc;
}
}
}
I've used a ListView to show my data from wamp server using mysql, also using JSON parsing , the following is my code....
public class JSONTask extends AsyncTask<String, String, List<PumpModel>> {
#Override
protected List<PumpModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("server_response");
List<PumpModel> pumpModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
PumpModel pumpModel = new PumpModel();
pumpModel.setPump(finalObject.getString("Pump"));
pumpModel.setAvailable(finalObject.getString("Available"));
pumpModelList.add(pumpModel);
}
return pumpModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<PumpModel> result) {
super.onPostExecute(result);
//TODO need to set the data to the list
PumpAdapter adapter = new PumpAdapter(getApplicationContext(), R.layout.row, result);
lvPump.setAdapter(adapter);
}
}
public class PumpAdapter extends ArrayAdapter {
private List<PumpModel> pumpModelList;
private int resource;
private LayoutInflater inflater;
public PumpAdapter(Context context, int resource, List<PumpModel> objects) {
super(context, resource, objects);
pumpModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
ImageView ivIcon;
TextView tvPump;
ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
tvPump = (TextView) convertView.findViewById(R.id.tvPump);
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(pumpModelList.get(position).getAvailable(), ivIcon); // Default options will be used
tvPump.setText(pumpModelList.get(position).getPump());
return convertView;
}
}
Now I want to create an onclick listener for my list view, which can be used to open another activity, and show the Description of pumps in TextView.
In your activity, where you defined your listview
you can write
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
public ItemClicked getItem(int position){
return items.get(position);
}
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
In your activity, where you defined your listview
you write
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
in your adapter's getItem you write
public ItemClicked getItem(int position){
return items.get(position);
}
Implement an OnItemClickListener (Best place to implement is in your adapter) & on your ListView object setOnItemClickListener(yourItemClickListener);
Refs :
https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
https://developer.android.com/reference/android/widget/AdapterView.html#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)
I am trying to fetch data using AsyncTask & displaying into a ListView. It never calls getView(), I checked getCount() return always 0.
MainActivityFragment.java
public class MainActivityFragment extends Fragment {
private final String LOG_TAG = MainActivityFragment.class.getSimpleName();
SourceAdapter adapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
adapter = new SourceAdapter(getActivity());
ListView listView = (ListView) rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);
Log.d(LOG_TAG,"after list view set to adapter");
return rootView;
}
#Override
public void onStart() {
new FetchDataTask().execute();
super.onStart();
}
public class FetchDataTask extends AsyncTask<String, Void, SourceObject[]>{
private final String LOG_TAG = FetchDataTask.class.getSimpleName();
private SourceObject[] getSourceDataFromJson(String jsonStr)throws JSONException{
JSONArray jsonArray = new JSONArray(jsonStr);
SourceObject[] sourceObjects = new SourceObject[jsonArray.length()];
for (int i=0; i<jsonArray.length();i++){
sourceObjects[i] = new SourceObject(
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getString("message")
);
}
return sourceObjects;
}
#Override
protected SourceObject[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonStr = null;
try {
String baseUrl = "https://api.github.com/repos/rails/rails/commits";
URL url = new URL(baseUrl);
Log.d(LOG_TAG,"URL IS "+url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
jsonStr = buffer.toString();
Log.d(LOG_TAG,"JSON STRING "+jsonStr);
}catch (IOException e){
Log.e(LOG_TAG, "ERROR"+e);
return null;
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getSourceDataFromJson(jsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.notifyDataSetChanged();
super.onPostExecute(strings);
}
}
}
SourceAdapter.java
public class SourceAdapter extends BaseAdapter {
private final String LOG_TAG = SourceAdapter.class.getSimpleName();
Context context;
ArrayList<SourceObject> objects = new ArrayList<SourceObject>();
public SourceAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
Log.d(LOG_TAG,"getCount called "+objects.size());
return objects.size();
}
#Override
public Object getItem(int position) {
Log.d(LOG_TAG,"getItem called");
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(LOG_TAG,"get view method is called");
SourceObject sourceObject = (SourceObject) getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_source,parent,false);
}
TextView personName = (TextView) convertView.findViewById(R.id.person_name);
TextView commit = (TextView) convertView.findViewById(R.id.xxx);
TextView commitMessage = (TextView) convertView.findViewById(R.id.commit_message);
personName.setText(sourceObject.getPersonName());
commit.setText(sourceObject.getCommit());
commitMessage.setText(sourceObject.getCommitMessage());
return convertView;
}
}
Please help.
You are not setting data retrieved from AsyncTask to adapter.
Add this method to your adapter class:
public void setItems(SourceObject[] items) {
this.objects = new ArrayList<SourceObject>();
for(SourceObject item : items){
this.objects.add(item);
}
this.notifyDataSetChanged();
}
And change onPostExecute of AsyncTask to:
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.setItems(strings);
super.onPostExecute(strings);
}
I am working on an app which performs (in an AsyncTask) a query to a remote server obtaining a JSON string.
To show the data on my ListView i have extended an ArrayAdapter.
When i execute my app, from the LogCat i can see that data is retrieved correctly but not shown in the ListView.
The only way i have to make everything work (and data be shown on the ListView) is by running the app in Debug mode, set a breakpoint on the line
myListView.setAdapter(myAdapter);
wait for a couple seconds and then resume the application.
After this procedure, everything works correctly.
Why is this happening?
Is the AsyncTask the right way for such a long operation, or should I use some other approach (but i don't know which one!).
Here is the MainActivity code
public class MainActivityFragment extends Fragment {
private List<Station> stationList = new ArrayList<Station>();
private StationAdapter stationsAdapter;
private ProgressDialog pd;
private String LOG_TAG = "ProvaAsyncTask";
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mioAsync mioTask = new mioAsync();
mioTask.execute();
stationsAdapter = new StationAdapter(stationList, getActivity());
ListView stationsListView = (ListView) rootView.findViewById(R.id.miaListView);
stationsListView.setAdapter(stationsAdapter);
return rootView;
}
public class mioAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Creo la ProgressDialog che precede il caricamento dei dati
pd = new ProgressDialog(getActivity());
pd.setMessage(MainActivityFragment.this.getString(R.string.preloader_stations_list));
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
try {
URL url = new URL("*remoteserver*");
// Create the request to the server, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try{
getStationsListFromJson(forecastJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pd.dismiss();
}
private void getStationsListFromJson(String stationsJsonStr) throws JSONException {
JSONArray stationsArray = new JSONArray(stationsJsonStr);
String nomeStaz;
String numSat;
stationList.clear();
for (int i = 0; i < stationsArray.length(); i++) {
JSONObject j = stationsArray.optJSONObject(i);
Iterator it = j.keys();
while (it.hasNext()) {
String n = it.next().toString();
numSat = j.getString(n) + " stazioni";
n = it.next().toString();
nomeStaz = j.getString(n);
stationList.add(new Station(nomeStaz, numSat));
}
}
}
}
}
The JSON string i get in return is like this
[{"nome":"Station1","satelliti":"11"},{"nome":"Station2","satelliti":"9"},{"nome":"Station3","satelliti":"8"}]
Here is where i extend the ArrayList
public class StationAdapter extends ArrayAdapter<Station> {
private List<Station> stationsList;
private Context context;
public StationAdapter(List<Station> lista, Context cont){
super(cont, R.layout.listitems, lista);
this.stationsList = lista;
this.context = cont;
}
public int getCount() {
return stationsList.size();
}
public Station getItem(int position) {
return stationsList.get(position);
}
public long getItemId(int position) {
return stationsList.get(position).hashCode();
}
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
StationHolder holder = new StationHolder();
// controllo che il convertview non sia null
if (convertView == null){
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.listitems, null);
// Now we can fill the layout with the right values
TextView stationName = (TextView) v.findViewById(R.id.testataUno);
TextView satellitesNumber = (TextView) v.findViewById(R.id.testataDue);
holder.stationNameView = stationName;
holder.satellitesNumberView = satellitesNumber;
v.setTag(holder);
} else {
holder = (StationHolder) v.getTag();
}
Station p = stationsList.get(position);
holder.stationNameView.setText(p.getName());
holder.satellitesNumberView.setText("" + p.getSatellites());
return v;
}
/* *********************************
* We use the holder pattern
* It makes the view faster and avoid finding the component
* **********************************/
private static class StationHolder {
public TextView stationNameView;
public TextView satellitesNumberView;
}
}
Here is the Station code
public class Station {
private String name;
private String satellites;
public Station(String nome, String satelliti){
this.name = nome;
this.satellites = satelliti;
}
public String getName(){
return this.name;
}
public String getSatellites(){
return this.satellites;
}
public void setName(String nome){
this.name = nome;
}
public void setSatellites(String satelliti){
this.satellites = satelliti;
}
}
You got the flow broken. It works in debug mode only because you stop execution of UI thread on your breakpoint, but line before your breakpoint you fired AsyncTask, and as this is not stopped, it downloads the data while you enjoy your breakpoint. You most likely assumed that AsyncTask (which is abbreviation of Asynchronous Task) is... well... synchronous. It's not. Your main code will not wait for asynctask,it will start it and continue. You need to rework your code and in asynctask's onPostExecute() method update your dataset based on downloaded content and then call notifyDatasetChanged() on your list's adapter. That should trigger list refresh.
i am working on this Android application which firstly downloads a .txt file from internet then populates the arraylist and in the end listview. The problem is that the Listview doesn't seem to populate despite that my file downloading and reading is everything ok since i have tested it with a TOAST.
Here is my code
Downloading File and Reading with AsyncTask
public class DownloadFile extends AsyncTask<String, Void, String> {
String filenamelist=TEST_FILE_NAME;
#Override
protected String doInBackground(String... params) {
//Here i download the file
} catch (Exception e) {
e.printStackTrace();
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
try {
InputStream instream = new FileInputStream(new File(getCacheDir(), filenamelist));
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader bReader = new BufferedReader(inputreader);
String key,value = null;
do{
key = bReader.readLine();
if(key != null)
value = bReader.readLine();
//channelname is the ArrayList
channelname.add(key);
channelmaps.put(key,value);
} while (key != null && value != null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Declaration of ArrayList
ArrayList<String> channelname = new ArrayList<String>();
Listview
final ListView listView = (ListView) findViewById(android.R.id.list);
channelname.removeAll(Collections.singleton(null));
ChannelAdapter cAdapter = new ChannelAdapter(this, channelname);
listView.setAdapter(cAdapter);
ChannelAdapter class
private class ChannelAdapter extends ArrayAdapter<String>
{
ArrayList<String> channelname;
public ChannelAdapter(Context context, ArrayList<String> channelname)
{
super (context, R.layout.activity_list_channels, channelname);
this.channelname = channelname;
}
public View getView(int position, View convertView, ViewGroup parent)
{
try
{
if(convertView==null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.mylistchannel,parent, false);
}
String name = getItem(position);
TextView txtview = (TextView) convertView.findViewById(R.id.Channelname);
txtview.setText(name);
return convertView;
}
catch(Exception e)
{
}
return null;
}
#Override
public int getCount()
{
return channelname.size();
}
#Override
public String getItem(int position)
{
return channelname.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
}
So what's the problem with my code? Why isn't the listview populated?
You should do
cAdapter.notifyDataSetChanged();
after the cycle in which you've read all the items from the file;