When I call asynctask function data is load and display in listview but whenever i go into this activity everytime that function execute and load data again. But I just want that function call only once and display in listview. So what is the solution for that.
This is My full class code:
public class Feed extends Fragment implements
PullToRefreshAttacher.OnRefreshListener {
Button btnSlider;
ListView lv;
String userid, success, message, eventType, feed_title, feed_desc,
timeDate, like, commemt, Feeduserid, photo, posted, hasLike,
latsId, noMore, feed_id, category_id, feedImg, result;
InputStream is;
ProgressDialog pDialog;
InterNetConnectionDetector isNet = new InterNetConnectionDetector(
getActivity());
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
FeedAdapter fdp;
HashMap<String, String> map;
private uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher mPullToRefreshAttacher;
int limit = 5;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.feed, container, false);
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
SharedPreferences pref = getActivity().getSharedPreferences("Login",
Activity.MODE_PRIVATE);
userid = pref.getString("user_id", "user_id");
btnSlider = (Button) v.findViewById(R.id.btnSlide);
lv = (ListView) v.findViewById(R.id.feed_ListView);
btnSlider.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
Sliding.viewActionsContentView.showActions();
} catch (Exception e) {
// TODO: handle exception
}
}
});
try {
if (fdp == null) {
new FeedData().execute();
} else {
lv.setAdapter(fdp);
}
} catch (Exception e) {
// TODO: handle exception
}
mPullToRefreshAttacher = new uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher(
getActivity(), lv);
// Set Listener to know when a refresh should be started
mPullToRefreshAttacher
.setRefreshListener((uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher.OnRefreshListener) this);
((LoadMore) lv)
.setOnLoadMoreListener(new com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
return v;
}
/*
* #Override protected void onCreate(Bundle savedInstanceState) { // TODO
* Auto-generated method stub super.onCreate(savedInstanceState);
* setContentView(R.layout.feed);
*
* if (Build.VERSION.SDK_INT >= 8) { getActionBar().hide(); }
*
* if (android.os.Build.VERSION.SDK_INT > 8) {
*
* StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
* .permitAll().build(); StrictMode.setThreadPolicy(stp);
*
* }
*
* try { new FeedData().execute();
*
* } catch (Exception e) { // TODO: handle exception }
*
* SharedPreferences pref = getSharedPreferences("Login",
* Activity.MODE_PRIVATE); userid = pref.getString("user_id", "user_id");
*
* btnSlider = (Button) findViewById(R.id.btnSlide); lv = (ListView)
* findViewById(R.id.feed_ListView); btnSlider.setOnClickListener(new
* OnClickListener() {
*
* #Override public void onClick(View arg0) { // TODO Auto-generated method
* stub
*
* int width = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
* 40, getResources() .getDisplayMetrics());
* SlideoutActivity.prepare(getActivity(), R.id.inner_content, width);
* startActivity(new Intent(getActivity(), MenuActivity.class));
* getoverridePendingTransition(0, 0);
*
* } });
*
* mPullToRefreshAttacher = new PullToRefreshAttacher(getActivity(), lv);
*
* // Set Listener to know when a refresh should be started
* mPullToRefreshAttacher .setRefreshListener((OnRefreshListener)
* getActivity());
*
* ((LoadMore) lv) .setOnLoadMoreListener(new
* com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() { public
* void onLoadMore() { // Do the work to load more items at the end of list
* // here new LoadDataTask().execute(); } }); }
*/
public class FeedData extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(), "", "Loading..");
pDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
Log.v("Length", contactList.size() + "");
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
}
}
#Override
public void onRefreshStarted(View view) {
/**
* Simulate Refresh with 4 seconds sleep
*/
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Notify PullToRefreshAttacher that the refresh has finished
mPullToRefreshAttacher.setRefreshComplete();
}
}.execute();
}
private class LoadDataTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
limit += 5;
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
// mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
fdp.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMore) lv).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMore) lv).onLoadMoreComplete();
}
}
}
Better option is like, just declare your ADAPTER as public static in your ROOT class or in your activity. This will make single copy. And you are done with.
Suppose you have following structure.
ABC (ROOT/SPLASH) Activity -> class Feed extends Fragment
So basically you are calling Feed from ABC. Inside ABC, declare like
public class ABC...{
public static FeedAdapter fdp;
//.. all other stuffs
}
public class Feed...{
//.. to use that object delcared in ABC
ABC.fdp = new FeedAdapter(...);
}
Related
In my app I am getting response from server and displayint it in listview, now what I am trying is when user click on listitem it should get position of it and need to send it to next activity, but it is not working.
Following is mt snippet code
btn_go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// listView1.removeAllViews();
listView1.setAdapter(null);
arraylist_oper = new ArrayList<HashMap<String, String>>();
// listView1.notify();
new getOperationalControlList().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
});
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
//qr = ((String) listView1.getItemAtPosition(position)).toString();
Intent intent=new Intent(OperationalControl.this,DispatchTracking.class);
intent.putExtra("arrow_val", "2");
intent.putExtra("qrcodes", qr);
Toast.makeText(OperationalControl.this, qr, Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
class getOperationalControlList extends AsyncTask<String, String, String> {
private String msg = "";
int register_error = 1;
JSONArray operation;
JSONObject obc;
String error;
String access_token, office_name, office_id;
String user_id;
String name;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(OperationalControl.this);
progressDialog.setCancelable(true);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();
noresponse.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObjSend;
String content = null;
arraylist_oper = new ArrayList<HashMap<String, String>>();
try {
consts.pref = getSharedPreferences("pref", MODE_PRIVATE);
consts.editor = consts.pref.edit();
String OperationalControlList_URL = ((consts.pref
.getString(consts.Base_URL,
consts.Base_URL)) + consts.OperationalControlList_URL);
Log.d("OperationalControlList_URL url:",
OperationalControlList_URL);
arraylist = new ArrayList<HashMap<String, String>>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(OperationalControlList_URL);
System.out.println("URL :-"
+ consts.OperationalControlList_URL.toString());
user_id = consts.pref.getString("user_id", "");
access_token = consts.pref.getString("access_token", "");
office_id = consts.pref.getString("office_id", "");
date = date_dropdown.getText().toString();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(
5);
nameValuePair.add(new BasicNameValuePair("user_id", user_id));
nameValuePair.add(new BasicNameValuePair("access_token",
access_token));
nameValuePair.add(new BasicNameValuePair("filter", filter));
nameValuePair
.add(new BasicNameValuePair("office_id", office_id));
nameValuePair.add(new BasicNameValuePair("date", date));
// Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("USER_ID : " + user_id.toString());
System.out.println("access_token : "
+ access_token.toString());
System.out.println("filter : " + filter.toString());
System.out.println("office_id : " + office_id.toString());
System.out.println("date : " + date.toString());
content = EntityUtils.toString(entity);
Log.d("aaa", content);
jsonObjSend = new JSONObject(content.toString());
if (jsonObjSend.getString("status").equals("2")) {
register_error = 1;
error = jsonObjSend.getString("error");
if (error.equals("3")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("4")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("5")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("6")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("7")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("8")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("9")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("10")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("11")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("12")) {
msg = jsonObjSend.getString("message");
} else {
msg = jsonObjSend.getString("message");
}
// {"status":1,"message":"There is no activity of the selected day and filtering otpions"}
} else if (jsonObjSend.getString("status").equals("1")) {
if (jsonObjSend.has("message"))
msg = jsonObjSend.getString("message");
// msg = jsonObjSend.getString("message");
register_error = 0;
operation = new JSONArray();
if (jsonObjSend.has("list")) {
operation = jsonObjSend.getJSONArray("list");
// arraylist_oper = new ArrayList<HashMap<String,
// String>>();
for (int i = 0; i < operation.length(); i++) {
map = new HashMap<String, String>();
qr = operation.getJSONObject(i)
.getString("qrcode");
type = operation.getJSONObject(i)
.getString("type").toString();
Log.d("Types", type);
String origin = operation.getJSONObject(i)
.getString("origin");
String destiny = operation.getJSONObject(i)
.getString("destiny");
String stop_status = operation.getJSONObject(i)
.getString("stop_status");
String stop_status_name = operation
.getJSONObject(i).getString(
"stop_status_name");
String stop_status_color = operation
.getJSONObject(i).getString(
"stop_status_color");
map.put("qrcode", qr);
map.put("type", type);
map.put("origin", origin);
map.put("destiny", destiny);
map.put("stop_status", stop_status);
map.put("stop_status_name", stop_status_name);
map.put("stop_status_color", stop_status_color);
// map.put("status_name", status_name);
arraylist_oper.add(map);
Log.d("qrcode:", qr + " type: " + type
+ " origine: " + origin);
}
} else {
msg = jsonObjSend.getString("message");
}
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if (error.equals("6")) {
Intent intent=new Intent(OperationalControl.this,LoginActivity.class);
startActivity(intent);
OperationalControl.this.finish();
}
try {
if (arraylist_oper.size() > 0) {
Operational_LazyAdapter adpt = new Operational_LazyAdapter(
getApplicationContext(), arraylist_oper);
listView1.setAdapter(adpt);
// Toast.makeText(getApplicationContext(), msg,
// Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Office não definir corretamente ou" + msg,
Toast.LENGTH_LONG).show();
noresponse.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Response
{"status":1,
"list":[{
"qrcode":"#00000757-00000277-700101-0000000040",
"type":"Tipo de Opera\u00e7\u00e3o: Chegada",
"origin":"Origem: ARMAMAR (757)",
"destiny":"Destino: REGUA (277)",
"stop_status":6,
"stop_status_name":"Finalizado",
"stop_status_color":"#cccccc"
},
{
"qrcode":"#00000278-00000277-700101-0000000041",
"type":"Tipo de Opera\u00e7\u00e3o: Chegada",
"origin":"Origem: LAMEGO (278)",
"destiny":"Destino: REGUA (277)",
"stop_status":6,
"stop_status_name":"Finalizado",
"stop_status_color":"#cccccc"
}]
}
On the Intent you create on the list item click listener you should add all variables you need.
In your case add
intent.putExtra("position", position);
In your DispatchTracking Activity use
int position = getIntent().getExtras().getInt("position");
Just you need to pass your HashMap Arraylist to next Activity. Like,
intent.putExtra("myList",arraylist_oper);
and in your next Activity just retrieve as
Intent intent = getIntent();
ArrayList<HashMap<String,String>> mylist = (ArrayList<HashMap<String, String>>)intent.getSerializableExtra("myList");
EDIT :
You need to pass your qrCode too next Activity
intent.putExtra("qrcodes", arraylist_oper.get(position).get("qrcode")));
Now retrieve in next activity as
String qrCode = intent.getStringExtra("qrcodes");
Now check your retrivable arraylist in your second activity using For loop.
for(int i=0; i < myList.size ; i++) {
if(qrCode.equals(myList.get(i).get("qrcode"))){
// get your data here you can get according to qrCode. Like
String density = myList.get(i).get("destiny"); // same for others
}
On the auto load, I need to be able to load more items from the URL. Where I am getting my Data via Json.
in my API call class I need to add to this nuber 10 as:
pairs.add(new BasicNameValuePair("limit", "10"));
Whenever the list view finish loading the currently data, then changes the value above and check again.
I though I needed to create a method in PaginationDemoActivity where it check for if more pages, then use intent to pass a new variable to overwrite ("limit", "10")) in the JSONfunctions class
Any advice ? Thanks guys
JSONfunctions
public class JSONfunctions extends Activity{
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//Add URL Encoding by sending post data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("c","getlist"));
pairs.add(new BasicNameValuePair("page","1"));
pairs.add(new BasicNameValuePair("limit", "10"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httppost.setEntity(entity);
// end Add URL Encoding by sending post data
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
//end test
/*
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
*/
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Data
public class Data {
static String URL = " my api url";
static String itemsPerPage = "20";
public static final String TAG = Data.class.getSimpleName();
public static List<Pair<String, List<Composer>>> getAllData() {
List<Pair<String, List<Composer>>> res = new ArrayList<Pair<String, List<Composer>>>();
for (int i = 0; i < 4; i++) {
res.add(getOneSection(i));
}
return res;
}
public static List<Composer> getFlattenedData() {
List<HashMap<String, String>> arraylist;
JSONObject jsonobject;
JSONArray jsonarray;
List<Composer> res = new ArrayList<Composer>();
//Pair<String, List<Composer>> mydata;
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(URL);
Log.e("check", jsonobject.toString());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id", jsonobject.getString("id"));
map.put("title", jsonobject.getString("title"));
map.put("s_desc", jsonobject.getString("s_desc"));
map.put("img", jsonobject.getString("img"));
// Set the JSON Objects into the array
arraylist.add(map);
Composer s = new Composer(
jsonobject.getString("title"),
jsonobject.getString("s_desc"),
jsonobject.getString("id"),
jsonobject.getString("img"));
res.add(s);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return res;
}
protected void updateUrlItems()
{
}
public static Pair<Boolean, List<Composer>> getRows(int page) {
List<Composer> flattenedData = getFlattenedData();
if (page == 1) {
return new Pair<Boolean, List<Composer>>(true, flattenedData.subList(0, 5));
} else {
SystemClock.sleep(2000); // simulate loading
return new Pair<Boolean, List<Composer>>(page * 5 < flattenedData.size(),
flattenedData.subList((page - 1) * 5, Math.min(page * 5, flattenedData.size())));
}
}
public static Pair<String, List<Composer>> getOneSection(int index) {
String[] titles = {"", "", "", ""};
Composer[][] composerss = {
{
new Composer("", "", "", ""),
},
};
return new Pair<String, List<Composer>>(titles[index], Arrays.asList(composerss[index]));
}
}
PaginationDemoActivity
public class PaginationDemoActivity extends Activity {
AmazingListView lsComposer;
PaginationComposerAdapter adapter;
ImageLoader imageLoader;
// Flag for current page
static Integer current_page = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagination_demo);
imageLoader = new ImageLoader(this);
lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
lsComposer.setAdapter(adapter = new PaginationComposerAdapter());
adapter.notifyMayHaveMorePages();
}
public void bRefresh_click(View v) {
adapter.reset();
adapter.resetPage();
adapter.notifyMayHaveMorePages();
}
class PaginationComposerAdapter extends AmazingAdapter {
List<Composer> list = Data.getRows(1).second;
private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;
public void reset() {
if (backgroundTask != null) backgroundTask.cancel(false);
list = Data.getRows(1).second;
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Composer getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
Log.d(TAG, "Got onNextPageRequested page=" + page);
if (backgroundTask != null) {
backgroundTask.cancel(false);
}
backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
#Override
protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
int page = params[0];
Log.e("more page", "page: " + page);
return Data.getRows(page);
}
#Override
protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
if (isCancelled()) return;
Log.e("onPostExecute", "result: " + result.first);
list.addAll(result.second);
nextPage();
notifyDataSetChanged();
if (result.first) {
// still have more pages
notifyMayHaveMorePages();
} else {
notifyNoMorePages();
}
};
}.execute(page);
}
#Override
protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
View res = convertView;
if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
// we don't have headers, so hide it
res.findViewById(R.id.header).setVisibility(View.GONE);
TextView lName = (TextView) res.findViewById(R.id.lName);
TextView lYear = (TextView) res.findViewById(R.id.lYear);
TextView lId = (TextView) res.findViewById(R.id.lId);
// Locate the ImageView in listview_item.xml
ImageView lImg = (ImageView) res.findViewById(R.id.lImg);
Composer composer = getItem(position);
lName.setText(composer.name);
lYear.setText(composer.year);
lId.setText(composer.id);
Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
// Capture position and set results to the ImageView
// Passes img images URL into ImageLoader.class
imageLoader.DisplayImage(composer.img, lImg);
Log.e("222","333");
//khen
lsComposer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
if(id > -1){
Composer composer = adapter.getItem(position);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SingleItemView.class);
Bundle bundle = new Bundle();
bundle.putString("id", composer.id);
bundle.putString("name", composer.name);
bundle.putString("year", composer.year);
bundle.putString("img", composer.img);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
//end khen
return res;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
}
#Override
public int getPositionForSection(int section) {
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
return null;
}
}
}
I have some data on the internet for each specific longitude and latitude. If a user inputs a particular latitude and longitude, the data is downloaded from the web and then used in further calculation. I want to save that data so that the next time the user inputs the same latitude and longitude, It bypasses the web connectivity and proceeds with the existing data.
My Input Class:
public class OpTilt extends Activity implements OnClickListener {
EditText latitude, longitude;
Button go;
String data1, data2, link, link1;
double dat1, dat2;
TextView gps;
SharedPreferences dataurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.optilt);
initialize();
go.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
go = (Button) findViewById(R.id.loaddata);
latitude = (EditText) findViewById(R.id.lat);
longitude = (EditText) findViewById(R.id.lon);
dataurl = getSharedPreferences("url", 0);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
data1 = longitude.getText().toString();
data2 = latitude.getText().toString();
dat1 = Double.parseDouble(data1);
dat2 = Double.parseDouble(data2);
link = ("http://www.otilt.com/api.php?lat=" + dat2 + "&lon=" + dat1);
SharedPreferences.Editor editor = dataurl.edit();
editor.putString("key", link);
editor.commit();
Intent i = new Intent(OpTilt.this, DataRetrieve.class);
startActivity(i);
}
}
My Parsing Class:
public class DataRetrieve extends Activity {
HttpClient client;
String URL, re, element;
JSONObject json, getjson;
int i, j, statusCode;
HttpGet httpget;
HttpResponse response;
HttpEntity entity;
InputStream is;
BufferedReader reader;
StringBuilder sb, sb1;
WakeLock w;
SharedPreferences getinput, passjson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
w = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "tag");
super.onCreate(savedInstanceState);
w.acquire();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.dataretrieve);
// Bundle gotBasket = getIntent().getExtras();
// URL = gotBasket.getString("key");
getinput = getSharedPreferences("url", 0);
URL = getinput.getString("key", null);
Read r = new Read();
r.execute();
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DataRetrieve.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
re = null;
is = null;
json = null;
try {
client = new DefaultHttpClient();
httpget = new HttpGet(URL);
response = client.execute(httpget);
entity = response.getEntity();
is = entity.getContent();
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
statusCode = -1;
Log.e("log_tag", "Erro http " + e.toString());
}
if (statusCode == 200) {
try {
reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
re = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Erro conversão " + e.toString());
}
}
return re;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pd.dismiss();
try {
json = new JSONObject(result);
getjson = json.getJSONObject("Solar");
String H[] = new String[getjson.length()];
for (i = 0, j = 1; i < getjson.length(); i++, j++) {
H[i] = getjson.getString("" + j);
}
Bundle bundle = new Bundle();
bundle.putStringArray("key1", H);
Intent f = new Intent(DataRetrieve.this, Calculator.class);
f.putExtras(bundle);
startActivity(f);
}
catch (JSONException e) {
Log.e("log_tag", "Erro dados " + e.toString());
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
w.release();
finish();
}
}
So, how can I achieve my goal?
package com.Itattooz.Gallery;
#SuppressWarnings("unused")
public class grid_layout extends Activity {
private GridView list;
private String id_folder;
private LazyAdapter1 adapter;
private Intent intent;
private String main_folder;
private JSONArray jArray;
private String result = null;
private InputStream is = null;
private StringBuilder sb = null;
private String[] r;
boolean flag1 = false, flag2 = false, flag3 = false;
private String[] sub_folder_id;
private String[] path;
private String[] sub_folder_name;
private String[] flag;
private String previouse_folder;
private String[] url;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
intent = getIntent();
main_folder = intent.getStringExtra("selected_item");
new Thread(new Runnable() {
public void run() {
databaseConnectivity();
}
}).start();
list = (GridView) findViewById(R.id.list);
adapter = new LazyAdapter1(this, url, sub_folder_name);
list.setAdapter(adapter);
list.setOnItemClickListener(grid_listener);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
// djhwawd
OnItemClickListener grid_listener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
id_folder = sub_folder_id[position];
flag1 = true;
TextView text = (TextView) v.findViewById(R.id.text);
String str = (String) text.getText();
if (flag[position].equals("X")) {
//main_folder = main_folder + "/" + str.replace(" ", "%20");
// int flags = Intent.FLAG_ACTIVITY_SINGLE_TOP;
intent = new Intent(v.getContext(), grid_layout_main.class);
intent.putExtra("folder_name", main_folder.replace(" ", "%20") + "/" + str.replace(" ", "%20"));
intent.putExtra("id", sub_folder_id[position]);
startActivity(intent);
} else {
flag2=true;
main_folder = main_folder + "/" + str.replace(" ", "%20");
int flags = Intent.FLAG_ACTIVITY_SINGLE_TOP;
intent = new Intent(v.getContext(), grid_layout.class);
intent.setFlags(flags);
intent.putExtra("selected_item", main_folder);
startActivity(intent);
}
}
};
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
new Thread(new Runnable() {
public void run() {
databaseConnectivity();
}
}).start();
adapter = new LazyAdapter1(this, url, sub_folder_name);
list.setAdapter(adapter);
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
list.setOnItemClickListener(grid_listener);
}
public void databaseConnectivity() {
HttpPost httppost = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try {
HttpClient httpclient = new DefaultHttpClient();
if (flag1 == false) {
nameValuePairs
.add(new BasicNameValuePair("folder", main_folder));
httppost = new HttpPost(
"http://www.itattooz.com/android/index.php");
} else if (flag1 == true) {
nameValuePairs.add(new BasicNameValuePair("sub_folder_id",
id_folder));
httppost = new HttpPost(
"http://www.itattooz.com/android/index2.php");
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
String rt;
try {
jArray = new JSONArray(result);
path = new String[jArray.length()];
sub_folder_id = new String[jArray.length()];
sub_folder_name = new String[jArray.length()];
flag = new String[jArray.length()];
url = new String[jArray.length()];
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
sub_folder_id[i] = json_data.getString("id");
sub_folder_name[i] = json_data.getString("folder");
flag[i] = json_data.getString("flag");
path[i] = json_data.getString("path");
rt = "http://www.itattooz.com/itattooz/"
+ main_folder.replace(" ", "%20") + "/"
+ sub_folder_name[i].replace(" ", "%20")
+ "/cover_image/" + path[i].replace(" ", "%20");
url[i] = rt;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Image Found",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
onResume();
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onResume() { // After a pause OR at startup
super.onResume();
// Refresh your stuff here
}
#Override
protected void onPause() {
super.onPause();
}
}
Hello Above is my code for a Gallery view as a grid layout ..
I researched a lot on net and got to know I should use AsyncTask for what I am trying to achieve .. Here Are few problems i am facing
I am doing something on Main thread
I want to change it to AsyncTask..
Don't know what should I do exactly to get rid of this issue.. Please Help...
use the asyncTask to handle this exception.
Please see the android developer Link
or you can see the stackoverflow Accepted answer related to this Link HERE
For exmp
class YourTask extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
// Fetch Data (Task A)
return "Result";
}
protected void onProgressUpdate(Integer... progress) {
// Show progress
}
protected void onPostExecute(String result) {
// Show UI after complete (Task B)
}
}
Use Async Task
or
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
use AsyncTask
or
add below code in your onCreate() method before thread starts to disable the strict mode using following code:
this is not the solution but avoids network IO on main thread so i recommend AsyncTask
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
also check internet permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
I have an application where I fetch data from http server & set data to activity.
for fetching data from server it takes time. so i want to give an progress dialog there.
I did that but problem is that progressdialog is coming but its not rotating(only constant).
Plz anybody tell me how it came like this!
Below is my code,
private void setupViews()
{
imgRestro = (ImageView) findViewById(R.id.imageResturant);
tvRestroName = (TextView) findViewById(R.id.tvRestroName);
tvRestroAddr = (TextView) findViewById(R.id.tvRestroAddr);
tvRestroArea = (TextView) findViewById(R.id.tvRestroArea);
tvRestroCity = (TextView) findViewById(R.id.tvRestroCity);
tvRestroPhone = (TextView) findViewById(R.id.tvRestroPhone);
tvRestroRating = (TextView) findViewById(R.id.tvRestroRating);
tvRestroCuisines = (TextView) findViewById(R.id.tvRestroCuisines);
tvRestroAttr = (TextView) findViewById(R.id.tvRestroAttributes);
}
//to execute url
private String executeHttpGet(String URL) throws Exception {
URL url = null;
StringBuffer strBuf = null;
BufferedReader read = null;
HttpURLConnection httprequest = null;
try {
url = new URL(URL);
httprequest = (HttpURLConnection) url.openConnection();
httprequest.setRequestMethod("GET");
httprequest.setDoInput(true);
httprequest.setDoOutput(true);
httprequest.setConnectTimeout(5000); //time for before connect
httprequest.setRequestProperty("Content-Type",
"text/plain; charset=utf-8");
//httprequest.setReadTimeout(15000); //time for after connect
read = new BufferedReader(new InputStreamReader(
httprequest.getInputStream()));
strBuf = new StringBuffer();
String line = "";
while ((line = read.readLine()) != null) {
strBuf.append(line).append("\n");
}
} catch (IOException ex) {
} finally {
try {
httprequest.disconnect();
read.close();
} catch (Exception ex) {
}
}
return strBuf.toString();
}
//to assign all the info from json to activity textview or imageview
private void examineJSONFile() {
try {
String str = "";
page = executeHttpGet(url);
Log.i("hello", str.toString());
JSONObject topobj = new JSONObject(page);
JSONObject innerobj = topobj.getJSONObject("restarutant");
tvRestroName.setText("Restaurant "+innerobj.getString("name"));
String photoURL = innerobj.getString("photo");
URI uri = new URI(photoURL);
Bitmap bmp = loadBitmap(photoURL);
System.out.println("str ;" + photoURL + " uri " + uri);
imgRestro.setImageBitmap(Bitmap.createScaledBitmap(bmp, 300, 300,true));
tvRestroAddr.setText("Address: " + innerobj.getString("address"));
tvRestroArea.setText("Area: " + innerobj.getString("area"));
tvRestroCity.setText("City: " + innerobj.getString("city"));
JSONArray location = innerobj.getJSONArray("location");
String lat = location.get(0).toString();
String lng = location.get(1).toString();
latitude = Double.valueOf(lat.trim()).doubleValue();
longitude = Double.valueOf(lng.trim()).doubleValue();
System.out.println("Lat :" + latitude + " Long :" + longitude);
JSONArray phone = innerobj.getJSONArray("phone");
tvRestroPhone.setText("Phone: " + phone.get(0).toString() + " ,"
+ phone.get(1).toString());
tvRestroRating.setText("Rating: " + innerobj.getString("rating"));
JSONArray cuisines = innerobj.getJSONArray("cuisines");
tvRestroCuisines.setText("Cuisines: " + cuisines.get(0).toString()
+ " ," + cuisines.get(1).toString());
JSONArray attributes = innerobj.getJSONArray("attributes");
tvRestroAttr.setText("Attributes: " + attributes.get(0).toString()
+ " ," + attributes.get(1).toString() + " ,"
+ attributes.get(2).toString());
Log.i("hello", str.toString());
} catch (Exception je) {
tvRestroAddr.setText("Error w/file: " + je.getMessage());
}
}
// to get image from url in form of bitmap
private static Bitmap loadBitmap(String url) {
URL myFileUrl = null;
InputStream is = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
Log.i("im connected", "Download");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return BitmapFactory.decodeStream(is);
}
//for progressdialog
private class DownloadTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(InfoActivity.this);
protected void onPreExecute() {
System.out.println("In onPreExecute ");
dialog.setTitle("Loading..");
dialog.setMessage("Downloading source..");
dialog.setProgress(100);
dialog.setMax(5000);
dialog.show();
}
protected Void doInBackground(Void... unused) {
//examineJSONFile();
System.out.println("In doInBackground ");
return null;
}
protected void onPostExecute(Void unused) {
System.out.println("In onPostExecute ");
dialog.dismiss();
examineJSONFile();
}
Plz have a look and give the answer.
Thank you
You should override onProgressUpdate() method in AsyncTask and change your dialog's value there. You can send your progress value to the dialog via publishProgress() method from doInBackground(). Hope this helps.
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}