Following is my coding for downloading the data from web and on post execute I save it to DB and then update the ListAdapter for GUI.
Problem is when saving to the DB, screen freezes for the time it is getting saved in DB and for 600 records it is about 20 secs.
Please let me know, how can I change this, so that UI do not freeze.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
public DownloadWebPageTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
InputStream content = client.execute(httpGet).getEntity()
.getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
try {
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog.dismiss();
}
if((result==null)|| result.isEmpty())
{
}
else
{
if (type.equalsIgnoreCase("ALL COURSES")) {
db.deleteAllCourseByTypeDB(type);
}
else
{
db.deleteAllCourseByCategoryIdDB(category_id);
}
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data_one = jArray.getJSONObject(i);
db.deleteAllCourseCategoryByTypeDB(type);
for (int j = 0; i < jArray.length(); i++)
{
CourseDB nbnt = new CourseDB();
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(i);
String crsCd=null, crsTitle=null;
if (type.equalsIgnoreCase("Area of Training")) {
crsCd = json_data.getString("courseCd");
crsTitle = json_data.getString("courseTitle");
}
else{
crsCd = (json_data.getString("crsCd"));
crsTitle = (json_data.getString("crsTitle"));
}
nbnt.setcourse_crs(crsCd);
nbnt.setcategory_course_type(type);
nbnt.setcourse_name(crsTitle);
nbnt.setcat_foreign_id(category_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
System.out.println("date to be inseted in DB"+currentDateandTime);
nbnt.setcourse_time(currentDateandTime);
arrayofWebData.add(nbnt);
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
db.addcourseByType(nbnt, sqlDB);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
long endTime = System.currentTimeMillis();
readWebpagerating();
Collections.sort(arrayofWebData, new CourseDBComparator ());
listAdapter = new SelectArralAdapter(getActivity(),
arrayofWebData);
lv123.setAdapter(listAdapter);
lv123.setFastScrollEnabled(true);
lv123.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CourseDB planet = listAdapter.getItem(position);
String key = planet.getcourse_crs();
String KEY_ID_NOTEBOOK = db.CourseDB(key);
System.out.println("value if key_id" + KEY_ID_NOTEBOOK);
Intent intent25 = new Intent(getActivity(),
CourseDetailsActivity.class);
intent25.putExtra("course_id", key);
intent25.putExtra("category_id", category_id);
intent25.putExtra("type", type);
intent25.putExtra("category_name", category_name);
startActivity(intent25);
getActivity().finish();
}
});
}
}
}
}
catch (JSONException e) {
Log.e("log tag", "Error parsing data" + e.toString());
}
}
}
Changed Code as Suggested, screen do not freeze now, but I f I move to another screen , it crashes on the post execute.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
public DownloadWebPageTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
dbList = db.getAllCourseDBByTypes(category_id, type);
if (dbList.isEmpty())
{
System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
InputStream content = client.execute(httpGet).getEntity()
.getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("value of the response"+response);
//adding new */
if((response==null)|| response.isEmpty())
{
}
else
{
if (type.equalsIgnoreCase("ALL COURSES")) {
db.deleteAllCourseByTypeDB(type);
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
db.deleteAllCourseByCategoryIdDB(category_id);
}
JSONArray jArray;
try {
jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data_one = jArray.getJSONObject(i);
System.out.println("All the not empty");
db.deleteAllCourseCategoryByTypeDB(type);
for (int j = 0; i < jArray.length(); i++)
{
CourseDB nbnt = new CourseDB();
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(i);
String crsCd=null, crsTitle=null;
if (type.equalsIgnoreCase("Area of Training")) {
System.out.println("im area of tarinin");
crsCd = json_data.getString("courseCd");
crsTitle = json_data.getString("courseTitle");
}
else{
crsCd = (json_data.getString("crsCd"));
crsTitle = (json_data.getString("crsTitle"));
}
System.out.println("Time for one JSON parsing "
+ (System.currentTimeMillis() - insideStart));
nbnt.setcourse_crs(crsCd);
nbnt.setcategory_course_type(type);
nbnt.setcourse_name(crsTitle);
nbnt.setcat_foreign_id(category_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
System.out.println("date to be inseted in DB"+currentDateandTime);
nbnt.setcourse_time(currentDateandTime);
arrayofWebData.add(nbnt);
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
db.addcourseByType(nbnt, sqlDB);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog.dismiss();
}
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
dbList = db.getAllCourseDBByTypes(category_id, type);
if (dbList.isEmpty())
{
System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
progressDialog.dismiss();
}
}
readWebpagerating();
Collections.sort(arrayofWebData, new CourseDBComparator ());
listAdapter = new SelectArralAdapter(getActivity(),
arrayofWebData);
lv123.setAdapter(listAdapter);
lv123.setFastScrollEnabled(true);
lv123.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CourseDB planet = listAdapter.getItem(position);
String key = planet.getcourse_crs();
String KEY_ID_NOTEBOOK = db.CourseDB(key);
System.out.println("value if key_id" + KEY_ID_NOTEBOOK);
System.out.println("category id on lcick listnere inside the post ecexute" + category_id);
Intent intent25 = new Intent(getActivity(),
CourseDetailsActivity.class);
intent25.putExtra("course_id", key);
intent25.putExtra("category_id", category_id);
intent25.putExtra("type", type);
intent25.putExtra("category_name", category_name);
startActivity(intent25);
getActivity().finish();
}
});
}
}
The database operation should be done in doInBackground()
Just like LuxuryMode says, all blocking operations need to be in background.
The problem with your approach is that you put all this in Activity, lifecycle of which is not appropriate for background operations.
Create application model that lives outside (usually in Application subclass) and move your AsyncTask there. In Activities bind to that model using simple pattern like observer/callback to update your Adapter.
Related
I have an app that at launch inside onCreate method copies data from assets folder. It does it in three for cycles, each with activity indicator and the problem is that when first two cycles run white screen shows and only when third loop starts i can seen activity screen with indicator on it.
The code is following
Realm realm;
ListView list;
int[] imageidsm = {R.drawable.fon_sovety350, R.drawable.fon_german350, R.drawable.fon_usa350, R.drawable.fon_uk350, R.drawable.fon_fr_it200, R.drawable.fon_japan_china200, R.drawable.fon_history200};
String[] itemname = {"СССР", "ГЕРМАНИЯ", "США", "ВЕЛИКОБРИТАНИЯ", "ФРАНЦИЯ И ИТАЛИЯ", "ЯПОНИЯ И КИТАЙ", "ИСТОРИЯ"};
Boolean firstLaunch = false;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
MainAdapter adapter = new MainAdapter(this, itemname, imageidsm, height, width);
list = (ListView) findViewById(R.id.mainListView);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 2) {
Intent toSssr = new Intent(MainActivity.this, TankListActivity.class);
toSssr.putExtra("category", "СССР");
startActivity(toSssr);
} else if (position == 3) {
Intent listActivity = new Intent(MainActivity.this, ArticleListActivity.class);
startActivity(listActivity);
}
}
});
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name("db.realm")
.build();
realm.setDefaultConfiguration(realmConfiguration);
realm = Realm.getDefaultInstance();
preferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
firstLaunch = preferences.getBoolean("firstLaunch", false);
if (firstLaunch == false) {
firstLaunch();
}
}
public void firstLaunch() {
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json", "10f.json"};
String[] arrayOfArticles = {"32.json", "34.json", "44.json", "51.json", "33.json", "40.json", "41.json", "42.json", "52.json", "45.json", "37.json", "46.json", "36.json", "54.json", "35.json", "43.json", "47.json", "50.json", "49.json", "48.json", "56.json", "58.json", "53.json", "59.json" , "55.json", "60.json", "61.json"};
String[] arrayOfUsssr = {"62.json", "74.json", "75.json", "76.json", "63.json", "78.json", "79.json", "77.json", "81.json", "80.json"};
for (int i = 0; i < arrayOfCatLists.length; i++) {
new GetArticlesListFromDisk(arrayOfCatLists[i], i).execute();
}
for (int i = 0; i < arrayOfArticles.length; i++) {
new GetArticleFromDisk(arrayOfArticles[i]).execute();
}
for (int i = 0; i < arrayOfUsssr.length; i++) {
new GetTanksFromDisk(arrayOfUsssr[i]).execute();
}
firstLaunch = true;
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstLaunch", firstLaunch);
editor.apply();
}
private class GetArticlesListFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int index;
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json"};
private GetArticlesListFromDisk(String id, int index) {
this.id = id;
this.index = index;
}
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("listing");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String image = object.getString("image");
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(image);
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("getArticleFromDisk", "Saved article " + title);
ImageStorage.saveToSdCard(bitmap, image, getApplicationContext());
if (index == 0) {
category = "Танковые сражения";
} else if (index == 1) {
category = "Справочник танкиста";
} else if (index == 2) {
category = "Танковые асы";
} else if (index == 3) {
category = "СССР";
} else if (index == 4) {
category = "Германия";
} else if (index == 5) {
category = "США";
} else if (index == 6) {
category = "Великобритания";
}
realm.beginTransaction();
ArticleList articleList = realm.createObject(ArticleList.class);
articleList.setId(id);
articleList.setTitle(title);
articleList.setSubtitle(subtitle);
articleList.setImage(image);
articleList.setCategory(category);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetArticleFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int categoryIndex;
private GetArticleFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetArticleFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String body = object.getString("body");
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Saved article with id " + id);
realm.beginTransaction();
Article article = realm.createObject(Article.class);
article.setId(id);
article.setTitle(title);
article.setSubtitle(subtitle);
article.setBody(body);
article.setHash(hash);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetTanksFromDisk extends AsyncTask<String, Void, Tank> {
private String id;
private int categoryIndex;
private GetTanksFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetTankFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
Tank tank = new Tank();
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(LOG_TAG, "Entered preExecute");
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected Tank doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(json);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
JSONArray signatures = object.getJSONArray("signatures");
ArrayList<String> signatures_list = new ArrayList<String>();
for (int j = 0; j < signatures.length(); j++) {
signatures_list.add(signatures.get(j).toString());
}
String signatures_string = Joiner.on(",").join(signatures_list);
String body = object.getString("body");
String construction = object.getString("construction");
String modification = object.getString("modification");
String ttx = object.getString("ttx");
JSONObject images = object.getJSONObject("images");
JSONArray tank_slider = images.getJSONArray("tank_slider");
ArrayList<String> tank_slider_list = new ArrayList<String>();
for (int k = 0; k < tank_slider.length(); k++) {
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(tank_slider.getString(k));
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
ImageStorage.saveToSdCard(bitmap, tank_slider.getString(k), getApplicationContext());
tank_slider_list.add(tank_slider.getString(k));
}
String tank_slider_string = Joiner.on(",").join(tank_slider_list);
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Imported from assets tank with id " + id);
tank.setId(id);
tank.setTitle(title);
tank.setSignatures(signatures_string);
tank.setBody(body);
tank.setConstruction(construction);
tank.setModification(modification);
tank.setTtx(ttx);
tank.setTank_slider(tank_slider_string);
tank.setHash(hash);
}
} catch (JSONException e) {
e.printStackTrace();
}
return tank;
}
#Override
protected void onPostExecute(Tank tank) {
super.onPostExecute(tank);
pd.dismiss();
realm.beginTransaction();
Tank newTank = realm.createObject(Tank.class);
newTank.setId(tank.getId());
newTank.setTitle(tank.getTitle());
newTank.setSignatures(tank.getSignatures());
newTank.setBody(tank.getBody());
newTank.setConstruction(tank.getConstruction());
newTank.setModification(tank.getModification());
newTank.setTtx(tank.getTtx());
newTank.setTank_slider(tank.getTank_slider());
newTank.setHash(tank.getHash());
realm.commitTransaction();
}
}
What Im I doing wrong ?
In this activity, i get places nearby and add them to a listview. I wanted also to add the place's phone number in an arrayList like the other datas, so i had to use place details request. So, i get all the place_id for all the places from the arrayList and launch the query to get the details (phone number). The problem is in class "readFromGooglePlaceDetailsAPI", it goes in the "try" and goes out with nothing happening, i don't know why!!! I only can see "IN TRY !!!" and then "----" from the println.
Is my sequence not right?
Where is the problem and what is the solution ?
public class ListActivity extends Activity implements OnItemClickListener {
public ArrayList<GetterSetter> myArrayList;
ArrayList<GetterSetter> detailsArrayList;
ListView myList;
ProgressDialog dialog;
TextView nodata;
CustomAdapter adapter;
GetterSetter addValues;
GetterSetter addDetails;
private LocationManager locMan;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_activity);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.placesList);
placeSearch();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void placeSearch() {
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
dialog = ProgressDialog.show(this, "", "Please wait", true);
//build places query string
String placesSearchStr;
placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types="+ ServicesListActivity.types+
"&key=My_KEY";
//execute query
new readFromGooglePlaceAPI().execute(placesSearchStr);
myList.setOnItemClickListener(this);
}
public void detailsSearch() {
String detailsSearchStr;
//build places query string
for(int i=0; i < myArrayList.size(); i++){
detailsSearchStr = "https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + myArrayList.get(i).getPlace_id() +
"&key=My_KEY";
Log.d("PlaceID:", myArrayList.get(i).getPlace_id());
//execute query
new readFromGooglePlaceDetailsAPI().execute(detailsSearchStr);
}
}
public class readFromGooglePlaceDetailsAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
detailsArrayList = new ArrayList<GetterSetter>();
String phoneNumber =" -NA-";
try {
System.out.println("IN TRY !!!");
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("result");
System.out.println("Before FOR !!!");
for (int i = 0; i < results.length(); i++) {
System.out.println("IN FOR LOOP !!!");
addDetails = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
if(!arrayItems.isNull("formatted_phone_number")){
phoneNumber = arrayItems.getString("formatted_phone_number");
Log.d("Phone Number ", phoneNumber);
}
addDetails.setPhoneNumber(phoneNumber);
System.out.println("ADDED !!!");
detailsArrayList.add(addDetails);
Log.d("Before", detailsArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("------------------------------------------------------------------");
Log.d("After:", detailsArrayList.toString());
// nodata = (TextView) findViewById(R.id.nodata);
//nodata.setVisibility(View.GONE);
// adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, detailsArrayList);
// myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
// dialog.dismiss();
}
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
String rating=" -NA-";
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
addValues = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
//place ID for place details later
String placeID = arrayItems.getString("place_id").toString();
if(!arrayItems.isNull("rating")){
rating = arrayItems.getString("rating");
}
addValues.setPlace_id(placeID);
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(rating);
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
//Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
// System.out
// .println("############################################################################");
// Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
dialog.dismiss();
detailsSearch();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(ListActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
details.putExtra("formatted_phone_number", detailsArrayList.get(arg2).getPhoneNumber());
startActivity(details);
}
}
try{
JSONObject jsonObject = new JSONObject(str);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
//your logic here
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Note that the getJSONArray() function throws an Exception if the mapping fails. For example I can't find a JSON Array which is called results.
The most important thing you have to do at first is:
change:
catch (Exception e) {
}
to
catch (Exception e) {
Log.e(YOUR_TAG, "Exception ..." , e);
}
Your try throws an Exception which you don't even Log. That might be the reason why you are confused.
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
}
I am converting my HTTP calls to asynchronous calls from synchronous ones. Because the connection is running in the background the data isn't there when I originally set my list adaptor. How can I get the list adaptor to update after my HTTP call? I've tried a few things like not setting the adaptor until data gets sent back and setting the adaptor again, but nothing has worked. Here's my current oncreate code
protected void onCreate(Bundle savedInstanceState) {
overridePendingTransition(R.layout.anim_out,R.layout.anim_in);
setTheme(R.style.Theme_D_theme);
setContentView(R.layout.news_fragment);
super.onCreate(savedInstanceState);
text = (TextView) this.findViewById(R.id.nomore);
list = (ListView) this.findViewById(R.id.newslist);
list.setDividerHeight(2);
new MyAsyncTask().execute("THIS");
list.setOnItemClickListener(this);
list.setCacheColorHint(Color.WHITE);
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
}
And my AsyncTast
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}
in on post execution add this line. in the end.
x.add(temp);
adapter.notifyDataSetChanged();
Do this way
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
//UPDATE HERE
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
list.setAdapter(adapter);
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}
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;
}