Listview appends new data instead of showing new data - android

I am new to android and sorry if somebody like this as stupid question
I have an activity that extends Listactivty. Listview is showing data fine when it is first time loaded. It shows all files and folders from server. But when i click on the listview then onListItemClick event is called and it again gets data from server but it is appending data with previous data. What i want is that ListView shows only the most recent data with no appending of data.
My ListView Activity code:
public class MainActivity extends ListActivity {
private String urlString="http://xxxxxxxxserver PathXXXXX";
private List<String> item = null;
private List<String> path = null;
private String root="http://xxxxxxxxserver PathXXXXX";
private String result;
private TextView myPath;
static private String pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View v= findViewById(R.id.rowtext);
myPath = (TextView)findViewById(R.id.path);
Http_connection f=new Http_connection();
f.execute("");
}
class Http_connection extends AsyncTask<String, Void, Void> {
private Exception exception;
protected Void doInBackground(String... urls)
{
try
{
URL url= new URL(urlString);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.connect();
int statusCode=con.getResponseCode();
if (statusCode==HttpURLConnection.HTTP_OK){
BufferedReader in= new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line=in.readLine())!=null)
{
result=result+"\n"+line;
}
in.close();
con.disconnect();
root="AndroidMapper";
runOnUiThread(new Runnable() {
#Override
public void run() {
getDir(urlString);
}
});
}
}
private void getDir(String dirPath)
{
String\[\] r=result.split("/");
myPath.setText("Location: " + urlString);
item = new ArrayList<String>();
path = new ArrayList<String>();
for (int k=0;k<r.length;k++)
{
if (r\[k\].contains("."))
{
item.add(r\[k\]);
}
else
{
item.add(r\[k\]+"/");
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(MainActivity.this, R.layout.row, item);
setListAdapter(fileList);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
String pos=new String(item.get(position));
if (pos.contains("."))
{
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
urlString=urlString+pos;
Http_connection f=new Http_connection();
f.execute("");
}

You need to re-init your result variable
Because of this line :
result=result+"\n"+line;
This way maybe :
String line;
result = "";
while ((line=in.readLine())!=null)
{
result=result+"\n"+line;
}

Related

AutoCompleteTextView on click of item not set in AutoCompleteBox

I want to show item in AutoCompleteTextView. Its working fine and all drop down item showing. but according to my need i dont want to set item in AutoComplete box on click of item. How can i achieve this?
public class AutoCompleteViewActvitiy extends Activity {
AutoCompleteTextView autoCompleteTextView;
String[] language;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.support_simple_spinner_dropdown_item);
//after calling this service then you will get resposne ...in post method
new CallServiceForFetchResponseOfCategory().execute();
}
public class CallServiceForFetchResponseOfCategory extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String stringUrl = params[0];
String result;
String inputLine;
try {
URL myUrl = new URL(stringUrl);
HttpURLConnection connection = (HttpURLConnection)
myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
result = null;
}
return result;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
//in response you will get category array ....
//like
then you will set array into this :
language = .......;
then
setResponse();
}
}
private void setResponse() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, language);
//Getting the instance of AutoCompleteTextView
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
autoCompleteTextView.setThreshold(1);//will start working from first character
autoCompleteTextView.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
autoCompleteTextView.setTextColor(Color.RED);
autoCompleteTextView.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) {
}
#Override
public void afterTextChanged(Editable s) {
// first srevice again and again call for fetching the result and show in autocomplete
if (autoCompleteTextView.getText().toString().trim().length() > 0) {
new CallServiceForFetchResponseOfCategory().execute();
}
}
});
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//according to id i will call this service but issue is that when i click on item it will set default in autocomplete text box and
//again afterTextChanged will call then again CallServiceForFetchResponseOfCategory hit, that is the issue
// i dont want call this time CallServiceForFetchResponseOfCategory service when i click on item...
new FetchingCityDataAsynkTask().execute();
}
});
}
//
public class FetchingCityDataAsynkTask extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String stringUrl = params[0];
String result;
String inputLine;
try {
URL myUrl = new URL(stringUrl);
HttpURLConnection connection = (HttpURLConnection)
myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
result = null;
}
return result;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
//setresponse here
}
}
}
Here is what I did in a project of mine. I simply put the text value of the AutoCompleteTextView to ""
articlesAutocomplete.setOnItemClickListener(
(detailedArticleAdapterView, childView, position, id) ->{
DetailedArticle selectedArticle = (DetailedArticle)detailedArticleAdapterView.getItemAtPosition(position);
/*logic with selected article*/
articlesAutocomplete.setText("");
}
);
I hope this is what you wanted to achieve :)
EDIT : I saw in your comments that you use a TextWatcher, why do you use it for? It may change the usefulness of my solution ^^

How do i get the right content in Single Item View

After Clicking an Item in my List view, my Single Item View should appear. Unfortunately every time i click on one of the two items just the same content appears. How can i fix the problem and the right content will be shown?
First i get parse data in my Main Activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = MainActivity.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
String image;
String street;
String postalcode;
String musicstyle;
String musicsecond;
String entry;
String opening;
String agegroup;
String urlbtn;
String Fsk;
String city;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final Button popbutton = (Button) findViewById(R.id.popbutton);
popbutton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
if (i == 1) {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.secondbg));
arrayList.clear();
url = "http://partypeople.bplaced.net/justpop.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i + 1;
}
} else {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.bg_popbutton));
arrayList.clear();
url = "http://partypeople.bplaced.net/maptest.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i - 1;
}
}
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
if (pDialog.isShowing())
pDialog.dismiss();
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
image= po.getString("imageurl"),
name = po.getString("name"),
street = po.getString("street"),
postalcode = po.getString("postalcode"),
musicstyle = po.getString("musicstyle"),
musicsecond = po.getString("musicsecond"),
entry = po.getString("entry"),
opening = po.getString("opening"),
agegroup = po.getString("agegroup"),
urlbtn = po.getString("urlbtn"),
Fsk = po.getString("Fsk"),
city = po.getString("city")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("imageurl",image);
intent.putExtra("street",street);
intent.putExtra("postalcode",postalcode);
intent.putExtra("musicstyle",musicstyle);
intent.putExtra("musicsecond",musicsecond);
intent.putExtra("entry",entry);
intent.putExtra("opening",opening);
intent.putExtra("agegroup",agegroup);
intent.putExtra("urlbtn",urlbtn);
intent.putExtra("Fsk",Fsk);
intent.putExtra("city",city);
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
/**
* Async task class to get json by making HTTP call
}
*/
}
Then as you can see in the bottom the content will be sent to the detailactivity, but i always get the content from the second item in my json even if i click on the first item.
Change your onItemClick method to get the right object from your list.
Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(positon);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}

Android: ListView from MySQL only display the last element

I'm trying to retrieve data from MySql database and put it on a ListView, everything works fine, I even put that data into textviews(dynamically) and it works fine. But when I used a ListView, only the last element was displayed, I think that means every new element is overwritten the old one, right?
What can I do to solve this? here's my code tell what's wrong??
public class MakeAppointementActivity extends AppCompatActivity {
public List<AvailabilityList> customList;
public ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_appointement);
lv=(ListView)findViewById(R.id.listView);
Intent intent=getIntent();
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String strUrl = "availableAppointments1.php";
URL url;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line;
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>> {
#Override
protected List<HashMap<String, String>> doInBackground(String... params) {
AppointementJSONParser appointementParser = new AppointementJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return appointementParser.parse(json);
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>(); / move it to here
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
addAvailableAppoint(fromT,toT,date);
}
updateListView(); // update listview when you add all data to arraylist
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
}
// split new function for update listview
private updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
intent.putExtra("fromT", fromT);
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
}
Try this code
.....// your above code
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>(); / move it to here
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
addAvailableAppoint(fromT,toT,date);
}
updateListView(); // update listview when you add all data to arraylist
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
}
// split new function for update listview
private updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
// intent.putExtra("fromT", fromT); // change it to
intent.putExtra("fromT", customList.get(position).getFromT());
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
}
Hope this help
You create new ArrayList for every item customList=new ArrayList<>();
Create list only once in OnCreate for example.
Also you create new Adapter every time you add an item, adapter should also be created only once in OnCreate then you should update data with adapter.NotifyDataSetChanged()

append more items to listfragment on scroll end

i know there are a lot of examples for this question on stackoverflow , but i don't know how to implement any of them on my code .
what i want to do is to load data from json url (first 15 element) , and append them to listfragment and when the user scroll down to the end of the list another 15 elements appended (total 30 elements on the list) and so on..
now i can fetch the first 15 elements correctly , but when i try to add more items when the user reach end of scroll i don't know what to do ... here is my code:
in MainActivity i have the following class which extend listfragment :
public static class NewsFragment extends ListFragment implements ILoadDataListener, OnScrollListener {
private ListView listView;
private NewsAdapter newsAdapter;
private int currentPage=1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceStatee){
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setOnScrollListener( this);
// URL to the JSON data
String strUrl = "http://opetmar.hostzi.com/test.php";
// Creating a new non-ui thread task to download json data
ProgressDialog progress = new ProgressDialog(getActivity());
progress.setMessage("loading ...");
GetJSON downloadTask = new GetJSON(this , progress , "news");
// Starting the download process
downloadTask.execute(strUrl);
}
#Override
public void onComplete(String[] titles , String[] images , String[] ids , String[] snippets , String[] data) {
if ( currentPage == 1 ){
newsAdapter = new NewsAdapter( getActivity() , titles , images , ids , snippets , data );
listView.setAdapter(newsAdapter);
}else {
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
DataHolder holder;
holder = (DataHolder) v.getTag();
Intent myIntent = new Intent(getActivity(), NewsOpen.class);
myIntent.putExtra("image", holder.image);
myIntent.putExtra("data", holder.data);
startActivity(myIntent);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - 1 ) {
currentPage++;
String strUrl = "http://opetmar.hostzi.com/test.php?page="+currentPage;
ProgressDialog progress = new ProgressDialog(getActivity());
progress.setMessage("loading ...");
GetJSON downloadTask = new GetJSON(this , progress , "news");
// Starting the download process
downloadTask.execute(strUrl);
}
}
}
}
NewsAdapter.java
public class NewsAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] titles;
private final String[] images;
private final String[] ids;
private final String[] snippets;
private final String[] data;
public NewsAdapter(Context context, String[] titles, String[] images , String[] ids , String[] snippets , String[] data) {
super(context, R.layout.drawer_list_item, titles);
this.context = context;
this.titles = titles;
this.images = images;
this.ids = ids;
this.snippets = snippets;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.news_list_item, parent, false);
TextView title = (TextView) rowView.findViewById(R.id.news_title);
TextView snippet = (TextView) rowView.findViewById(R.id.news_snippet);
ImageView imageView = (ImageView) rowView.findViewById(R.id.news_thumble);
title.setText(titles[position]);
snippet.setText(snippets[position]);
DataHolder holder = new DataHolder();
holder.data=data[position];
holder.image=images[position];
rowView.setTag(holder);
new DownloadImageTask(imageView).execute(images[position]);
return rowView;
}
public class DataHolder {
String image;
String data;
}
}
GetJSON.java
/** AsyncTask to download json data */
public class GetJSON extends AsyncTask<String, Integer, String>{
String data = null;
private ListView listView;
private NewsAdapter newsAdapter;
private ILoadDataListener mListener;
private ProgressDialog progress;
private String type;
public GetJSON(ILoadDataListener listener , ProgressDialog progress , String type) {
this.mListener = listener;
this.progress = progress;
this.type = type;
}
public void onPreExecute() {
progress.show();
}
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
if (result != null){
if (this.type == "news") {
try {
JSONObject jObject;
jObject = new JSONObject(result);
JSONArray jCountries = jObject.optJSONArray("news");
ArrayList<String> stringArrayList = new ArrayList<String>();
ArrayList<String> stringArrayList2 = new ArrayList<String>();
ArrayList<String> stringArrayList3 = new ArrayList<String>();
ArrayList<String> stringArrayList4 = new ArrayList<String>();
ArrayList<String> stringArrayList5 = new ArrayList<String>();
for (int i=0; i < jCountries.length(); i++)
{
try {
JSONObject oneObject = jCountries.getJSONObject(i);
// Pulling items from the array
stringArrayList.add(oneObject.getString("title"));
stringArrayList2.add( oneObject.getString("image"));
stringArrayList3.add( oneObject.getString("id"));
stringArrayList4.add( oneObject.getString("snippet"));
stringArrayList5.add( oneObject.getString("data"));
} catch (JSONException e) {
// Oops
}
}
String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
String [] stringArray2 = stringArrayList2.toArray(new String[stringArrayList2.size()]);
String [] stringArray3 = stringArrayList3.toArray(new String[stringArrayList3.size()]);
String [] stringArray4 = stringArrayList4.toArray(new String[stringArrayList4.size()]);
String [] stringArray5 = stringArrayList5.toArray(new String[stringArrayList5.size()]);
progress.dismiss();
if (mListener != null) {
mListener.onComplete(stringArray , stringArray2 , stringArray3 , stringArray4 , stringArray5);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}else{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
}
to be more specific , when the user reach the end of the scroll the following code will triggered which load more data from json url:
#Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - 1 ) {
currentPage++;
String strUrl = "http://opetmar.hostzi.com/test.php?page="+currentPage;
ProgressDialog progress = new ProgressDialog(getActivity());
progress.setMessage("loading ...");
GetJSON downloadTask = new GetJSON(this , progress , "news");
// Starting the download process
downloadTask.execute(strUrl);
}
}
then the GetJSON will call the following method after finish fetching and parsing data :
#Override
public void onComplete(String[] titles , String[] images , String[] ids , String[] snippets , String[] data) {
if ( currentPage == 1 ){
newsAdapter = new NewsAdapter( getActivity() , titles , images , ids , snippets , data );
listView.setAdapter(newsAdapter);
}else {
}
}
so if currentpage is not equal one , i want to append more data . how to achieve that ?
I'm not sure whether it's possible for ListView, but using Gallery you can override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
and use it to define the events when the items scrolled to the end. I did so to organize infinite list of calendar ietms in the gallery.
Regards,
Alex.

How to show a progress spinner in android, when doInBackground() is being executed

This is my Activity class where i use AsyncTask to get data from a server:
public class UserProfileActivity extends Activity {
private ImageView userImage;
private TextView userName;
private TextView userLocation;
private TextView editInfo;
private TextView chnageImage;
private TextView userScore;
private ListView friendsList;
public ArrayAdapter<String> adapter;
public int score;
public int level;
public String image;
public String fname;
public String lname;
public String city;
public int id;
public String email;
protected Activity activity = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
userImage = (ImageView) findViewById(R.id.profileImage);
userName = (TextView) findViewById(R.id.userName_profile);
userLocation = (TextView) findViewById(R.id.userLocation_profile);
editInfo = (TextView) findViewById(R.id.edit_profile);
chnageImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsList = (ListView) findViewById(R.id.friendsList);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
#Override
protected String doInBackground(String... params) {
try {
HttpPost httppost = new HttpPost(
"http://www.xxxxxxxxx.com/mobile/getProfileInfo");
HttpResponse response = SignUpActivity.httpclient
.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
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) {
}
try {
JSONObject jObj = new JSONObject(result);
String status = jObj.getString("status");
score = jObj.getInt("credits");
level = jObj.getInt("level");
image = jObj.getString("image");
fname = jObj.getString("fname");
lname = jObj.getString("lname");
city = jObj.getString("city");
id = jObj.getInt("user_id");
email = jObj.getString("email");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
int size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
String[] friendsIds = new String[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
}
adapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
}
} catch (Exception e) {
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
userImage.setImageBitmap(bitmap);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
when this activity is loaded it shows all the default values and images and then changes when background code execution is competed(as excepted), but this takes 2-3 secs for which user will be seeing default values, which i dont want to. So how can i keep a spinner like this:
for 2-3 secs and then when the spinner disappears the activity must show the actual values.
Thank you
Refer the below code
private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected Boolean doInBackground(final String... args) {
try {
Utilities.arrayRSS = objRSSFeed
.FetchRSSFeeds(Constants.Feed_URL);
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
// Setting data to list adapter
setListData();
}
Do This:-
Declare the ProgressDialog at the Top.
ProgressDialog pd;
Start it in onPreExecute Method of Async Task.
pd=ProgressDialog.show(ActivityName.this,"","Please Wait",false);
Stop it in the onPostExecute Method.
pd.dismiss();
In onCreate method call some like below
mdialog=new Dialog(this);
new LongOperation().execute("");
Then override onPostExecute of AyncTask
#Override
protected void onPostExecute() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mdialog.dismiss();
}
});
}

Categories

Resources