Making Image auto slider, i have written code to parse JSON but still using drawable images
Actually i am concern, How to use online images in slideshow instead of drawables
Please clear to me because if same kind of problem occurs in future so i will be able to make changes.
check my code below:
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
public int currentimageindex = 0;
ImageView slidingimage;
// using drawable images
// in place of these static images, how can i use my arraylist
// along with DownloadImageTask class, i have written posted below
private int[] IMAGE_IDS = {
R.drawable.splash0,
R.drawable.splash1,
R.drawable.splash2,
R.drawable.splash3
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
// execute AsyncTask
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
// handler to set duration and to upate animation
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 0000;
int period = 4000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
// AsyncTask to get data from server
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setImage(object.getString("image"));
Log.d("image: ", object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
// method to show slide show
private void AnimateandSlideShow() {
slidingimage = (ImageView)findViewById(R.id.ImageView3_Left);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
}
// method to dowload online images
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/ImageView3_Left"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>
Logcat:
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/cruise.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/johnny.jpg
10-09 05:21:34.636: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/jolie.jpg
10-09 05:21:34.666: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/tom.jpg
10-09 05:21:34.666: D/image:(735): http://microblogging.wingnity.com/JSONParsingTutorial/will.jpg
Here is my code. I use View Flipper
public class MainActivity extends Activity {
ArrayList<String> actorsList;
ViewFlipper viewFlipper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
actorsList = new ArrayList<String>();
// execute AsyncTask
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
// handler to set duration and to upate animation
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 500;
int period = 4000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
// AsyncTask to get data from server
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
// Actors actor = new Actors();
actorsList.add(object.getString("image"));
// actor.setImage(object.getString("image"));
Log.d("image: ", object.getString("image"));
// actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(result == false){
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else{
setFlipperImage( actorsList);
}
}
}
private void setFlipperImage(ArrayList<String> actorsList) {
for(int i=0;i<actorsList.size();i++){
Log.i("Set Filpper Called", actorsList.get(i).toString()+"");
ImageView image = new ImageView(getApplicationContext());
// image.setBackgroundResource(res);
Picasso.with(MainActivity.this)
.load(actorsList.get(i).toString())
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_launcher)
.into(image);
viewFlipper.addView(image);
}
}
// method to show slide show
private void AnimateandSlideShow() {
viewFlipper.showNext();
}}
And i use Picasso to load the images....
Related
Hi I am very for android just one week ago I come into this technology and in my app I am integrating services.
Here I have used HttpClient for that, but in android 6 I was deprecated.
That's why we have to use URlconnection, but how can we use this Url connection instead of HttpClient?
My code is below.
Please help me.
my code:-
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
Use Volley instead. Volley is compatible with almost all APIs.
See here on how to do this.
Here is ,my code for selecting images and texts from mysql database through php.And it is displaying in a linearlayout in a scrollview.All i want to do is change my layout to listview like this example.
I tried listview and other many ways but its not working properly.I'm new in android,so im trying for a long time.Please help me by editing my code for my requirement.Please.
JAVA
#SuppressLint("NewApi")
public class News_and_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_and_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pDialog = new ProgressDialog(getActivity());
View rootView = inflater.inflate(R.layout.activity_news_and_events, container, false);
cd = new ConnectionDetector(rootView.getContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(),
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
//return.rootView;
return rootView;
}
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
// Toast.makeText(getActivity(),image, Toast.LENGTH_LONG).show();
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(16);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundColor(Color.parseColor("#ffcd14"));
// headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(0, 20, 0, 0);
// headln.setHeight(50);
headln.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.CENTER);
detailsln.setPadding(10, 10, 10, 10);
int width = LayoutParams.WRAP_CONTENT;
int height = 200;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
img.setLayoutParams(parms);
parms.gravity = Gravity.CENTER;
img.setPaddingRelative (15, 15, 15, 15);
MainLL.addView(headln);
MainLL.addView(dateln);
// MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
img.setClickable(true);
// img.buildDrawingCache();
// final Bitmap bmap = img.getDrawingCache();
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}
pDialog.dismiss();
}
}
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
XML
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"[![enter image description here][1]][1]
(source: codelearn.org)
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false"
>
<LinearLayout
android:id="#+id/newslayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffffff"
>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
You cannot call display() from within AsyncTask to display results in listview.
You should follow the following steps
Inside on create, Call AsyncTask to fetch the data from server and populate this into an Array List. While async task is running, make sure you display a progress dialogue so that user cannot do anything in the UI thread.
Inside on create, do initialize your listview.
inside on Post execute of AsyncTask, after you have populated all the elements in the arraylist, call the adapter to populate the listview.
Define an adapter which extends BaseAdapter using which you can populate the listview from the array list.
You may want to check out this link for a similar working example.
I fetched json from server using asynctask and populated the listview. The list is too large and taking more time in 2g networks. so i want to use endscrolllistener on listview. When ever user scrolled down, it should fetch 30 items at a time. Can anyone please help me how to implement this. how to restrict doInBackground method to fetch only 30 items to listview at a time.
Please look into my code.
public class Articles extends Activity {
ArrayList<ArticlesGetSet> articlesList;
ArticlesAdapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articles_main);
mProgressDialog = new ProgressDialog(Articles.this);
mProgressDialog.setMessage("Currently downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Log.i("Main", "finito onCreate");
articlesList = new ArrayList<ArticlesGetSet>();
new JSONAsyncTask()
.execute("url");
ListView listview = (ListView) findViewById(R.id.list);
adapter = new ArticlesAdapter(getApplicationContext(),
R.layout.articles_row, articlesList);
listview.setAdapter(adapter);
listview.setOnScrollListener(new EndlessScrollListener());
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Articles.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// ------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("articles");
for (int i = 0; i < 30; i++) {
JSONObject object = jarray.getJSONObject(i);
ArticlesGetSet actor = new ArticlesGetSet();
actor.setName(object.getString("name"));
actor.setDob(object.getString("dob"));
actor.setHeight(object.getString("height"));
articlesList.add(actor);
}
return true;
// ------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
// if (result == false)
// Toast.makeText(getApplicationContext(),
// "Unable to fetch data from server", Toast.LENGTH_LONG)
// .show();
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new LoadMoreTask().execute("url");
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
class LoadMoreTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Articles.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// ------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("articles");
for (int i = 30; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
ArticlesGetSet actor = new ArticlesGetSet();
actor.setName(object.getString("name"));
actor.setDob(object.getString("dob"));
actor.setHeight(object.getString("height"));
articlesList.add(actor);
}
return true;
// ------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
}
}
}
Change
for (int i = 30; i < jarray.length(); i++) {
to
for (int i = 0; i < 30 && i < jarray.length(); i++) {
I'm having problem when I try to use HttpCleitn to fetch data from my server it takes a lot of time (about 30sec and response is only a few kB) and it keeps logging a messages: "Skippe xxx frames. App may be doing too much work on its main thread". There just a plenty of these messages (like a 1000 or 2000).
I'm really new to android dev and have no idea what i'm doing wrong. Though all the process of fetching data from the server is held inside the doInBackground method.
Here's all my code
public class MainActivity extends Activity {
ListView videoList;
ArrayList<String> videoArrayList;
ArrayAdapter<String> videoAdapter;
Context context;
String feedUrl = "http://www.rateksib.ru/ios/track_json.php?order=НскС101712124";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
videoArrayList = new ArrayList<String>();
videoList = (ListView) findViewById(R.id.videoList);
videoAdapter = new ArrayAdapter<String>(this, R.layout.video_list_item, videoArrayList);
videoList.setAdapter(videoAdapter);
VideoListTask loaderTask = new VideoListTask();
loaderTask.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class VideoListTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setTitle("Выполняется запрос");
dialog.show();
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
videoAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(feedUrl);
try
{
HttpResponse response = client.execute(getRequest);
StatusLine statusLine = response.getStatusLine();
if( statusLine.getStatusCode() != 200 ) {
return null;
}
InputStream jsonStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while( (line = reader.readLine()) != null ) {
stringBuilder.append(line);
}
String jsonData = stringBuilder.toString();
JSONObject json = new JSONObject(jsonData);
JSONArray results = json.getJSONArray("results");
for( int i = 0; i < results.length(); i++ ) {
JSONObject item = results.getJSONObject(i);
String status = item.getString("status");
String date = item.getString("date");
Log.i("OK:", "Detsya");
videoArrayList.add(date + ": " + status);
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
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();
}
});
}