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"/>
Related
I have a listview populated by the data from mysql database. It works fine but when I select an item then press back , the previous listview fecth again data from database that duplicates the items in my listview.
Here's is my code :
public class CityPage extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CityAdapter cityAdapter;
ListView listCity;
ArrayList<City> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_page);
context = this;
records = new ArrayList<City>();
listCity = (ListView) findViewById(R.id.cities);
cityAdapter = new CityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),City_attractions.class);
Toast.makeText(CityPage.this, "Opening", Toast.LENGTH_LONG).show();
String info1 = records.get(position).getCityName();
String info2 = records.get(position).getDescription();
myIntent.putExtra("info1", info1);
myIntent.putExtra("info2", info2);
startActivity(myIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
fetchCity fetch = new fetchCity();
fetch.execute();
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://iguideph-001-site1.btempurl.com/getcity.php");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 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("ERROR", "Error converting result " + e.toString());
}
//parse json data
try {
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("place_name"));
p.setDescription(json_data.getString("description"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
try remove those lines from onstart() and put them inside oncreate() function
fetchCity fetch = new fetchCity();
fetch.execute();
Good luck !
I have an issue, which is not that big, but to the user it is bad.
The app basically gets the user's input of some place and, when the user clicks on the button, a URL to the Google API with the place on its parameter is sent to an AsyncTask, where it sends this URL via HttpGet and is returned a JSONArray with everything needed. The problem is, when I click on the button and the internet is not that good, the button seems to "freeze" like this:
My activity code is below:
public class MainActivity extends Activity{
...
protected void onCreate(Bundle savedInstanceState){...}
public void onResume()}
btnSearch.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String search = txtSearch.getText().toString();
try{
List<Location> locations = new SearchTask(MainActivity.this).execute(strSearch).get();
if(locations != null){
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations);
listView.setAdapter(adapter);
...
}
}
}
}
}
}
My AsyncTask class code is below:
public class SearchTask extends AsyncTask<String, Void, List<Location>>{
...
protected List<Location> doInBackground(String... params){
if(isNetworkAvailable()){
HttpGet httpGet = null;
HttpClient client = null;
HttpResponse response = null;
StringBuilder builder = null;
try{
String param = URLDecoder.decode(params[0], "UTF-8").replace(" ", "%20");
httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?address=" + param + "&sensor=false");
client = new DefaultHttpClient();
builder = new StringBuilder();
}
catch(UnsupportedEncodingException e){
Log.i("Error", e.getMessage());
}
try{
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int val;
while((val = br.read()) != -1){
builder.append((char) val);
}
}
catch(IOException e){
Log.i("Error", e.getMessage());
}
JSONObject jsonObject = new JSONObject();
List<Location> listLocation = new ArrayList<Location>();
int countJson = 0;
try{
jsonObject = new JSONObject(builder.toString());
JSONArray jArray = jsonObject.getJSONArray("results");
countJson = jArray.length();
for(int i = 0; i < countJson; i++){
Location location = new Location();
String formattedAddress = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getString("formatted_address");
double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
location.setFormattedAddress(formattedAddress);
location.setLat(lat);
location.setLng(lng);
listLocation.add(location);
}
}
catch(JSONException e){
Log.i("Error", e.getMessage());
}
return listLocation;
}
else{
return null;
}
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progress = new ProgressDialog(context);
progress.setMessage("Loading...");
progress.show();
}
#Override
protected void onPostExecute(List<Location> result){
super.onPostExecute();
progress.dismiss();
}
private boolean isNetworkAvailable(){
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connManager.getActiveNetworkInfo();
return info != null && info.isConnected();
}
}
The ListView is on the same xml of the EditView and the Button.
Is there a way to improve it in order to make the UI not behave like this?
Thanks!
Try this:
btnSearch.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String search = txtSearch.getText().toString();
new SearchTask(MainActivity.this).execute(strSearch);
}
}
#Override
protected void onPostExecute(List<Location> locations){
if(locations != null){
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations);
listView.setAdapter(adapter);
}
progress.dismiss();
}
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(...);
}
In my activity i have an AsyncTask, in which i had overridden doInBackGround.
In the same activity i have a camera intent to open the camera and allow user to take a pic
The problem is when i call the camera intent it is triggering the doInBackGround method i overrode. Which eventually gives me a SingleClientConnManager exception which asks me to release the client before allocating it again.
Here is my activity code:
public class UserProfileActivity extends Activity {
//many instance fiels here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
new LongOperation().execute("");
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);
changeImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsLabel = (TextView) findViewById(R.id.userFriends_profile);
changeImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
//Point 1
}
});
//Point 2
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
private ProgressDialog dialog = new ProgressDialog(context);
#Override
protected String doInBackground(String... params) {
//Point 3
try {
HttpResponse response;
HttpPost httppost = new HttpPost(
"http://www.xxxxx.com/yyyy/zzzz");
//httpclient is global to maintain sessions
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) {
Log.e("error in reading input stream", e.toString());
}
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");
email = jObj.getString("email");
clickedUserId = jObj.getInt("user_id");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
friendsIds = new int[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
friendsIds[i] = friendsJsonArray.getJSONObject(i)
.getInt("user_id");
}
adapter = new ArrayAdapter<String>(context,
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
Log.d("error in creating json object", e.toString());
}
} catch (Exception e) {
//Point 5
Log.e("error main try", "Error in http connection" + e.toString());
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
changeImage.setText("Change image");
editInfo.setText("Edit");
friendsLabel.setText("Friends");
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
userImage.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
e1.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
} catch (IOException e2) {
e2.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Point 4
if (resultCode == RESULT_OK) {
if (data != null) {
photo = (Bitmap) data.getExtras().get("data");
userImage.setImageBitmap(photo);
}else{
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
}
}
here in the code Point 1, 2, 3, 4, 5 gives the sequence of code flow once i click the changeImage TextView.
Please help me in solving this scenario.
Thank You.
If I am correct the problem is because of your device orientation get changed when you open camera.That calls your activity's onCreate() method again
please insert this line to your activity in menifest that is causing problem
<activity
android:name="your activity" android:configChanges="keyboardHidden|orientation"
/>
I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}