Showing ProgressBar on parsing and downloading json result - android

In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}

Related

Progress Bar not visible with Stand alone asynctask

I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}

Showing loading for a UI freezing async task like this one

I have an Async task class which gets the name of a web method and run it and I have to wait for the result of that web method, so I used task.execute.get() method which is freezing my UI. the problem is that I want to show a loading dialog when task is executing but when I'm trying to call this method 10 times for 10 web methods, the UI freezes and after executing 10 web methods, loading dialog appears for 1 second.
What can I do to show loading without moving all of my codes into doInBackground? I want to have a class which gets web method info and returns the result. this is my class code:
public class AsyncCallWs extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
public String methodName="";
private WebService ws;
private ArrayList<ServiceParam> paramsList;
private boolean hasParams;
public AsyncCallWs(Activity activity,String methodName) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
hasParams = false;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
public AsyncCallWs(Activity activity,String methodName,ArrayList<ServiceParam> params) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
this.paramsList = params;
hasParams = true;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage(PersianReshape.reshape("Loading..."));
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
xLog.position();
String result = "No async task result!";
try {
ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL);
if (!hasParams){
result = ws.CallMethod(methodName);
}
else{
xLog.info("THIS METHOD IS: "+ methodName);
result = ws.CallMethod(methodName,paramsList);
xLog.info("THIS RESULT IS: "+ result);
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
xLog.position();
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
xLog.info("Output of current AsyncTask is:"+ result);
}
}
And this is the way I'm calling web methods using this class:
public void doSync(String method){
xLog.position();
AsyncCallWs t;
ArrayList<ServiceParam> serviceParams = new ArrayList<ServiceParam>();
String result="";
Settings settings = new Settings(activity);
PublicVariable.pGuid = Login(settings.getValue("Username"), settings.getValue("Password"));
xLog.info("pGuid in doSync is:" + PublicVariable.pGuid);
serviceParams.add(new ServiceParam("pGuid", PublicVariable.pGuid, String.class));
if (method=="all" || method=="person"){
try {
t = new AsyncCallWs(activity,"GetPersonInfo",serviceParams);
result = t.execute().get();
xLog.info("Sync Person=>"+ result);
String fields[] = result.split(PublicVariable.FIELD_SPLITTER);
Person person = new Person(activity,fields);
person.empty();
person.insert();
settings.update("PersonId",String.valueOf(person.getId()));
PublicVariable.personId = person.getId();
xLog.info("Person inserted...");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
if (method=="all" || method=="personImage"){
try {
t = new AsyncCallWs(activity,"GetPersonImage",serviceParams);
result = t.execute().get();
if (!result.equals("Nothing")){
settings.update("picture", result);
xLog.info("Picture updatted...");
}
else
xLog.error("NO PERSON IMAGE FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="lawyers"){
try {
t = new AsyncCallWs(activity,"GetLawyers",serviceParams);
result = t.execute().get();
xLog.info("Sync Lawyer=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Lawyer lawyer= new Lawyer(activity);
lawyer.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
lawyer = new Lawyer(activity, fields);
lawyer.insert();
}
xLog.info("Lawyers inserted...");
}
else
xLog.error("NO LAWYER FOUND!");
}catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="news"){
try {
t = new AsyncCallWs(activity,"GetNews",serviceParams);
result = t.execute().get();
String fields[];
Log.d("Ehsan","Sync News=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
News news = new News(activity);
news.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
news= new News(activity,fields);
news.insert();
}
xLog.info("News inserted...");
}
else
xLog.error("NO NEWS FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="messages"){
try {
t = new AsyncCallWs(activity,"GetMessagesInbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Inbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Inbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
try {
t = new AsyncCallWs(activity,"GetMessagesOutbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Outbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Outbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="requests"){
try {
t = new AsyncCallWs(activity,"GetAllRequests",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync share buy sell requests=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Share share = new Share(activity);
share.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
share= new Share(activity,fields);
share.insert();
}
xLog.info("Shares inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="financials"){
try {
t = new AsyncCallWs(activity,"GetFinancials",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync Financials=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Financial financial = new Financial(activity);
financial.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
financial= new Financial(activity,fields);
financial.insert();
}
xLog.info("Financials inserted...");
}
else{
Log.e("Ehsan", "NOT FINANCIALS FOUND!");
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
Here
result = t.execute().get(); //<<< calling get method
as in doc AsyncTask.get() :
Waits if necessary for the computation to complete, and then retrieves
its result.
so to avoid freezing of Main UI Thread during execution of doInBackground start AsyncTask without calling get method as|:
t.execute();
I want to have a class which gets web method info and returns the
result
For this you should implement callback with AsyncTask which report to Activity. see following examples :
android asynctask sending callbacks to ui
How to implement callback with AsyncTask

Asynctask never dies

I use asynctask to show data from json but asynctask show loading never dies, no error but loading and loading this code doInBackground function
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// check for login response
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
//DatabaseHandler db = new DatabaseHandler(
// activity.getApplicationContext());
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL+id_user);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// Getting Array of Following
user = json.getJSONArray(KEY_USER);
// looping through All Following
for (int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
// Storing each json item in variable
nama = c.getString(KEY_NAMA);
instansi = c.getString(KEY_INSTANSI);
status = c.getString(KEY_STATUS);
responseCode = 1;
}
} else{
responseCode = 0;
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
if (responseCode == 1) {
headerNama = (TextView)activity.findViewById(R.id.headerNama);
headerInstansi = (TextView)activity.findViewById(R.id.headerInstansi);
buttonStatus = (Button)activity.findViewById(R.id.buttonStatus);
headerNama.setText(nama);
headerInstansi.setText(instansi);
buttonStatus.setText(status);
}else {
progressDialog.dismiss();
activity.showDashboardError(responseCode);
}
}
i think no probleme in doinbackground, please help thanks
You should dismiss your dialog like:
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}

android - autocomplete text view is not updating

I try to update the autocomplete textview data from the web service based text typed in the textbox. It's working fine but i put the progressbar at the time of web service call because it will take some time in this case autocomplete text view is not showing the drop down menu. I guess autocomplete textview is dissmissed at the time of progressbar dissmissed. How should we put the progress bar in this case.
Code
class GetFundNames extends AsyncTask {
ProgressDialog progress = new ProgressDialog(BasicAutoText.this);
#Override
protected void onPreExecute() {
Log.d("TAG", "onPreExecute()");
progress.setMessage("Please wait...");
progress.setCanceledOnTouchOutside(false);
progress.show();
}
#Override
// three dots is java for an array of strings
protected String doInBackground(Void... args) {
try {
response = getNames(strKeyword);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
;
return response;
}
// then our post
#Override
protected void onPostExecute(String response) {
if(progress.isShowing())
{
progress.dismiss();
}
if (ETF_Constants.registerResponsevalue == 200) {
JSONArray arObjects;
try {
arObjects = new JSONArray(response);
arProducts = new ArrayList<ProductData>();
arProducts.clear();
for (int i = 0; i < arObjects.length(); i++) {
JSONObject jOb = arObjects.getJSONObject(i);
ProductData pd = new ProductData();
int fundId = jOb.getInt("fundId");
String con = "" + fundId;
String fundName = jOb.getString("fundName");
String priceAndDate = jOb.getString("priceAndDate");
String recentGain = jOb.getString("recentGain");
String recentGrowth = jOb.getString("recentGrowth");
String tickerName = jOb.getString("tickerName");
pd.fundId = con;
pd.fundName = fundName;
pd.priceAndDate = priceAndDate;
pd.recentGain = recentGain;
pd.recentGrowth = recentGrowth;
pd.tickerName = tickerName;
arProducts.add(pd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// autocomplete
adapter = new ArrayAdapter<String>(BasicAutoText.this,
R.layout.advancelist);
adapter.setNotifyOnChange(true);
AUTO_View.setAdapter(adapter);
System.out.println("adapter" + adapter);
for (int i = 0; i < arProducts.size(); i++) {
adapter.add(arProducts.get(i).fundName);
System.out.println("Fund Name:"
+ arProducts.get(i).fundName);
}
System.out.println("arProducts count:" + arProducts.size());
System.out.println("adapter count:" + adapter.getCount());
adapter.notifyDataSetChanged();
}
}
}

Fetching and setting images in listView via HTTP

I am making an app that loads images via internet to a ListView. It is built on sdk 15 with an minimum of 8. Everything works fine if i run it on an emulator with version 8, but if i run it on anything with an sdk of 11 and up the app fails to set the images in the ListView and it then only displays an empty list. Logcat doesn't give anything on this.
I haven't had any succes finding an article addressing this issue, but i think it most be something with the HTTP that is suppose to get the images from the internet, but i don't understand why they don't work on the newer versions of android.
My code looks like this.
EDIT UPDATED CODE:
public class MainActivity extends Activity {
static ArrayList<Tumblr> tumblrs;
ListView listView;
TextView footer;
int offset = 0;
ProgressDialog pDialog;
View v;
String responseBody;
HttpResponse r;
HttpEntity e;
String searchUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
setContentView(R.layout.main);
try {
tumblrs = getTumblrs();
listView = (ListView) findViewById(R.id.list);
View v = getLayoutInflater().inflate(R.layout.footer_layout,
null);
footer = (TextView) v.findViewById(R.id.tvFoot);
listView.addFooterView(v);
listView.setAdapter(new UserItemAdapter(this, R.layout.listitem));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
new GetChicks().execute();
footer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new loadMoreListView().execute();
}
});
} else {
setContentView(R.layout.nonet);
}
}
public class UserItemAdapter extends ArrayAdapter<Tumblr> {
public UserItemAdapter(Context context, int imageViewResourceId) {
super(context, imageViewResourceId, tumblrs);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Tumblr tumblr = tumblrs.get(position);
if (tumblr != null) {
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (image != null) {
image.setImageBitmap(GetImage_usingURl(urls[position]));
}
}
return v;
}
}
String[] urls = new String[] { "url1", "url2", "url2" };
public Bitmap GetImage_usingURl(String BitmapUrl) {
try {
Log.d("Image Download State", " Open Stream For : " + BitmapUrl);
InputStream in = new java.net.URL(BitmapUrl).openStream();
Log.d("Image Download State", " Start Decode");
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", "" + e.getMessage());
return null;
}
}
public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
IOException, JSONException {
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=rTZsymOWtMudbb5tql2U20qQ5ooYLPYVNnL3COPpO2qBHDxJUu&limit=2&offset=0";
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
return tumblrs;
}
private class GetChicks extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Chicks coming up..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpGet get = new HttpGet(searchUrl);
HttpResponse r = null;
try {
r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
e = r.getEntity();
responseBody = EntityUtils.toString(e);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray(
"photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// Setting new scroll position
listView.setSelectionFromTop(0, 0);
pDialog.dismiss();
}
}
public class Tumblr {
public String image_url;
public Tumblr(String url) {
this.image_url = url;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("More chicks coming up..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
// increment current page
offset += 2;
// Next page request
tumblrs.clear();
String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=rTZsymOWtMudbb5tql2U20qQ5ooYLPYVNnL3COPpO2qBHDxJUu&limit=2&offset="
+ offset;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
HttpResponse r = null;
try {
r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
responseBody = EntityUtils.toString(e);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray(
"photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// Setting new scroll position
listView.setSelectionFromTop(0, 0);
pDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.aboutUs:
Intent i = new Intent("com.example.example.ABOUT");
startActivity(i);
break;
case R.id.refresh:
Intent f = new Intent(MainActivity.this, MainActivity.class);
startActivity(f);
finish();
break;
case R.id.exit:
finish();
break;
}
return false;
}
}
LOG
10-09 13:21:57.923: D/Image Download State(888): Open Stream For : url1
10-09 13:21:57.923: E/Error(888): Protocol not found: url1
10-09 13:21:58.013: D/Image Download State(888): Open Stream For : url2
10-09 13:21:58.033: E/Error(888): Protocol not found: url2
10-09 13:21:58.113: D/Image Download State(888): Open Stream For : url1
10-09 13:21:58.123: E/Error(888): Protocol not found: url1
10-09 13:21:58.153: D/Image Download State(888): Open Stream For : url2
10-09 13:21:58.153: E/Error(888): Protocol not found: url2
For Images From internet Try this Could Help you:
if you want to download when you create adapter .
String[] urls=new String[]{"url1","url2","url2"}
public Bitmap GetImage_usingURl(String url){
try {
Log.d("Image Download State", " Open Stream For : "
+ url);
InputStream in = new java.net.URL(url).openStream();
Log.d("Image Download State", " Start Decode");
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
return null;
e.printStackTrace();
}
}
And When You Create Adapet Just Use :
image.setImageBitmap(GetImage_usingURl(urls[position]);
Important Thing For Your Project You Have To Get Policy When You using HTTP its Only For API 9 or higher so i check VERSION.SDK_INT First .
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if you don't set StrictMode you program maybe crash.
Set This Code Before Everything .
Your Errors Its :
In getView You Try To Check img!=null but you forget its create now and its already null
so compiler never get in and set your images , This is first thing .

Categories

Resources